Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Zarr Tile Sink: Generate Downsampled Levels #1490

Merged
merged 27 commits into from
Apr 5, 2024
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
d31ee70
wip: start implementing downsampling method
annehaley Mar 18, 2024
91d0b99
fix: handle bands separately when number of bands > 4
annehaley Mar 26, 2024
152b80b
test: add basic tests for downsampling
annehaley Mar 26, 2024
1ea179e
fix: update reference to ResampleMethod
annehaley Mar 26, 2024
7f35702
fix: Use tileIterator and addTile to write downsampled levels
annehaley Mar 28, 2024
e86015d
test: Update downsampling tests
annehaley Mar 28, 2024
38d5e57
Merge branch 'master' into downsample
annehaley Apr 1, 2024
a8bf91a
refactor: split `addTile` into two functions to satisfy function comp…
annehaley Apr 1, 2024
441995f
refactor: move typed resampling methods to `large_image.tilesource` m…
annehaley Apr 2, 2024
42aeffe
fix: simplify NP_MODE resize implementation
annehaley Apr 3, 2024
49a46d7
fix: eliminate type error for 2d tiles
annehaley Apr 3, 2024
e769fe0
fix: only default to LANCZOS if dtype is uint8
annehaley Apr 3, 2024
94d517d
fix: don't split bands when using numpy resample methods
annehaley Apr 3, 2024
d33c89b
test: use 6 8-bit bands in downsampling multiband test
annehaley Apr 3, 2024
cbd48da
fix: put back tile shape check for typing
annehaley Apr 3, 2024
92a1687
Merge branch 'master' into downsample
annehaley Apr 3, 2024
a472576
fix: round up tile dimensions when dividing by 2
annehaley Apr 3, 2024
9a74c0a
fix: only overlap tiles when using interpolated resample modes
annehaley Apr 3, 2024
e7234b2
fix: swap order of operations computing tile start coords using overlap
annehaley Apr 3, 2024
dbcb661
fix: copy last row/col when tile has odd dims
annehaley Apr 3, 2024
ff67307
refactor: rename min/max methods
annehaley Apr 3, 2024
815c87e
style: remove extra whitespace
annehaley Apr 4, 2024
05827bc
Merge branch 'master' into downsample
annehaley Apr 4, 2024
4ef0c58
fix: update crop method and crop before generating downsampled levels
annehaley Apr 4, 2024
f7876a3
test: Reorganize tests and add assertion for downsampled content
annehaley Apr 4, 2024
fe4ed29
refactor: define expected masks as a dict to pass function complexity…
annehaley Apr 4, 2024
2e10ec4
test: use odd dimensions in downsampling test
annehaley Apr 5, 2024
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
124 changes: 124 additions & 0 deletions large_image/tilesource/resample.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
from enum import Enum
from typing import Dict

import numpy as np
from PIL import Image


class ResampleMethod(Enum):
PIL_NEAREST = Image.Resampling.NEAREST # 0
PIL_LANCZOS = Image.Resampling.LANCZOS # 1
PIL_BILINEAR = Image.Resampling.BILINEAR # 2
PIL_BICUBIC = Image.Resampling.BICUBIC # 3
PIL_BOX = Image.Resampling.BOX # 4
PIL_HAMMING = Image.Resampling.HAMMING # 5
PIL_MAX_ENUM = 5
NP_MEAN = 6
NP_MEDIAN = 7
NP_MODE = 8
NP_MAX = 9
NP_MIN = 10
NP_NEAREST = 11
NP_MAX_CROSSBAND = 12
NP_MIN_CROSSBAND = 13


def pilResize(
tile: np.ndarray,
new_shape: Dict,
resample_method: ResampleMethod,
) -> np.ndarray:
# Only NEAREST works for 16 bit images
img = Image.fromarray(tile)
resized_img = img.resize(
(new_shape['width'], new_shape['height']),
resample=resample_method.value,
)
result = np.array(resized_img).astype(tile.dtype)
return result


def numpyResize(
tile: np.ndarray,
new_shape: Dict,
resample_method: ResampleMethod,
) -> np.ndarray:
if resample_method == ResampleMethod.NP_NEAREST:
return tile[::2, ::2]
else:
pixel_selection = None
subarrays = np.asarray(
[
tile[0::2, 0::2],
tile[1::2, 0::2],
tile[0::2, 1::2],
tile[1::2, 1::2],
],
)

if resample_method == ResampleMethod.NP_MEAN:
return np.mean(subarrays, axis=0).astype(tile.dtype)
elif resample_method == ResampleMethod.NP_MEDIAN:
return np.median(subarrays, axis=0).astype(tile.dtype)
elif resample_method == ResampleMethod.NP_MODE:
# if a pixel occurs twice in a set of four, it is a mode
# if no mode, default to pixel 0. check for minimal matches 1=2, 1=3, 2=3
pixel_selection = np.where(
(
(subarrays[1] == subarrays[2]).all(axis=2) |
(subarrays[1] == subarrays[3]).all(axis=2)
),
1, np.where(
(subarrays[2] == subarrays[3]).all(axis=2),
2, 0,
),
)
elif resample_method == ResampleMethod.NP_MAX:
summed = np.sum(subarrays, axis=3)
pixel_selection = np.argmax(summed, axis=0)
elif resample_method == ResampleMethod.NP_MIN:
summed = np.sum(subarrays, axis=3)
pixel_selection = np.argmin(summed, axis=0)
elif resample_method == ResampleMethod.NP_MAX_CROSSBAND:
return np.max(subarrays, axis=0).astype(tile.dtype)
elif resample_method == ResampleMethod.NP_MIN_CROSSBAND:
return np.min(subarrays, axis=0).astype(tile.dtype)

if pixel_selection is not None:
if len(tile.shape) > 2:
pixel_selection = np.expand_dims(pixel_selection, axis=2)
pixel_selection = np.repeat(pixel_selection, tile.shape[2], axis=2)
return np.choose(pixel_selection, subarrays).astype(tile.dtype)
else:
msg = f'Unknown resample method {resample_method}.'
raise ValueError(msg)


def downsampleTileHalfRes(
tile: np.ndarray,
resample_method: ResampleMethod,
) -> np.ndarray:
new_shape = {
'height': (tile.shape[0] + 1) // 2,
'width': (tile.shape[1] + 1) // 2,
'bands': 1,
}
if len(tile.shape) > 2:
new_shape['bands'] = tile.shape[-1]
if resample_method.value <= ResampleMethod.PIL_MAX_ENUM.value:
if new_shape['bands'] > 4:
result = np.empty(
(new_shape['height'], new_shape['width'], new_shape['bands']),
dtype=tile.dtype,
)
for band_index in range(new_shape['bands']):
result[(..., band_index)] = pilResize(
tile[(..., band_index)],
new_shape,
resample_method,
)
return result
else:
return pilResize(tile, new_shape, resample_method)
else:
return numpyResize(tile, new_shape, resample_method)
Loading