Skip to content

Commit 292218d

Browse files
weiji14kylebarron
andauthored
feat!: enable fetching only specific planes from a band-interleaved TIFF (#251)
* Add band-interleaved multi-band sample TIFF * Fetch range of bands for a tile instead of all bands * Add specific test pulling specific band ranges from a TIFF * Enable fetching disjoint bands from a TIFF Change from passing in a Range<usize> to a Vec<usize> so specific bands can be indexed. * Change parameters from just bands to more extensible fetch_options Create a FetchOptions struct that allows passing specific parameters (currently only `bands`) when doing a fetch_tile operation. Keep the existing option of passing only None to do the default action of fetching of all bands. * Check that we are not fetching bands outside the max band count With some special handling to handle 0-based indexing. * Support fetching specific bands with `fetch_tiles` Use the same FetchOptions struct, included another unit test using the eox_cloudless.tif data as test case. * Rename to ReadOptions * Enable fetching specific bands via TIFF.fetch_tile and .fetch_tiles Add `bands` kwarg to TIFF.fetch_tile and TIFF.fetch_tiles to allow fetching only specific bands (or by default, all bands when `None` is given). Included a unit test to ensure it is possible to fetch only 2 bands from an RGB TIFF. * Update geotiff-test-data from efc3ee1 to b7158c4 Include updated uint8_1band_deflate_block128_unaligned_predictor2.tif file from developmentseed/geotiff-test-data#74 * Change unit test to check against AEF embedding dataset with 64 bands Try pulling 3 bands out of 64 from the sample AlphaEarth Foundations embedding TIFF dataset. Updated geotiff-test-data from b7158c4 to 0b1055b which includes the tiled sample AEF embedding TIFF from developmentseed/geotiff-test-data#79 * Rename fetch_options parameter to read_options Following the ReadOptions struct name used in 72e1071 * Change bands/planes to be kwarg only * Rename bands -> planes Xref #360 * Clarify that planes arguments should be using 0-based indexing E.g. [0, 1, 2] for the first three planes/bands. --------- Co-authored-by: Kyle Barron <kyle@developmentseed.org>
1 parent b18344f commit 292218d

20 files changed

Lines changed: 353 additions & 54 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ let ifds = meta.read_all_ifds(&cache).await.unwrap();
4343
let tiff = TIFF::new(ifds, meta.endianness());
4444

4545
// Fetch and decode a tile
46-
let tile = tiff.ifds()[0].fetch_tile(0, 0, &reader).await.unwrap();
46+
let tile = tiff.ifds()[0].fetch_tile(0, 0, &reader, Default::default()).await.unwrap();
4747
let array = tile.decode(&Default::default()).unwrap();
4848
println!("shape: {:?}, dtype: {:?}", array.shape(), array.data_type());
4949
# })

‎benches/read_tiff.rs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,9 @@ async fn read_tiles<R: AsyncFileReader + Clone>(reader: R) -> AsyncTiffResult<Ve
4848
.flat_map(|i| (0..y_count).map(move |j| (i, j)))
4949
.collect();
5050

51-
let tiles: Vec<Tile> = ifd.fetch_tiles(&xy_ids, &reader).await?;
51+
let tiles: Vec<Tile> = ifd
52+
.fetch_tiles(&xy_ids, &reader, Default::default())
53+
.await?;
5254
Ok(tiles)
5355
}
5456

‎python/python/async_tiff/_ifd.pyi‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,21 +132,33 @@ class ImageFileDirectory:
132132
def colormap(self) -> Colormap | None:
133133
"""The colormap for palette-color images."""
134134
...
135-
async def fetch_tile(self, x: int, y: int) -> Tile:
135+
async def fetch_tile(
136+
self,
137+
x: int,
138+
y: int,
139+
*,
140+
planes: Sequence[int] | None = None,
141+
) -> Tile:
136142
"""Fetch a single tile.
137143
138144
Args:
139145
x: The column index within the ifd to read from.
140146
y: The row index within the ifd to read from.
147+
planes: The plane indices to read from (using 0-based indexing). If `None`,
148+
all planes will be read.
141149
142150
Returns:
143151
Tile response.
144152
"""
145-
async def fetch_tiles(self, xy: Sequence[tuple[int, int]]) -> list[Tile]:
153+
async def fetch_tiles(
154+
self, xy: Sequence[tuple[int, int]], *, planes: Sequence[int] | None = None
155+
) -> list[Tile]:
146156
"""Fetch multiple tiles concurrently.
147157
148158
Args:
149159
xy: The (column, row) indexes within the ifd to read from.
160+
planes: The plane indices to read from (using 0-based indexing). If `None`,
161+
all planes will be read.
150162
151163
Returns:
152164
Tile responses.
@@ -156,12 +168,16 @@ class ImageFileDirectory:
156168
self,
157169
x: int,
158170
y: int,
171+
*,
172+
planes: Sequence[int] | None = None,
159173
) -> tuple[int, int] | list[tuple[int, int]]:
160174
"""The byte range of the tile at the given column and row indices.
161175
162176
Args:
163177
x: The column index within the ifd to read from.
164178
y: The row index within the ifd to read from.
179+
planes: The plane indices to read from (using 0-based indexing). If `None`,
180+
all planes will be read.
165181
166182
Returns:
167183
The byte range or ranges of the tile, as `(start, end)`. The result will be

