diff --git a/crates/analysis/src/warp.rs b/crates/analysis/src/warp.rs index ee2632cb96..96f619fe47 100644 --- a/crates/analysis/src/warp.rs +++ b/crates/analysis/src/warp.rs @@ -693,6 +693,7 @@ impl Canvas { } out.copyright = r.copyright.clone(); out.white_is_zero = r.white_is_zero; + out.sample_bits = r.sample_bits; out.keep_rounded_mark(r); Ok(out) } @@ -1195,6 +1196,15 @@ mod tests { assert!(out.bands.iter().all(|b| b.data.iter().all(|v| v.fract() == 0.0))); } + #[test] + fn a_reprojected_scan_keeps_its_sample_bits() { + let mut r = scan(2, 2, vec![vec![0.0, 1.0, 1.0, 0.0]], ColorHint::Gray, "UInt8"); + r.sample_bits = Some(1); + let grid = Grid::snapped(Crs::LonLat, [0.0, 0.0, 2.0, 2.0], (1.0, 1.0), (0.0, 0.0)).unwrap(); + let out = project(&r, &grid, Method::Sample(Resampling::Nearest), "warped".into()).unwrap(); + assert_eq!(out.sample_bits, Some(1)); + } + #[test] fn rgbi_reprojection_keeps_nir_as_data_and_uses_nan_outside() { let r = scan(2, 2, vec![vec![200.0; 4], vec![100.0; 4], vec![50.0; 4], vec![0.0; 4]], ColorHint::Rgb { alpha: false }, "UInt16"); diff --git a/crates/data/src/raster/cog.rs b/crates/data/src/raster/cog.rs index ecec29aed3..ec93af2acf 100644 --- a/crates/data/src/raster/cog.rs +++ b/crates/data/src/raster/cog.rs @@ -249,6 +249,8 @@ pub struct Layout { pub lost: crate::loss::Notes, /// The file says 0 is white, as [`super::Raster::white_is_zero`]. pub white_is_zero: bool, + /// The bits a sample holds, when fewer than 8, as [`super::Raster::sample_bits`]. + pub sample_bits: Option, /// Who holds the rights to the picture (its Copyright tag), as [`super::Raster::copyright`]. pub copyright: Option, /// The file is in strips, not tiles (#2592): each level's tiles are its strips, as wide as the @@ -354,6 +356,8 @@ pub fn layout(bytes: &Sparse) -> Result { } } +/// Read the full image header without fetching its pixels, retaining the file metadata that +/// whole-file and windowed reads need to choose the same default appearance. fn read_layout(r: Sparse) -> Result { // The same bytes, to tell a tag not read yet from one that is broken. let seen = r.clone(); @@ -674,6 +678,7 @@ fn read_layout(r: Sparse) -> Result { described, lost, white_is_zero, + sample_bits: u8::try_from(bits).ok().filter(|b| matches!(b, 1 | 2 | 4)), copyright, strips, }))) diff --git a/crates/data/src/raster/cogwrite.rs b/crates/data/src/raster/cogwrite.rs index b8a2f993f8..d4c22057e7 100644 --- a/crates/data/src/raster/cogwrite.rs +++ b/crates/data/src/raster/cogwrite.rs @@ -1575,6 +1575,7 @@ impl<'a, W: Write + Seek> TileStream<'a, W> { r.overview = Some((full.w, full.h)); } r.white_is_zero = self.plan.white_is_zero; + r.sample_bits = t.sample_bits; for (b, tb) in r.bands.iter_mut().zip(&t.bands) { b.name.clone_from(&tb.name); b.wavelength = tb.wavelength; diff --git a/crates/data/src/raster/geotiff.rs b/crates/data/src/raster/geotiff.rs index 6bd8e258bb..05f621e71f 100644 --- a/crates/data/src/raster/geotiff.rs +++ b/crates/data/src/raster/geotiff.rs @@ -1978,6 +1978,7 @@ fn read_image( 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 sample_bits = u8::try_from(bits(&mut dec)).ok().filter(|b| matches!(b, 1 | 2 | 4)); let (full_w, full_h) = dec.dimensions().map_err(err)?; let geo = geo_tags(&mut dec)?; // A turned image is resampled north up whole, and one without coordinates may be placed by a @@ -2275,6 +2276,7 @@ fn read_image( 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.sample_bits = sample_bits; r.overview = overview; r.step = decimate_by.max(1); r.rounded = rounded; @@ -2370,6 +2372,7 @@ fn read_image( }; let mut r = Raster::new(name, w, h, bands, transform, crs, geo.nodata, color, data_type)?; r.white_is_zero = white_is_zero; + r.sample_bits = sample_bits; 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 }; @@ -5311,7 +5314,7 @@ mod tests { let bytes = packed_tiff(37, 21, bits, layout, lsb_first, false, pixel); let r = read(std::io::Cursor::new(&bytes), "packed").unwrap(); let at = format!("{bits} bits, {layout:?}, lsb first {lsb_first}"); - assert_eq!((r.width, r.height, r.data_type.as_str()), (37, 21, "UInt8"), "{at}"); + assert_eq!((r.width, r.height, r.data_type.as_str(), r.sample_bits), (37, 21, "UInt8", Some(bits as u8)), "{at}"); for (x, y) in [(0, 0), (1, 0), (8, 3), (36, 0), (36, 20), (17, 11)] { assert_eq!(r.value(0, i64::from(x), i64::from(y)), Some(f32::from(pixel(x, y))), "{at}: {x}, {y}"); } @@ -5908,11 +5911,13 @@ mod tests { let mut bytes = grey8(40, 16, &data, None); set_photometric(&mut bytes, 0); let r = read(std::io::Cursor::new(&bytes), "w").unwrap(); + assert_eq!(r.sample_bits, None, "8 bits a sample"); assert!(r.white_is_zero && r.color == ColorHint::Gray); assert_eq!(r.bands[0].data, data.iter().map(|v| f32::from(*v)).collect::>()); 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); + assert_eq!(layout.sample_bits, None); 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(); diff --git a/crates/data/src/raster/mod.rs b/crates/data/src/raster/mod.rs index 1f6c330162..788cf824c4 100644 --- a/crates/data/src/raster/mod.rs +++ b/crates/data/src/raster/mod.rs @@ -867,6 +867,11 @@ pub struct Raster { /// 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, + /// The bits a sample holds in the file, when fewer than 8 (a TIFF's 1, 2 or 4). One-bit grey + /// defaults to black and white; 2- and 4-bit grey can still default to classes. Reprojecting, + /// clipping and imagery commands that keep its grey keep this too. Exporting to GeoTIFF + /// writes byte or float samples, not sub-byte samples, so that copy reopens without this mark. + pub sample_bits: Option, transformer: Transformer, extent: Extent, } @@ -1057,6 +1062,7 @@ impl Raster { rounded_some: Vec::new(), copyright: None, white_is_zero: false, + sample_bits: None, transformer, extent: Extent::EMPTY, }; @@ -1333,6 +1339,7 @@ impl Raster { 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.sample_bits = self.sample_bits; (r.rounded, r.rounded_some) = (self.rounded, self.rounded_some); r }; diff --git a/crates/engine/src/cmd/imagery.rs b/crates/engine/src/cmd/imagery.rs index cf9cae1391..0de1ae403e 100644 --- a/crates/engine/src/cmd/imagery.rs +++ b/crates/engine/src/cmd/imagery.rs @@ -245,6 +245,7 @@ fn rebuild(r: &Raster, transform: GeoTransform, crs: Crs, bands: Vec>) o.wavelength = i.wavelength; } out.white_is_zero = r.white_is_zero; + out.sample_bits = r.sample_bits; Ok(out) } @@ -2019,6 +2020,7 @@ fn resample_whole(r: &super::workflows::Input, factor: u32, out: String) -> Resu let color = if matches!(r.color, ColorHint::Palette(_)) { ColorHint::Gray } else { r.color.clone() }; let mut out = Raster::new(out, w, h, bands, gt, r.crs, nodata, color, r.data_type.clone()).map_err(|e| e.to_string())?; out.white_is_zero = r.white_is_zero; + out.sample_bits = r.sample_bits; // A block's mean is of the same band: its name and wavelength are the input's. out.bands.iter_mut().zip(&r.bands).for_each(|(o, i)| { o.name = i.name.clone(); @@ -2112,6 +2114,7 @@ fn resample_in_blocks( let mut res = Raster::new(out, w, h, res, t.transform, t.crs, t.nodata, t.color.clone(), t.data_type.clone()).map_err(|e| e.to_string())?; res.white_is_zero = t.white_is_zero; + res.sample_bits = t.sample_bits; res.bands.iter_mut().zip(&t.bands).for_each(|(o, i)| { o.name.clone_from(&i.name); o.wavelength = i.wavelength; @@ -2282,6 +2285,7 @@ fn resampled_as(read: &rustgis_data::raster::PartRead, k: u32, out: &str) -> Res o.wavelength = i.wavelength; }); t.white_is_zero = r.white_is_zero; + t.sample_bits = r.sample_bits; Ok(t) } @@ -2520,6 +2524,7 @@ impl Tiles { }); out.copyright = first.copyright.clone(); out.white_is_zero = first.white_is_zero; + out.sample_bits = first.sample_bits.filter(|bits| rs.iter().all(|r| r.sample_bits == Some(*bits))); // The first input's metadata accompanies its pixels; report other credits rather than // silently dropping them or attributing every input to the first one's owner. let credits = rs @@ -2761,6 +2766,7 @@ fn clip_window( band.wavelength = r.bands.get(i).and_then(|b| b.wavelength); } out.white_is_zero = r.white_is_zero; + out.sample_bits = r.sample_bits; // Some of the values rounded when the file was read may be in the window: how many isn't known. out.keep_rounded_mark(r); // What reading the input left out was said, with its code, when the input was read: a clip, @@ -2936,6 +2942,7 @@ fn edit_pixels(s: &mut Session, p: &Value) -> CmdResult { o.wavelength = i.wavelength; }); out.white_is_zero = r.white_is_zero; + out.sample_bits = r.sample_bits; // The edit may have overwritten some of the values rounded when the file was read. out.keep_rounded_mark(&r); replace(s, &layer, out)?; @@ -3345,6 +3352,7 @@ pub(crate) fn mosaic_work(s: &Session, p: &Value) -> Result = (!messages.is_empty()).then(|| { @@ -3775,3 +3783,28 @@ fn a_resampled_pixel_with_alpha_is_weighted_by_it() { let grey = Raster::new("grey", 4, 1, vec![vec![0.0, 4.0, 8.0, 0.0]], gt, Crs::LonLat, Some(0.0), ColorHint::Gray, "UInt8").unwrap(); assert_eq!(resample_mean(&grey, 0, alpha_band(&grey), all(), -1.0), 6.0, "no alpha: no-data left out"); } + +/// The overview used to style a file-backed resample keeps the scan's bit depth; the float +/// file itself has no sub-byte samples when reopened independently. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_written_resample_overview_keeps_one_bit_style() { + use rustgis_data::raster::cogwrite::{Samples, TileStream}; + use rustgis_map::raster::Colorizer; + use rustgis_map::{RasterRenderer, RasterStyle, Stretch}; + let gt = GeoTransform { origin_x: 10.0, origin_y: 46.0, pixel_width: 0.001, pixel_height: -0.001 }; + let mut template = Raster::new("scan", 2, 1, vec![vec![0.0, 1.0]], gt, Crs::LonLat, None, ColorHint::Gray, "UInt8").unwrap(); + template.sample_bits = Some(1); + let mut file = std::io::Cursor::new(Vec::new()); + let mut stream = TileStream::new(&template, 2, 1, Samples::Floats, &mut file).unwrap().keeping(2); + stream.put(&[0.0, 1.0]).unwrap(); + let (_, overview) = stream.finish().unwrap(); + let overview = overview.unwrap(); + assert_eq!(overview.sample_bits, Some(1)); + let style = RasterStyle::default_for(&overview); + assert!(matches!(style.renderer, RasterRenderer::Stretch { band: 0, .. }) && style.stretch == Stretch::MinMax, "{style:?}"); + let c = Colorizer::new(&style, &overview, None); + assert_eq!([0.0, 1.0].map(|v| c.color(&[v], None).unwrap()), [[0, 0, 0, 255], [255, 255, 255, 255]]); + let reopened = raster::geotiff::read(std::io::Cursor::new(file.into_inner()), "reopened").unwrap(); + assert_eq!((reopened.data_type.as_str(), reopened.sample_bits), ("Float32", None)); +} diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index ed16461bea..d611f05b1e 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -6989,6 +6989,7 @@ pub(crate) fn read_window_raster(asked: &WindowAsked, stop: &std::sync::atomic:: rustgis_data::raster::Raster::new(&name, width, height, bands, transform, layout.crs, layout.nodata, color, layout.data_type) .map_err(|e| named(e.to_string()))?; r.white_is_zero = layout.white_is_zero; + r.sample_bits = layout.sample_bits; if rounded.iter().any(|n| *n > 0) { r.rounded = rounded; } diff --git a/crates/map/src/raster.rs b/crates/map/src/raster.rs index 1a4e7627ed..5513378986 100644 --- a/crates/map/src/raster.rs +++ b/crates/map/src/raster.rs @@ -2509,9 +2509,10 @@ impl RasterStyle { /// The default look, as the file's PhotometricInterpretation says: the file's colours, RGB for /// colour images and for grey ones of exactly three bands (most remote sensing images are - /// grey, whatever their bands: three are taken as red, green and blue), unique values for a - /// few categories, otherwise a grey stretch of the first band (an image of more bands is - /// combined as the user picks). + /// grey, whatever their bands: three are taken as red, green and blue), black and white for + /// one-bit grey (with or without alpha), + /// unique values for a few categories, otherwise a grey stretch of the first band (an image of + /// more bands is combined as the user picks). pub fn default_for(r: &Raster) -> RasterStyle { RasterStyle::default_with(r, &RasterDefaults::default()) } @@ -2520,12 +2521,20 @@ impl RasterStyle { /// stretch. pub fn default_with(r: &Raster, d: &RasterDefaults) -> RasterStyle { let byte_rgb = r.data_type == "UInt8"; - let (renderer, stretch) = match &r.color { - ColorHint::Palette(_) => (RasterRenderer::Colormap, Stretch::None), - ColorHint::Rgb { .. } if r.band_count() >= 3 => { + let (renderer, stretch) = match (&r.color, r.sample_bits) { + (ColorHint::Palette(_), _) => (RasterRenderer::Colormap, Stretch::None), + (ColorHint::Rgb { .. }, _) if r.band_count() >= 3 => { (RasterRenderer::Rgb { red: 0, green: 1, blue: 2 }, if byte_rgb { Stretch::None } else { Stretch::default() }) } - ColorHint::Gray if r.band_count() == 3 => (RasterRenderer::Rgb { red: 0, green: 1, blue: 2 }, Stretch::default()), + (ColorHint::Gray, _) if r.band_count() == 3 => (RasterRenderer::Rgb { red: 0, green: 1, blue: 2 }, Stretch::default()), + // One-bit grey is black and white, including a scan warped with alpha. Two- and + // four-bit grey can be classifications, so they keep the usual default below. + (ColorHint::Gray, Some(1)) if r.band_count() == 1 => { + (RasterRenderer::Stretch { band: 0, ramp: Ramp::gray(), invert: false }, Stretch::MinMax) + } + (ColorHint::GrayAlpha, Some(1)) if r.band_count() == 2 => { + (RasterRenderer::Stretch { band: 0, ramp: Ramp::gray(), invert: false }, Stretch::MinMax) + } _ => match r.bands.first().and_then(|b| b.stats.categories.as_ref()).filter(|c| c.len() <= 16 && r.data_type.contains("Int")) { Some(_) => (unique_values(r, 0, Ramp::Harbour), Stretch::None), None => (RasterRenderer::Stretch { band: 0, ramp: d.ramp.clone(), invert: d.invert }, d.stretch), @@ -2670,10 +2679,18 @@ impl Normalizer { /// what isn't alike at both ends, so it draws as it would the values mirrored: a percent clip's /// low end is the dark one, and equalization counts from the top. pub fn drawn(style: &RasterStyle, r: &Raster, channel: usize, s: &BandStats) -> Normalizer { + let mut n = Normalizer::for_channel(style.stretch, channel, s, &r.data_type); + // A blank low-bit picture still reaches black or white. Keep MinMax in its saved style + // so reopening a MinIsWhite file doesn't mistake the default for pre-0.10 custom bounds. + if style.stretch == Stretch::MinMax + && (s.min == s.max || !s.min.is_finite() || !s.max.is_finite()) + && let Some(bits @ (1 | 2 | 4)) = r.sample_bits + { + (n.lo, n.hi) = (0.0, f64::from((1u32 << bits) - 1)); + } if !r.white_is_zero || !matches!(style.renderer, RasterRenderer::Stretch { .. }) { - return Normalizer::for_channel(style.stretch, channel, s, &r.data_type); + return n; } - let mut n = Normalizer::for_channel(style.stretch, channel, s, &r.data_type); if matches!(style.stretch, Stretch::PercentClip { .. }) { // From the statistics of the values mirrored about 0: a percentile counts up from the // low end, so one counted down isn't another percentage counted up where values tie. @@ -3685,6 +3702,86 @@ mod tests { std::fs::remove_file(&path).unwrap(); } + /// A 1-bit grey picture opens black and white, including a warped scan with alpha; + /// grey files of 2 or 4 bits with few values still open as classes. + #[test] + fn a_one_bit_scan_is_black_and_white() { + let gt = GeoTransform { origin_x: 0.0, origin_y: 2.0, pixel_width: 1.0, pixel_height: -1.0 }; + let mut r = Raster::new("scan", 2, 2, vec![vec![0.0, 1.0, 1.0, 0.0]], gt, Crs::LonLat, None, ColorHint::Gray, "UInt8").unwrap(); + assert!(matches!(RasterStyle::default_for(&r).renderer, RasterRenderer::UniqueValues { .. }), "classes, from no file"); + for bits in [2, 4] { + r.sample_bits = Some(bits); + assert!(matches!(RasterStyle::default_for(&r).renderer, RasterRenderer::UniqueValues { .. }), "{bits}-bit classes"); + } + r.sample_bits = Some(1); + let style = RasterStyle::default_for(&r); + assert!(matches!(style.renderer, RasterRenderer::Stretch { .. }) && style.stretch == Stretch::MinMax, "{style:?}"); + let drawn = |r: &Raster| { + let c = Colorizer::new(&style, r, None); + [0.0, 1.0].map(|v| c.color(&[v], None).unwrap()) + }; + assert_eq!(drawn(&r), [[0, 0, 0, 255], [255, 255, 255, 255]]); + r.white_is_zero = true; + assert_eq!(drawn(&r), [[255, 255, 255, 255], [0, 0, 0, 255]]); + for value in [0.0, 1.0] { + let mut constant = + Raster::new("blank scan", 2, 2, vec![vec![value; 4]], gt, Crs::LonLat, None, ColorHint::Gray, "UInt8").unwrap(); + constant.sample_bits = Some(1); + for white_is_zero in [false, true] { + constant.white_is_zero = white_is_zero; + let style = RasterStyle::default_for(&constant); + assert_eq!(style.stretch, Stretch::MinMax); + let c = Colorizer::new(&style, &constant, None); + let expected = if (value == 1.0) != white_is_zero { 255 } else { 0 }; + assert_eq!(c.color(&[value], None), Some([expected, expected, expected, 255])); + } + } + // A palette file keeps its colours. + r.color = ColorHint::Palette(vec![[200, 0, 0, 255], [0, 0, 200, 255]]); + assert_eq!(RasterStyle::default_for(&r).renderer, RasterRenderer::Colormap); + } + + #[test] + fn a_one_bit_scan_with_alpha_is_black_and_white() { + let gt = GeoTransform { origin_x: 0.0, origin_y: 2.0, pixel_width: 1.0, pixel_height: -1.0 }; + let mut with_alpha = Raster::new( + "warped scan", + 2, + 2, + vec![vec![0.0, 1.0, 1.0, 0.0], vec![255.0, 255.0, 0.0, 0.0]], + gt, + Crs::LonLat, + None, + ColorHint::GrayAlpha, + "UInt8", + ) + .unwrap(); + with_alpha.sample_bits = Some(1); + let style = RasterStyle::default_for(&with_alpha); + assert!(matches!(style.renderer, RasterRenderer::Stretch { band: 0, .. }) && style.stretch == Stretch::MinMax, "{style:?}"); + let c = Colorizer::new(&style, &with_alpha, None); + assert_eq!([0.0, 1.0].map(|v| c.color(&[v], None).unwrap()), [[0, 0, 0, 255], [255, 255, 255, 255]]); + } + + #[test] + fn a_constant_one_bit_white_is_zero_scan_needs_no_range_warning() { + let gt = GeoTransform { origin_x: 0.0, origin_y: 2.0, pixel_width: 1.0, pixel_height: -1.0 }; + let mut r = Raster::new("blank", 2, 2, vec![vec![1.0; 4]], gt, Crs::LonLat, None, ColorHint::Gray, "UInt8").unwrap(); + r.sample_bits = Some(1); + r.white_is_zero = true; + let mut layer = RasterLayer::from_path(r.clone(), "blank.tif"); + assert_eq!(layer.style.stretch, Stretch::MinMax); + assert!(layer.lost_unsaid().is_empty()); + // As a saved layer's pixels land: computed bounds are safe, custom bounds still need a look. + for (stretch, said) in [(Stretch::MinMax, false), (Stretch::custom(0.0, 1.0), true), (Stretch::custom(0.0, 2.0), true)] { + layer.style.stretch = stretch; + layer.data = None; + layer.values_checked = false; + layer.land(Ok(Arc::new(r.clone()))); + assert_eq!(layer.lost_unsaid().iter().any(|n| format!("{n:?}").contains("0 is white")), said); + } + } + /// A file whose 0 is white draws its lowest value white, its legend the same way round, and an /// inverted ramp the other way; a saved style that names values is said to need a look, one /// worked out from the pixels isn't (#2761). diff --git a/crates/tiles/src/cog/raster.rs b/crates/tiles/src/cog/raster.rs index 3b418e234c..5d898429d0 100644 --- a/crates/tiles/src/cog/raster.rs +++ b/crates/tiles/src/cog/raster.rs @@ -159,6 +159,7 @@ fn read_overview(info: Arc, url: String, done: Box