From 29823fa3a6b446ce5ca7e9600271323f846cd4a1 Mon Sep 17 00:00:00 2001 From: Ajey Pai K Date: Fri, 9 Aug 2024 21:06:58 +0200 Subject: [PATCH] Fixes #107 --- ahcore/utils/callbacks.py | 13 ++++++++----- ahcore/writers.py | 7 ++++++- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/ahcore/utils/callbacks.py b/ahcore/utils/callbacks.py index 125b4f1..1c1b296 100644 --- a/ahcore/utils/callbacks.py +++ b/ahcore/utils/callbacks.py @@ -81,8 +81,9 @@ def __init__( self._annotations = _validate_annotations(data_description, annotations) self._mask = _validate_annotations(data_description, mask) + self._reader_grid_offset = self._reader.metadata["grid_offset"] self._grid = Grid.from_tiling( - (0, 0), + self._reader_grid_offset, reader.size, tile_size=self._region_size, tile_overlap=(0, 0), @@ -166,12 +167,14 @@ def _read_and_pad_region(self, coordinates: tuple[int, int]) -> pyvips.Image: width, height = self._region_size new_width = min(width, self._reader.size[0] - x) new_height = min(height, self._reader.size[1] - y) - clipped_region = self._reader.read_region((x, y), 0, (new_width, new_height)) - prediction = pyvips.Image.black(self._region_size[0], self._region_size[1]) - prediction = prediction.insert(clipped_region, 0, 0) - return prediction + # The new width and height can be negative if the coordinates x or y are outside the image. + if new_width > 0 and new_height > 0: + clipped_region = self._reader.read_region((x, y), 0, (new_width, new_height)) + prediction = prediction.insert(clipped_region, 0, 0) + + return prediction.numpy() def _get_annotation_data( self, coordinates: tuple[int, int] diff --git a/ahcore/writers.py b/ahcore/writers.py index 1a59997..1baaefc 100644 --- a/ahcore/writers.py +++ b/ahcore/writers.py @@ -314,7 +314,12 @@ def consume(self, batch_generator: Generator[tuple[GenericNumberArray, GenericNu def init_writer(self, first_coordinates: GenericNumberArray, first_batch: GenericNumberArray, file: Any) -> Any: """Initializes the image_dataset based on the first tile.""" - self._grid_offset = (int(first_coordinates[0][0]), int(first_coordinates[0][1])) + if self._grid is None: + # If the grid is not given to the constructor, we take the first element of the coordinates as the offset. + self._grid_offset = (int(first_coordinates[0][0]), int(first_coordinates[0][1])) + else: + # If the grid is given to the constructor, we take the first element of the grid as the offset. + self._grid_offset = tuple(self._grid[0]) writer_metadata = self.get_writer_metadata(first_batch)