‎python/python/async_tiff/_tiff.pyi‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import Sequence
1+
from collections.abc import Sequence
22

33
from ._ifd import ImageFileDirectory
44
from ._input import ObspecInput
@@ -63,23 +63,40 @@ class TIFF:
6363
Each ImageFileDirectory (IFD) represents one of the internal "sub images" of
6464
this file.
6565
"""
66-
async def fetch_tile(self, x: int, y: int, z: int) -> Tile:
66+
async def fetch_tile(
67+
self,
68+
x: int,
69+
y: int,
70+
z: int,
71+
*,
72+
planes: Sequence[int] | None = None,
73+
) -> Tile:
6774
"""Fetch a single tile.
6875
6976
Args:
7077
x: The column index within the ifd to read from.
7178
y: The row index within the ifd to read from.
7279
z: The IFD index to read from.
80+
planes: The plane indices to read from (using 0-based indexing). If `None`,
81+
all planes will be read.
7382
7483
Returns:
7584
Tile response.
7685
"""
77-
async def fetch_tiles(self, xy: Sequence[tuple[int, int]], z: int) -> list[Tile]:
86+
async def fetch_tiles(
87+
self,
88+
xy: Sequence[tuple[int, int]],
89+
z: int,
90+
*,
91+
planes: Sequence[int] | None = None,
92+
) -> list[Tile]:
7893
"""Fetch multiple tiles concurrently.
7994
8095
Args:
8196
xy: The (column, row) indexes within the ifd to read from.
8297
z: The IFD index to read from.
98+
planes: The plane indices to read from (using 0-based indexing). If `None`,
99+
all planes will be read.
83100
84101
Returns:
85102
Tile responses.

‎python/src/ifd.rs‎

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use std::collections::HashMap;
22
use std::sync::Arc;
33

44
use async_tiff::reader::AsyncFileReader;
5-
use async_tiff::{ImageFileDirectory, TileByteRange};
5+
use async_tiff::{ImageFileDirectory, ReadOptions, TileByteRange};
66
use pyo3::exceptions::{PyTypeError, PyValueError};
77
use pyo3::prelude::*;
88
use pyo3::IntoPyObjectExt;
@@ -453,45 +453,57 @@ impl PyImageFileDirectory {
453453
}
454454
}
455455

456+
#[pyo3(signature = (x, y, *, planes=None))]
456457
fn fetch_tile<'py>(
457458
&'py self,
458459
py: Python<'py>,
459460
x: usize,
460461
y: usize,
462+
planes: Option<Vec<usize>>,
461463
) -> PyResult<Bound<'py, PyAny>> {
464+
let options = ReadOptions { planes };
462465
let reader = self.reader.clone();
463466
let ifd = self.ifd.clone();
464467
future_into_py(py, async move {
465468
let tile = ifd
466-
.fetch_tile(x, y, reader.as_ref())
469+
.fetch_tile(x, y, reader.as_ref(), options)
467470
.await
468471
.map_err(|err| PyTypeError::new_err(err.to_string()))?;
469472

470473
Ok(PyTile::new(tile))
471474
})
472475
}
473476

477+
#[pyo3(signature = (xy, *, planes=None))]
474478
pub(crate) fn fetch_tiles<'py>(
475479
&'py self,
476480
py: Python<'py>,
477481
xy: Vec<(usize, usize)>,
482+
planes: Option<Vec<usize>>,
478483
) -> PyResult<Bound<'py, PyAny>> {
484+
let options = ReadOptions { planes };
479485
let reader = self.reader.clone();
480486
let ifd = self.ifd.clone();
481487
future_into_py(py, async move {
482488
let tiles = ifd
483-
.fetch_tiles(&xy, reader.as_ref())
489+
.fetch_tiles(&xy, reader.as_ref(), options)
484490
.await
485491
.map_err(|err| PyTypeError::new_err(err.to_string()))?;
486492
let py_tiles = tiles.into_iter().map(PyTile::new).collect::<Vec<_>>();
487493
Ok(py_tiles)
488494
})
489495
}
490496

