Skip to content
1 change: 1 addition & 0 deletions crates/analysis/src/warp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -692,6 +692,7 @@ impl Canvas {
}
}
out.copyright = r.copyright.clone();
out.white_is_zero = r.white_is_zero;
out.keep_rounded_mark(r);
Ok(out)
}
Expand Down
4 changes: 4 additions & 0 deletions crates/data/src/raster/cog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,8 @@ pub struct Layout {
/// a colour table too short for its pixels. One line each, for a window to say (AGENTS.md,
/// Never silent); drawing in place shows the file grey without them, as before.
pub lost: crate::loss::Notes,
/// The file says 0 is white, as [`super::Raster::white_is_zero`].
pub white_is_zero: bool,
/// Who holds the rights to the picture (its Copyright tag), as [`super::Raster::copyright`].
pub copyright: Option<String>,
/// The file is in strips, not tiles (#2592): each level's tiles are its strips, as wide as the
Expand Down Expand Up @@ -364,6 +366,7 @@ fn read_layout(r: Sparse) -> Result<Parse> {
// An RGB image with more bands (shown to the decoder as grey, see `Unpaletted`): every band,
// the first three red, green and blue.
let wide_rgb = rd.first_is_wide_rgb();
let white_is_zero = rd.first_white_is_zero();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
let mut dec = Decoder::new(rd).map_err(err)?.with_limits(limits());
let Some(geo) = super::geotiff::cog_geo(&mut dec)? else {
return Ok(Parse::NotTiled("a rotated image, or one without coordinates, is read whole".into()));
Expand Down Expand Up @@ -670,6 +673,7 @@ fn read_layout(r: Sparse) -> Result<Parse> {
palette,
described,
lost,
white_is_zero,
copyright,
strips,
})))
Expand Down
30 changes: 24 additions & 6 deletions crates/data/src/raster/cogwrite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,8 @@ struct Plan {
palette: Option<Vec<[u8; 4]>>,
/// Classes (a palette's, or few whole numbers): overviews take a pixel, never an average.
categorical: bool,
/// Grey with 0 as white ([`Raster::white_is_zero`]).
white_is_zero: bool,
}

/// Whether band `b` holds whole numbers of a 16-bit type, and its no-data value (if any) is one.
Expand Down Expand Up @@ -183,6 +185,7 @@ fn plan(r: &Raster, band: usize) -> Result<Plan> {
nodata_int: int_nodata(max),
palette: None,
categorical: false,
white_is_zero: false,
});
}
}
Expand All @@ -196,13 +199,23 @@ fn plan(r: &Raster, band: usize) -> Result<Plan> {
nodata_int: None,
palette: None,
categorical: false,
white_is_zero: false,
});
}
if matches!(r.color, ColorHint::GrayAlpha) && r.bands.len() >= 2 {
let sample = sample_of(&[0, 1]).unwrap_or(Sample::Float);
let max = if sample == Sample::Byte { 255.0 } else { 65_535.0 };
let nodata_int = if sample == Sample::Float { None } else { int_nodata(max) };
return Ok(Plan { bands: vec![0, 1], sample, rgb: false, alpha: Some(1), nodata_int, palette: None, categorical: false });
return Ok(Plan {
bands: vec![0, 1],
sample,
rgb: false,
alpha: Some(1),
nodata_int,
palette: None,
categorical: false,
white_is_zero: r.white_is_zero,
});
}
let b = r.bands.get(band).ok_or_else(|| err(format!("the raster has no band {}", band + 1)))?;
if let ColorHint::Palette(colors) = &r.color {
Expand All @@ -227,6 +240,7 @@ fn plan(r: &Raster, band: usize) -> Result<Plan> {
nodata_int,
palette: Some(colors.clone()),
categorical: true,
white_is_zero: false,
});
}
let all_valid = b.stats.count == r.width as usize * r.height as usize;
Expand All @@ -246,6 +260,7 @@ fn plan(r: &Raster, band: usize) -> Result<Plan> {
nodata_int: if sample == Sample::Float { None } else { int_nodata(max) },
palette: None,
categorical,
white_is_zero: r.white_is_zero,
})
}

