-
Notifications
You must be signed in to change notification settings - Fork 51
Chunkwise image loader #279
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
Open
lucas-diedrich
wants to merge
17
commits into
scverse:main
Choose a base branch
from
lucas-diedrich:image-reader-chunkwise
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 11 commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
8027c0b
feature: Initial lazy tiff reader
lucas-diedrich 7ff1d23
Updated comments
lucas-diedrich 826133a
Updated comments
lucas-diedrich df258bc
Move utility functions to designated submodule readers._utils._image
lucas-diedrich db0d782
Initial tests utils
lucas-diedrich c03932f
Fixes edge cases for min coordinate
lucas-diedrich 339cbd8
Added test for negative coordinates
lucas-diedrich 24c6eec
Add support for png/jpg again
lucas-diedrich dbdc7c7
Add initial test
lucas-diedrich da98469
Fix: Fix jpeg and png reader, fix issues with local variable name
lucas-diedrich b7e5874
Merge branch 'main' of https://github.com/scverse/spatialdata-io into…
lucas-diedrich 2349be7
Update src/spatialdata_io/readers/_utils/_image.py
lucas-diedrich 46ed3e5
[Refactor|API] Rename dimensions to shape to stick to numpy convention
lucas-diedrich 99731fe
[Refactor] Make suggested simplification of code, suggested by @melonora
lucas-diedrich f03ca8e
[Test] Add test for compressed tiffs
lucas-diedrich 9e057de
[Fix] Account for compressed images
lucas-diedrich c05b718
[Refactor] Remove unnecessary type hint
lucas-diedrich File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,129 @@ | ||
| from collections.abc import Callable | ||
| from typing import Any | ||
|
|
||
| import dask.array as da | ||
| import numpy as np | ||
| from dask import delayed | ||
| from numpy.typing import NDArray | ||
|
|
||
|
|
||
| def _compute_chunk_sizes_positions(size: int, chunk: int, min_coord: int) -> tuple[NDArray[np.int_], NDArray[np.int_]]: | ||
| """Calculate chunk sizes and positions for a given dimension and chunk size""" | ||
| # All chunks have the same size except for the last one | ||
| positions = np.arange(min_coord, min_coord + size, chunk) | ||
| lengths = np.full_like(positions, chunk, dtype=int) | ||
|
|
||
| if positions[-1] + chunk > size + min_coord: | ||
| lengths[-1] = size + min_coord - positions[-1] | ||
|
|
||
| return positions, lengths | ||
|
|
||
|
|
||
| def _compute_chunks( | ||
| dimensions: tuple[int, int], | ||
| chunk_size: tuple[int, int], | ||
| min_coordinates: tuple[int, int] = (0, 0), | ||
| ) -> NDArray[np.int_]: | ||
| """Create all chunk specs for a given image and chunk size. | ||
| Creates specifications (x, y, width, height) with (x, y) being the upper left corner | ||
| of chunks of size chunk_size. Chunks at the edges correspond to the remainder of | ||
| chunk size and dimensions | ||
| Parameters | ||
| ---------- | ||
| dimensions : tuple[int, int] | ||
lucas-diedrich marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| Size of the image in (width, height). | ||
| chunk_size : tuple[int, int] | ||
| Size of individual tiles in (width, height). | ||
| min_coordinates : tuple[int, int], optional | ||
| Minimum coordinates (x, y) in the image, defaults to (0, 0). | ||
| Returns | ||
| ------- | ||
| np.ndarray | ||
| Array of shape (n_tiles_x, n_tiles_y, 4). Each entry defines a tile | ||
| as (x, y, width, height). | ||
| """ | ||
| x_positions, widths = _compute_chunk_sizes_positions(dimensions[1], chunk_size[1], min_coord=min_coordinates[1]) | ||
| y_positions, heights = _compute_chunk_sizes_positions(dimensions[0], chunk_size[0], min_coord=min_coordinates[0]) | ||
|
|
||
| # Generate the tiles | ||
| tiles = np.array( | ||
| [ | ||
| [[x, y, w, h] for x, w in zip(x_positions, widths, strict=True)] | ||
| for y, h in zip(y_positions, heights, strict=True) | ||
| ], | ||
| dtype=int, | ||
| ) | ||
| return tiles | ||
|
|
||
|
|
||
| def _read_chunks( | ||
| func: Callable[..., NDArray[np.int_]], | ||
| slide: Any, | ||
| coords: NDArray[np.int_], | ||
| n_channel: int, | ||
| dtype: np.number, | ||
| **func_kwargs: Any, | ||
| ) -> list[list[da.array]]: | ||
| """Abstract method to tile a large microscopy image. | ||
| Parameters | ||
| ---------- | ||
| func | ||
| Function to retrieve a rectangular tile from the slide image. Must take the | ||
| arguments: | ||
| - slide Full slide image | ||
| - x0: x (col) coordinate of upper left corner of chunk | ||
| - y0: y (row) coordinate of upper left corner of chunk | ||
| - width: Width of chunk | ||
| - height: Height of chunk | ||
| and should return the chunk as numpy array of shape (c, y, x) | ||
| slide | ||
| Slide image in lazyly loaded format compatible with func | ||
| coords | ||
| Coordinates of the upper left corner of the image in format (n_row_x, n_row_y, 4) | ||
| where the last dimension defines the rectangular tile in format (x, y, width, height). | ||
| n_row_x represents the number of chunks in x dimension and n_row_y the number of chunks | ||
| in y dimension. | ||
| n_channel | ||
| Number of channels in array | ||
| dtype | ||
| Data type of image | ||
| func_kwargs | ||
| Additional keyword arguments passed to func | ||
| Returns | ||
| ------- | ||
| list[list[da.array]] | ||
| List (length: n_row_x) of lists (length: n_row_y) of chunks. | ||
| Represents all chunks of the full image. | ||
| """ | ||
| func_kwargs = func_kwargs if func_kwargs else {} | ||
|
|
||
| # Collect each delayed chunk as item in list of list | ||
| # Inner list becomes dim=-1 (cols/x) | ||
| # Outer list becomes dim=-2 (rows/y) | ||
| # see dask.array.block | ||
| chunks = [ | ||
| [ | ||
| da.from_delayed( | ||
| delayed(func)( | ||
| slide, | ||
| x0=coords[y, x, 0], | ||
| y0=coords[y, x, 1], | ||
| width=coords[y, x, 2], | ||
| height=coords[y, x, 3], | ||
| **func_kwargs, | ||
| ), | ||
| dtype=dtype, | ||
| shape=(n_channel, *coords[y, x, [3, 2]]), | ||
| ) | ||
| for x in range(coords.shape[1]) | ||
| ] | ||
| for y in range(coords.shape[0]) | ||
| ] | ||
| return chunks | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| import numpy as np | ||
| import pytest | ||
| from numpy.typing import NDArray | ||
|
|
||
| from spatialdata_io.readers._utils._image import ( | ||
| _compute_chunk_sizes_positions, | ||
| _compute_chunks, | ||
| ) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| ("size", "chunk", "min_coordinate", "positions", "lengths"), | ||
| [ | ||
| (300, 100, 0, np.array([0, 100, 200]), np.array([100, 100, 100])), | ||
| (300, 200, 0, np.array([0, 200]), np.array([200, 100])), | ||
| (300, 100, -100, np.array([-100, 0, 100]), np.array([100, 100, 100])), | ||
| (300, 200, -100, np.array([-100, 100]), np.array([200, 100])), | ||
| ], | ||
| ) | ||
| def test_compute_chunk_sizes_positions( | ||
| size: int, | ||
| chunk: int, | ||
| min_coordinate: int, | ||
| positions: NDArray[np.number], | ||
| lengths: NDArray[np.number], | ||
| ) -> None: | ||
| computed_positions, computed_lengths = _compute_chunk_sizes_positions(size, chunk, min_coordinate) | ||
| assert (positions == computed_positions).all() | ||
| assert (lengths == computed_lengths).all() | ||
|
|
||
|
|
||
| @pytest.mark.parametrize( | ||
| ("dimensions", "chunk_size", "min_coordinates", "result"), | ||
| [ | ||
| # Regular grid 2x2 | ||
| ( | ||
| (2, 2), | ||
| (1, 1), | ||
| (0, 0), | ||
| np.array([[[0, 0, 1, 1], [1, 0, 1, 1]], [[0, 1, 1, 1], [1, 1, 1, 1]]]), | ||
| ), | ||
| # Different tile sizes | ||
| ( | ||
| (3, 3), | ||
| (2, 2), | ||
| (0, 0), | ||
| np.array([[[0, 0, 2, 2], [2, 0, 1, 2]], [[0, 2, 2, 1], [2, 2, 1, 1]]]), | ||
| ), | ||
| ( | ||
| (2, 2), | ||
| (1, 1), | ||
| (-1, 0), | ||
| np.array([[[0, -1, 1, 1], [1, -1, 1, 1]], [[0, 0, 1, 1], [1, 0, 1, 1]]]), | ||
| ), | ||
| ], | ||
| ) | ||
| def test_compute_chunks( | ||
| dimensions: tuple[int, int], | ||
| chunk_size: tuple[int, int], | ||
| min_coordinates: tuple[int, int], | ||
| result: NDArray[np.number], | ||
| ) -> None: | ||
| tiles = _compute_chunks(dimensions, chunk_size, min_coordinates) | ||
|
|
||
| assert (tiles == result).all() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.