Skip to content

Commit 2c01ecd

Browse files
authored
feat: Support for non-boundless tile reads (#94)
* Implement clipping * don't return contiguous * Add rasterio boundless=False test
1 parent e835e95 commit 2c01ecd

3 files changed

Lines changed: 134 additions & 10 deletions

File tree

‎src/async_geotiff/_fetch.py‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,16 @@ def nodata(self) -> int | float | None:
5050
"""The nodata value for the image, if any."""
5151
...
5252

53+
@property
54+
def width(self) -> int:
55+
"""The width of the image in pixels."""
56+
...
57+
58+
@property
59+
def height(self) -> int:
60+
"""The height of the image in pixels."""
61+
...
62+
5363

5464
class FetchTileMixin:
5565
"""Mixin for fetching tiles from a GeoTIFF.
@@ -61,7 +71,22 @@ async def fetch_tile(
6171
self: HasTiffReference,
6272
x: int,
6373
y: int,
74+
*,
75+
boundless: bool = True,
6476
) -> Tile:
77+
"""Fetch a single tile from the GeoTIFF.
78+
79+
Args:
80+
x: The x-coordinate of the tile.
81+
y: The y-coordinate of the tile.
82+
83+
Keyword Args:
84+
boundless: If False, clip edge tiles to the image bounds. Defaults to True.
85+
86+
Returns:
87+
A Tile object containing the fetched tile data.
88+
89+
"""
6590
tile_fut = self._ifd.fetch_tile(x, y)
6691

6792
mask_data: AsyncTiffArray | None = None
@@ -86,6 +111,10 @@ async def fetch_tile(
86111
transform=tile_transform,
87112
nodata=self.nodata,
88113
)
114+
115+
if not boundless:
116+
array = _clip_to_image_bounds(self, x, y, array)
117+
89118
return Tile(
90119
x=x,
91120
y=y,
@@ -95,12 +124,17 @@ async def fetch_tile(
95124
async def fetch_tiles(
96125
self: HasTiffReference,
97126
xy: Sequence[tuple[int, int]],
127+
*,
128+
boundless: bool = True,
98129
) -> list[Tile]:
99130
"""Fetch multiple tiles from this overview.
100131
101132
Args:
102133
xy: The (x, y) coordinates of the tiles.
103134
135+
Keyword Args:
136+
boundless: If False, clip edge tiles to the image bounds.
137+
104138
"""
105139
tiles_fut = self._ifd.fetch_tiles(xy)
106140

@@ -136,6 +170,10 @@ async def fetch_tiles(
136170
transform=tile_transform,
137171
nodata=self.nodata,
138172
)
173+
174+
if not boundless:
175+
array = _clip_to_image_bounds(self, x, y, array)
176+
139177
tile = Tile(
140178
x=x,
141179
y=y,
@@ -144,3 +182,43 @@ async def fetch_tiles(
144182
final_tiles.append(tile)
145183

146184
return final_tiles
185+
186+
187+
def _clip_to_image_bounds(
188+
self: HasTiffReference,
189+
x: int,
190+
y: int,
191+
array: Array,
192+
) -> Array:
193+
"""Clip a decoded tile array to the valid image bounds.
194+
195+
Edge tiles in a COG are always encoded at the full tile size, with the
196+
out-of-bounds region zero-padded. When ``boundless=False`` is requested,
197+
this function copies only the valid pixel sub-rectangle into a new array,
198+
returning an Array whose width/height match the actual image content.
199+
200+
Interior tiles (where the tile fits entirely within the image) are
201+
returned unchanged.
202+
"""
203+
clipped_width = min((x + 1) * self.tile_width, self.width) - x * self.tile_width
204+
clipped_height = min((y + 1) * self.tile_height, self.height) - y * self.tile_height
205+
206+
if clipped_width == self.tile_width and clipped_height == self.tile_height:
207+
return array
208+
209+
# data shape is (bands, height, width)
210+
clipped_data = array.data[:, :clipped_height, :clipped_width]
211+
clipped_mask = (
212+
array.mask[:clipped_height, :clipped_width] if array.mask is not None else None
213+
)
214+
215+
return Array(
216+
data=clipped_data,
217+
mask=clipped_mask,
218+
width=clipped_width,
219+
height=clipped_height,
220+
count=array.count,
221+
transform=array.transform,
222+
crs=array.crs,
223+
nodata=array.nodata,
224+
)

‎src/async_geotiff/_overview.py‎

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -29,16 +29,10 @@ class Overview(ReadMixin, FetchTileMixin, TransformMixin):
2929
"""
3030

3131
_ifd: ImageFileDirectory
32-
"""The IFD for this overview level.
33-
34-
(positional index of the IFD in the TIFF file, IFD object)
35-
"""
32+
"""The IFD for this overview level."""
3633

3734
_mask_ifd: ImageFileDirectory | None
38-
"""The IFD for the mask associated with this overview level, if any.
39-
40-
(positional index of the IFD in the TIFF file, IFD object)
41-
"""
35+
"""The IFD for the mask associated with this overview level, if any."""
4236

4337
@classmethod
4438
def _create(
@@ -94,9 +88,9 @@ def transform(self) -> Affine:
9488
"""
9589
full_transform = self._geotiff.transform
9690

97-
overview_width = self._ifd.image_width
91+
overview_width = self.width
9892
full_width = self._geotiff.width
99-
overview_height = self._ifd.image_height
93+
overview_height = self.height
10094
full_height = self._geotiff.height
10195

10296
scale_x = full_width / overview_width

‎tests/test_fetch.py‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from __future__ import annotations
44

5+
import math
56
from typing import TYPE_CHECKING
67

78
import numpy as np
@@ -120,6 +121,57 @@ async def test_mask_overview(
120121
np.testing.assert_array_equal(tile.array.mask, mask.astype(np.bool_))
121122

122123

124+
@pytest.mark.asyncio
125+
async def test_fetch_tile_bounded(
126+
load_geotiff: LoadGeoTIFF,
127+
load_rasterio: LoadRasterio,
128+
) -> None:
129+
"""Edge tiles clipped to image bounds match rasterio's non-boundless read."""
130+
file_name = "uint8_1band_deflate_block128_unaligned"
131+
geotiff = await load_geotiff(file_name)
132+
133+
tiles_across = math.ceil(geotiff.width / geotiff.tile_width)
134+
tiles_down = math.ceil(geotiff.height / geotiff.tile_height)
135+
136+
# Test every edge tile (last column and last row)
137+
edge_tiles = [
138+
(x, y)
139+
for x in range(tiles_across)
140+
for y in range(tiles_down)
141+
if x == tiles_across - 1 or y == tiles_down - 1
142+
]
143+
144+
with load_rasterio(file_name) as rasterio_ds:
145+
for tx, ty in edge_tiles:
146+
tile = await geotiff.fetch_tile(tx, ty, boundless=False)
147+
148+
expected_width = (
149+
min((tx + 1) * geotiff.tile_width, geotiff.width)
150+
- tx * geotiff.tile_width
151+
)
152+
expected_height = (
153+
min((ty + 1) * geotiff.tile_height, geotiff.height)
154+
- ty * geotiff.tile_height
155+
)
156+
157+
assert tile.array.width == expected_width, f"tile ({tx},{ty}) width"
158+
assert tile.array.height == expected_height, f"tile ({tx},{ty}) height"
159+
160+
window = Window(
161+
tx * geotiff.tile_width,
162+
ty * geotiff.tile_height,
163+
expected_width,
164+
expected_height,
165+
)
166+
rasterio_data = rasterio_ds.read(window=window, boundless=False)
167+
168+
np.testing.assert_array_equal(
169+
tile.array.data,
170+
rasterio_data,
171+
err_msg=f"tile ({tx},{ty}) data mismatch",
172+
)
173+
174+
123175
@pytest.mark.asyncio
124176
@pytest.mark.parametrize(
125177
("variant", "file_name"),

0 commit comments

Comments
 (0)