Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions crates/analysis/src/warp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
out.keep_rounded_mark(r);
Ok(out)
}
Expand Down Expand Up @@ -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");
Expand Down
5 changes: 5 additions & 0 deletions crates/data/src/raster/cog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u8>,
/// 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 @@ -354,6 +356,8 @@ pub fn layout(bytes: &Sparse) -> Result<Parse> {
}
}

/// 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<Parse> {
// The same bytes, to tell a tag not read yet from one that is broken.
let seen = r.clone();
Expand Down Expand Up @@ -674,6 +678,7 @@ fn read_layout(r: Sparse) -> Result<Parse> {
described,
lost,
white_is_zero,
sample_bits: u8::try_from(bits).ok().filter(|b| matches!(b, 1 | 2 | 4)),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The bit depth here comes from the local bits at line 403, which takes the first band's BitsPerSample. The whole-file reader (geotiff.rs, fn bits at line 876) takes the maximum over all bands. For a file whose bands differ, the two routes can disagree. Example: BitsPerSample [1, 8] (1-bit grey with an 8-bit alpha) gives Some(1) in a COG or window read, so it opens black and white, but None in a whole-file read, so it opens as classes. That breaks the PR's "same default on every read" claim. Use one rule on both routes, for example by making geotiff::bits pub(super) and calling it here. I have not compiled or run this. The mixed-depth case is rare, so confidence is moderate.

Category: bug

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A file whose bands' BitsPerSample differ, such as [1, 8], doesn't open on either route: the tiff crate (0.11.3) refuses mixed bit depths (InconsistentBitsPerSample) when it sets up the image, so the whole-file read fails, as do the tile and window decodes in place. With equal depths the first band's value and the maximum are the same, so the two routes give the same default for every file that opens.

copyright,
strips,
})))
Expand Down
1 change: 1 addition & 0 deletions crates/data/src/raster/cogwrite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
7 changes: 6 additions & 1 deletion crates/data/src/raster/geotiff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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 };
Expand Down Expand Up @@ -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}");
}
Expand Down Expand Up @@ -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::<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);
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();
Expand Down
7 changes: 7 additions & 0 deletions crates/data/src/raster/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u8>,
transformer: Transformer,
extent: Extent,
}
Expand Down Expand Up @@ -1057,6 +1062,7 @@ impl Raster {
rounded_some: Vec::new(),
copyright: None,
white_is_zero: false,
sample_bits: None,
transformer,
extent: Extent::EMPTY,
};
Expand Down Expand Up @@ -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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This keeps sample_bits when a raster is rebuilt on a new grid, but the other places that copy white_is_zero onto a derived raster don't copy it. Those are crates/analysis/src/warp.rs:695 (the output of warp/project), crates/engine/src/cmd/imagery.rs:247 (rebuild, whose doc says it keeps "which way round its grey is drawn"), and the other white_is_zero copies in imagery.rs (around lines 2021, 2114, 2284, 2763, 2938 and 3347; I did not check each one). A warped or rebuilt copy of a 1-bit scan has UInt8 data and category stats, so it falls back to Unique Values, which is the bug this PR fixes. Either copy sample_bits at those sites too, or say in the field doc that derived rasters intentionally lose it. Related: the GeoTIFF/COG writer in cogwrite.rs writes 8-bit output with no bit depth, so a re-exported scan reopens as classes. The PR should state which of these it intends.

Category: bug

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 68be14a: warp/project and every imagery path that copies the source grey interpretation now retain sample_bits; mosaics keep it only when all inputs agree. The reprojection regression failed before the fix and passes now. GeoTIFF export remains 8-bit by design, as documented on the field, so an exported copy reopens as 8-bit.

(r.rounded, r.rounded_some) = (self.rounded, self.rounded_some);
r
};
Expand Down
33 changes: 33 additions & 0 deletions crates/engine/src/cmd/imagery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,7 @@ fn rebuild(r: &Raster, transform: GeoTransform, crs: Crs, bands: Vec<Vec<f32>>)
o.wavelength = i.wavelength;
}
out.white_is_zero = r.white_is_zero;
out.sample_bits = r.sample_bits;
Ok(out)
}

Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Ok(t)
}

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)?;
Expand Down Expand Up @@ -3345,6 +3352,7 @@ pub(crate) fn mosaic_work(s: &Session, p: &Value) -> Result<super::workflows::Wo
.map_err(|e| e.to_string())?;
out.bands.iter_mut().zip(&wavelengths).for_each(|(band, w)| band.wavelength = *w);
out.white_is_zero = imgs.iter().all(|r| r.white_is_zero);
out.sample_bits = imgs.first().and_then(|first| first.sample_bits).filter(|bits| imgs.iter().all(|r| r.sample_bits == Some(*bits)));
// What the result says is said in the app too.
let name = w.name.clone();
let then: Option<super::workflows::Then> = (!messages.is_empty()).then(|| {
Expand Down Expand Up @@ -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));
}
1 change: 1 addition & 0 deletions crates/engine/src/cmd/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The window read now copies sample_bits from the layout, and the COG window path does the same in crates/tiles/src/cog/raster.rs. The diff adds no assertion on sample_bits on either path: the geotiff and cog tests cover only the whole-file and layout reads. If this line were removed, nothing in the diff would fail. Add a test that reads a 1-bit file through the window path (and through a COG window) and asserts sample_bits == Some(1) plus the default style from RasterStyle::default_for (Stretch with MinMax), and an 8-bit file gives None. That makes the "same default on every read" claim in the PR checkable.

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The additional window-path tests are left for the release quality pass.

if rounded.iter().any(|n| *n > 0) {
r.rounded = rounded;
}
Expand Down
Loading
Loading