Skip to content

Commit

Permalink
feat: add function to handle out of bounds coordinates for a RegionBo…
Browse files Browse the repository at this point in the history
…x in an image
  • Loading branch information
strixy16 committed Feb 7, 2025
1 parent 6eb58ea commit ec9359a
Showing 1 changed file with 20 additions and 10 deletions.
30 changes: 20 additions & 10 deletions src/imgtools/coretypes/box.py
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,21 @@ def _adjust_negative_coordinates(
setattr(min_coord, axis, 0)
setattr(max_coord, axis, getattr(max_coord, axis) + diff)


def check_out_of_bounds_coordinates(self, image: sitk.Image) -> None:
"""Adjust the coordinates to ensure that the max values are not greater than the image size."""
# if any of the max values are greater than the image size, set them to the image size,
# and subtract the difference from the min values
for idx, axis in enumerate(["x", "y", "z"]):
max_value = getattr(self.max, axis)
image_size = image.GetSize()[idx]
if max_value > image_size:
logger.debug(f"Adjusting box {axis} coordinates to be within the image size.")
diff = max_value - image_size
setattr(self.min, axis, getattr(self.min, axis) - diff)
setattr(self.max, axis, image_size)


def crop_image(self, image: sitk.Image) -> sitk.Image:
"""Crop an image to the coordinates defined by the box.
Expand All @@ -327,17 +342,12 @@ def crop_image(self, image: sitk.Image) -> sitk.Image:
The cropped image.
"""
try:
self.check_out_of_bounds_coordinates(image)
cropped_image = sitk.RegionOfInterest(image, self.size, self.min)
except RuntimeError as e:
msg = (
f"The box {self} is outside"
f" the image size {calculate_image_boundaries(image)} "
)
# this is probably due to the box being outside the image
# try to crop the image to the largest possible region
# we could handle this in the future, for now let it raise the error
# and make user try again with an adjusted box
raise BoundingBoxOutsideImageError(msg) from e
except Exception as e:
msg = f"Error cropping image to the box: {e}"
logger.exception(msg)
raise e
else:
return cropped_image

Expand Down

0 comments on commit ec9359a

Please sign in to comment.