491-
fn tile_byte_range(&self, x: usize, y: usize) -> PyAsyncTiffResult<PyTileByteRange> {
497+
#[pyo3(signature = (x, y, *, planes=None))]
498+
fn tile_byte_range(
499+
&self,
500+
x: usize,
501+
y: usize,
502+
planes: Option<Vec<usize>>,
503+
) -> PyAsyncTiffResult<PyTileByteRange> {
492504
let byte_range = self
493505
.ifd
494-
.tile_byte_range(x, y)
506+
.tile_byte_range(x, y, planes.as_deref())?
495507
.ok_or(PyValueError::new_err("Not a tiled tiff"))?;
496508
Ok(PyTileByteRange(byte_range))
497509
}

‎python/src/tiff.rs‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use std::sync::Arc;
33
use async_tiff::metadata::cache::ReadaheadMetadataCache;
44
use async_tiff::metadata::TiffMetadataReader;
55
use async_tiff::reader::{AsyncFileReader, Endianness};
6-
use async_tiff::ImageFileDirectory;
6+
use async_tiff::{ImageFileDirectory, ReadOptions};
77
use pyo3::exceptions::{PyIndexError, PyTypeError};
88
use pyo3::prelude::*;
99
use pyo3::types::PyType;
@@ -99,13 +99,16 @@ impl PyTIFF {
9999
.collect()
100100
}
101101

102+
#[pyo3(signature = (x, y, z, *, planes=None))]
102103
fn fetch_tile<'py>(
103104
&'py self,
104105
py: Python<'py>,
105106
x: usize,
106107
y: usize,
107108
z: usize,
109+
planes: Option<Vec<usize>>,
108110
) -> PyResult<Bound<'py, PyAny>> {
111+
let options = ReadOptions { planes };
109112
let reader = self.reader.clone();
110113
let ifd = self
111114
.ifds
@@ -114,20 +117,22 @@ impl PyTIFF {
114117
.clone();
115118
future_into_py(py, async move {
116119
let tile = ifd
117-
.fetch_tile(x, y, reader.as_ref())
120+
.fetch_tile(x, y, reader.as_ref(), options)
118121
.await
119122
.map_err(|err| PyTypeError::new_err(err.to_string()))?;
120123

121124
Ok(PyTile::new(tile))
122125
})
123126
}
124-
127+
#[pyo3(signature = (xy, z, *, planes=None))]
125128
fn fetch_tiles<'py>(
126129
&'py self,
127130
py: Python<'py>,
128131
xy: Vec<(usize, usize)>,
129132
z: usize,
133+
planes: Option<Vec<usize>>,
130134
) -> PyResult<Bound<'py, PyAny>> {
135+
let options = ReadOptions { planes };
131136
let reader = self.reader.clone();
132137
let ifd = self
133138
.ifds
@@ -136,7 +141,7 @@ impl PyTIFF {
136141
.clone();
137142
future_into_py(py, async move {
138143
let tiles = ifd
139-
.fetch_tiles(&xy, reader.as_ref())
144+
.fetch_tiles(&xy, reader.as_ref(), options)
140145
.await
141146
.map_err(|err| PyTypeError::new_err(err.to_string()))?;
142147
let py_tiles = tiles.into_iter().map(PyTile::new).collect::<Vec<_>>();

‎python/tests/test_tiff.py‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,32 @@ async def test_read_band_interleaved_tiff_window(
4545
np.testing.assert_array_equal(data, rasterio_data)
4646

4747

48+
@pytest.mark.asyncio
49+
@pytest.mark.parametrize(
50+
("variant", "file_name"),
51+
[("source-coop-alpha-earth", "xjejfvrbm1fbu1ecw-0000000000-0000008192")],
52+
)
53+
async def test_fetch_specific_planes(
54+
load_tiff: LoadTIFF,
55+
load_rasterio: LoadRasterio,
56+
variant: str,
57+
file_name: str,
58+
) -> None:
59+
"""
60+
Ensure TIFF.fetch_tile() can retrieve specific planes from a band-interleaved TIFF.
61+
"""
62+
tiff = await load_tiff(file_name, variant=variant)
63+
64+
tile = await tiff.fetch_tile(0, 0, z=0, planes=[0, 42, 63]) # 0-indexing
65+
array = await tile.decode()
66+
data = np.array(array)
67+
68+
with load_rasterio(file_name, variant=variant) as rasterio_ds:
69+
rasterio_data = rasterio_ds.read(indexes=[1, 43, 64]) # 1-indexing
70+
71+
np.testing.assert_array_equal(data, rasterio_data)
72+
73+
4874
@pytest.mark.asyncio
4975
@pytest.mark.parametrize(("variant", "file_name"), [("eox", "eox_cloudless")])
5076
async def test_header_byte_size(

0 commit comments

Comments
 (0)