Expand Down Expand Up @@ -517,6 +532,8 @@ fn entries(r: &Raster, plan: &Plan, lv: &Level, first: bool, geo: &GeoKeys, big:
3
} else if plan.rgb {
2
} else if plan.white_is_zero {
0
} else {
1
}],
Expand Down Expand Up @@ -789,7 +806,7 @@ pub(super) struct Strips {
/// Samples to a pixel, interleaved.
pub spp: u16,
pub sample: Sample,
/// PhotometricInterpretation: 1 for grey, 2 for RGB.
/// PhotometricInterpretation: 1 for grey (0 when 0 is white), 2 for RGB.
pub photometric: u16,
/// The ExtraSamples values of the samples past the grey or colour ones (none to leave it out).
pub extra: Vec<u16>,
Expand Down Expand Up @@ -1204,7 +1221,7 @@ impl<'a, W: Write + Seek> TileStream<'a, W> {
Self::most_bands()
)));
}
let plan = stream_plan(bytes, template.nodata, n, &template.color);
let plan = stream_plan(bytes, template.nodata, n, &template.color, template.white_is_zero);
// With alpha, alpha says which pixels have a value, as [`write_to`] writes it: no no-data
// value is written, a pixel with none is see-through, its colours what they are (a black
// one stays black), and an integer template's alpha is held on a float's scale, opaque
Expand Down Expand Up @@ -1557,6 +1574,7 @@ impl<'a, W: Write + Seek> TileStream<'a, W> {
if level > 0 {
r.overview = Some((full.w, full.h));
}
r.white_is_zero = self.plan.white_is_zero;
for (b, tb) in r.bands.iter_mut().zip(&t.bands) {
b.name.clone_from(&tb.name);
b.wavelength = tb.wavelength;
Expand All @@ -1568,8 +1586,8 @@ impl<'a, W: Write + Seek> TileStream<'a, W> {
/// What a [`TileStream`] writes: `n` bands of 32-bit floats, or with `bytes` one band of bytes
/// whose no-data value is `nodata`, averaged in its overviews; red, green and blue first for an
/// RGB `color` of three bands or more (the fourth alpha when it says so), grey and alpha first for
/// grey and alpha, else grey, the further bands nothing in particular.
fn stream_plan(bytes: bool, nodata: Option<f64>, n: usize, color: &ColorHint) -> Plan {
/// grey and alpha, else grey (0 as white with `white_is_zero`), the further bands nothing in particular.
fn stream_plan(bytes: bool, nodata: Option<f64>, n: usize, color: &ColorHint, white_is_zero: bool) -> Plan {
let (sample, nodata_int) = match bytes {
true => (Sample::Byte, nodata.filter(|d| (0.0..=255.0).contains(d)).map(|d| d as u16)),
false => (Sample::Float, None),
Expand All @@ -1579,7 +1597,7 @@ fn stream_plan(bytes: bool, nodata: Option<f64>, n: usize, color: &ColorHint) ->
ColorHint::GrayAlpha if n >= 2 => (false, Some(1)),
_ => (false, None),
};
Plan { bands: (0..n).collect(), sample, rgb, alpha, nodata_int, palette: None, categorical: false }
Plan { bands: (0..n).collect(), sample, rgb, alpha, nodata_int, palette: None, categorical: false, white_is_zero }
}

/// How a [`TileStream`] holds a pixel's value in its file: `given` (the template's no-data, or
Expand Down
93 changes: 85 additions & 8 deletions crates/data/src/raster/geotiff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -812,6 +812,9 @@ fn samples<R: Read + Seek>(dec: &mut Decoder<R>) -> usize {
/// every sample is decoded. The only change is the PhotometricInterpretation value (→ 1) in each
/// such image's IFD, in memory.
///
/// So is a grey image whose 0 is white (MinIsWhite, 0): the `tiff` crate inverts its samples, and
/// they are read as stored, the picture inverted as it is drawn (`Raster::white_is_zero`, #2761).
///
/// It also shows a SampleFormat of 4 ("undefined", which CBERS-4 scenes have) as 1, unsigned, as
/// libtiff and GDAL read it: the `tiff` crate refuses to decode it (#2593).
pub(crate) struct Unpaletted<R> {
Expand All @@ -823,6 +826,8 @@ pub(crate) struct Unpaletted<R> {
/// Whether the first image is an RGB image with samples past the colour ones (shown to the
/// decoder as grey): its first three samples are red, green and blue, every sample read.
first_wide_rgb: bool,
/// Whether the first image is grey with 0 as white.
first_white_is_zero: bool,
pos: u64,
}

Expand All @@ -834,13 +839,13 @@ const MAX_ENTRIES: u64 = 4096;
/// samples past the colour ones (which the decoder would leave out, or refuse), walking the IFD
/// chain (classic and BigTIFF). A file it can't walk has none: the decoder reports what's wrong.
/// Each SampleFormat value of 4 (undefined) is patched to 1 too, in the entry or in the array it
/// points to (#2593). Returns the patches, whether the first image is a palette image, and whether
/// it is such an RGB image.
fn palette_patches<R: Read + Seek>(r: &mut R) -> (Vec<(u64, [u8; 2])>, bool, bool) {
/// points to (#2593). Returns the patches, whether the first image is a palette image, whether it is
/// such an RGB image, and whether it is grey with 0 as white.
fn palette_patches<R: Read + Seek>(r: &mut R) -> (Vec<(u64, [u8; 2])>, bool, bool, bool) {
use std::io::SeekFrom;
let mut patches = Vec::new();
// Whether the first image is one of them, and whether it is an RGB image with more samples.
let (mut first, mut first_wide) = (false, false);
let (mut first, mut first_wide, mut first_white) = (false, false, false);
let mut walk = || -> Option<()> {
let mut head = [0u8; 16];
r.seek(SeekFrom::Start(0)).ok()?;
Expand Down Expand Up @@ -922,6 +927,10 @@ fn palette_patches<R: Read + Seek>(r: &mut R) -> (Vec<(u64, [u8; 2])>, bool, boo
patches.push((at, one));
first |= k == 0;
}
Some((at, 0)) => {
patches.push((at, one));
first_white |= k == 0;
}
// An RGB image whose fourth sample isn't alpha, or with five or more: RGBI
// orthophotos, multispectral images.
Some((at, 2)) if samples > 4 || (samples == 4 && !matches!(extra, Some(1 | 2))) => {
Expand Down Expand Up @@ -949,7 +958,7 @@ fn palette_patches<R: Read + Seek>(r: &mut R) -> (Vec<(u64, [u8; 2])>, bool, boo
Some(())
};
let _ = walk();
(patches, first, first_wide)
(patches, first, first_wide, first_white)
}

/// Any reader, boxed: the decoder is compiled once for every kind of source (a file, bytes in
Expand All @@ -972,6 +981,12 @@ impl<R> Unpaletted<R> {
self.first_palette
}

/// Whether the first image is grey with 0 as white (PhotometricInterpretation 0), shown as
/// grey with 0 as black.
pub(crate) fn first_white_is_zero(&self) -> bool {
self.first_white_is_zero
}

/// Whether the first image is an RGB image with more samples than its colours.
pub(crate) fn first_is_wide_rgb(&self) -> bool {
self.first_wide_rgb
Expand All @@ -980,9 +995,9 @@ impl<R> Unpaletted<R> {

impl<R: Read + Seek> Unpaletted<R> {
fn new(mut inner: R) -> std::io::Result<Self> {
let (patches, first_palette, first_wide_rgb) = palette_patches(&mut inner);
let (patches, first_palette, first_wide_rgb, first_white_is_zero) = palette_patches(&mut inner);
inner.seek(std::io::SeekFrom::Start(0))?;
Ok(Unpaletted { inner, patches, first_palette, first_wide_rgb, pos: 0 })
Ok(Unpaletted { inner, patches, first_palette, first_wide_rgb, first_white_is_zero, pos: 0 })
}
}

Expand Down Expand Up @@ -1801,6 +1816,7 @@ fn read_image(
// overviews of it.
let palette = r.first_is_palette();
let wide_rgb = r.first_is_wide_rgb();
let white_is_zero = r.first_white_is_zero();
let limits = limits();
let mut dec = Decoder::new(r).map_err(err)?.with_limits(limits.clone());
let (full_w, full_h) = dec.dimensions().map_err(err)?;
Expand Down Expand Up @@ -2102,6 +2118,7 @@ fn read_image(
if !geo.referenced {
let mut r = Raster::new(name, w, h, bands, super::unreferenced(w, h), Crs::LonLat, geo.nodata, color, data_type)?;
r.georeferenced = false;
r.white_is_zero = white_is_zero;
r.overview = overview;
r.step = decimate_by.max(1);
r.rounded = rounded;
Expand Down Expand Up @@ -2197,6 +2214,7 @@ fn read_image(
None => (w, h, overview),
};
let mut r = Raster::new(name, w, h, bands, transform, crs, geo.nodata, color, data_type)?;
r.white_is_zero = white_is_zero;
r.overview = overview;
// A turned image is resampled to a grid of its own: its pixels are no longer the file's.
r.step = if geo.affine.is_none() { decimate_by.max(1) } else { 1 };
Expand Down Expand Up @@ -2456,7 +2474,7 @@ fn encode(r: &Raster, band: usize, every: bool, out: &mut (impl std::io::Write +
h,
spp: u16::try_from(colour + extra.len()).map_err(|_| err("a TIFF holds at most 65,535 bands"))?,
sample,
photometric: if rgb { 2 } else { 1 },
photometric: if rgb { 2 } else { u16::from(!r.white_is_zero) },
extra,
classes: matches!(written, [b] if r.bands.get(*b).is_some_and(few_classes)),
tags: geo_entries(r, &geo, written, nodata_tag()),
Expand Down Expand Up @@ -5456,6 +5474,65 @@ mod tests {
out
}

/// A grey image whose 0 is white has its values as stored, whole and in place, whichever
/// decoder reads its chunks, and no-data matched with them; the flag says how to draw it (#2761).
#[test]
fn white_is_zero_values_are_read_as_stored() {
use super::super::cog;
let data: Vec<u8> = (0..40 * 16).map(|i| (i * 7 % 251) as u8).collect();
let mut bytes = grey8(40, 16, &data, None);
set_photometric(&mut bytes, 0);
let r = read(std::io::Cursor::new(&bytes), "w").unwrap();
assert!(r.white_is_zero && r.color == ColorHint::Gray);
assert_eq!(r.bands[0].data, data.iter().map(|v| f32::from(*v)).collect::<Vec<_>>());
let header = Sparse::default().with(0, bytes.clone());
let cog::Parse::Done(mut layout) = cog::layout(&header).unwrap() else { panic!("not read in place") };
assert!(layout.white_is_zero);
layout.nodata = Some(f64::from(data[1]));
let (at, n) = (layout.levels[0].offsets[0] as usize, layout.levels[0].counts[0] as usize);
let strip = cog::decode_tile(&header, &layout, 0, 0, bytes[at..at + n].to_vec()).unwrap();
assert_eq!(strip[0][2], f32::from(data[2]));
assert!(strip[0][1].is_nan(), "no-data is a stored value");
// LZW, by our decoder too, which refused such an image before.
let pixel = |x: u32, y: u32| (x * 3 + y) as f32;
let mut lzw = lzw_tiled(300, 170, 128, 1, pixel);
set_photometric(&mut lzw, 0);
let r = read(std::io::Cursor::new(&lzw), "w").unwrap();
assert!(r.white_is_zero);
assert_eq!(r.value(0, 299, 169), Some(pixel(299, 169)));
let mut dec = Decoder::new(reader(std::io::Cursor::new(&lzw)).unwrap()).unwrap();
let DecodingResult::F32(ours) = super::super::lzw::chunk(&mut dec, 0).unwrap() else { panic!("not Float32") };
assert_eq!(ours[129], pixel(1, 1));
// Every overview too, whether it says 0 is white or, as some writers have it, isn't.
for overview in [0, 1] {
let mut two = std::io::Cursor::new(Vec::new());
{
use tiff::encoder::{TiffEncoder, colortype};
let mut enc = TiffEncoder::new(&mut two).unwrap();
for (side, photometric) in [(64u32, 0u16), (32, overview)] {
let mut img = enc.new_image::<colortype::Gray8>(side, side).unwrap();
let e = img.encoder();
if side == 32 {
e.write_tag(Tag::NewSubfileType, 1u32).unwrap();
}
e.write_tag(Tag::PhotometricInterpretation, photometric).unwrap();
img.write_data(&(0..side * side).map(|i| (i % 251) as u8).collect::<Vec<_>>()).unwrap();
}
}
let r = read_limited(reader(std::io::Cursor::new(two.into_inner())).unwrap(), "o", 2_000, None).unwrap();
assert_eq!((r.width, r.white_is_zero, r.value(0, 3, 0)), (32, true, Some(3.0)), "overview {overview}");
}
// Written again, plain or cloud-optimised, the file says so still, and holds the values.
let r = read(std::io::Cursor::new(&bytes), "w").unwrap();
for out in [write(&r, 0).unwrap(), super::super::cogwrite::write(&r, 0).unwrap()] {
let back = read(std::io::Cursor::new(&out), "back").unwrap();
assert!(back.white_is_zero);
assert_eq!(back.bands[0].data, r.bands[0].data);
}
// 0 as black says nothing.
assert!(!read(std::io::Cursor::new(&grey8(40, 16, &data, None)), "b").unwrap().white_is_zero);
}

/// The chunks a sparse file leaves out are no-data read whole, with one thread or several,
/// whole or every k-th pixel, compressed or not, and the image keeps its type (#2761).
#[test]
Expand Down
4 changes: 0 additions & 4 deletions crates/data/src/raster/lzw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,6 @@ pub(crate) fn chunk<R: Read + Seek>(dec: &mut Decoder<R>, index: u32) -> Result<
let planar = tag(dec, Tag::PlanarConfiguration) == Some(2);
let samples = if planar { 1 } else { spp };
let predictor = tag(dec, Tag::Predictor).unwrap_or(1);
// WhiteIsZero samples are inverted by the crate; left to it.
if tag(dec, Tag::PhotometricInterpretation) == Some(0) {
return Err(err("WhiteIsZero LZW images aren't supported"));
}

// Where the chunk is in its plane, and how much of it is image.
let across = w.div_ceil(cw);
Expand Down
5 changes: 5 additions & 0 deletions crates/data/src/raster/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -849,6 +849,9 @@ pub struct Raster {
/// when this raster is exported; a raster made from it (clipped, reprojected) starts
/// without.
pub copyright: Option<String>,
/// The file says 0 is white (a TIFF's MinIsWhite): the values are as stored, and a stretch of
/// them is drawn the other way round. A raster with other values made from it starts without.
pub white_is_zero: bool,
transformer: Transformer,
extent: Extent,
}
Expand Down Expand Up @@ -1030,6 +1033,7 @@ impl Raster {
rounded: Vec::new(),
rounded_some: Vec::new(),
copyright: None,
white_is_zero: false,
transformer,
extent: Extent::EMPTY,
};
Expand Down Expand Up @@ -1294,6 +1298,7 @@ impl Raster {
let exact = (r.transform.pixel_width.abs() / (f64::from(self.step) * file_cell) - 1.0).abs() < 1e-9;
r.step = if exact { self.step } else { 1 };
(r.source, r.lost, r.copyright) = (self.source, self.lost, self.copyright);
r.white_is_zero = self.white_is_zero;
(r.rounded, r.rounded_some) = (self.rounded, self.rounded_some);
r
};
Expand Down
2 changes: 2 additions & 0 deletions crates/data/src/raster/world.rs
Original file line number Diff line number Diff line change
Expand Up @@ -394,10 +394,12 @@ mod tests {
let mut r = crate::raster::read_path_unplaced(&dir.join("p.png"), None, None).unwrap();
r.bands[0].name = "landcover".into();
r.bands[0].classes = vec!["water".into(), "forest".into()];
r.white_is_zero = true;
let wf = WorldFile::parse("0\n-1\n-1\n0\n11.5\n49.5\n").unwrap();
let r = r.placed_by_world_file(&wf, crate::raster::Crs::LonLat).map_err(|(_, e)| e).unwrap();
assert_eq!((r.width, r.height), (2, 4));
assert_eq!((r.bands[0].name.as_str(), r.bands[0].classes.len()), ("landcover", 2));
assert!(r.white_is_zero, "0 stays white");
std::fs::remove_dir_all(&dir).unwrap();
}

Expand Down
Loading
Loading