Skip to content

Commit

Permalink
add method to create downsampled version of cog (#63)
Browse files Browse the repository at this point in the history
  • Loading branch information
geospatial-jeff authored Aug 15, 2020
1 parent e4787a8 commit 1f79514
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
31 changes: 31 additions & 0 deletions aiocogeo/cog.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,37 @@ async def point(self, x: Union[float, int], y: Union[float, int]) -> Union[np.nd
return tile[:, xindex, yindex]


async def preview(
self,
max_size: int = 1024,
height: Optional[int] = None,
width: Optional[int] = None,
resample_method: int = Image.NEAREST
) -> Union[np.ndarray, np.ma.masked_array]:
"""
Create downsampled version of the COG
https://github.com/cogeotiff/rio-tiler/blob/master/rio_tiler/reader.py#L272-L315
"""
ifd = self.ifds[0]
if not height and not width:
if max(ifd.ImageHeight.value, ifd.ImageWidth.value) < max_size:
height, width = ifd.ImageHeight.value, ifd.ImageWidth.value
else:
ratio = ifd.ImageHeight.value / ifd.ImageWidth.value
if ratio > 1:
height = max_size
width = math.ceil(height / ratio)
else:
width = max_size
height = math.ceil(width * ratio)
return await self.read(
bounds=self.bounds,
shape=(width, height),
resample_method=resample_method
)


def create_tile_matrix_set(self, identifier: str = None) -> Dict[str, Any]:
"""Create an OGC TileMatrixSet where each TileMatrix corresponds to an overview"""
matrices = []
Expand Down
23 changes: 23 additions & 0 deletions tests/test_cog_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,29 @@ async def test_point(create_cog_reader, infile):
assert np.equal(pt, tile[:,0,0]).all()


@pytest.mark.asyncio
@pytest.mark.parametrize(
"infile", TEST_DATA[:-1]
)
async def test_preview(create_cog_reader, infile):
async with create_cog_reader(infile) as cog:
profile = cog.profile
preview = await cog.preview(max_size=1024)

src_aspect_ratio = profile['height'] / profile['width']
dst_aspect_ratio = preview.shape[-2] / preview.shape[-1]
assert pytest.approx(src_aspect_ratio, 0.001) == dst_aspect_ratio
assert preview.shape[-2] <= 1024
assert preview.shape[-1] <= 1024


@pytest.mark.asyncio
async def test_preview_width_height(create_cog_reader):
async with create_cog_reader("https://async-cog-reader-test-data.s3.amazonaws.com/webp_cog.tif") as cog:
preview = await cog.preview(width=512, height=512)
assert preview.shape == (3, 512, 512)


@pytest.mark.asyncio
@pytest.mark.parametrize(
"infile", TEST_DATA
Expand Down

0 comments on commit 1f79514

Please sign in to comment.