Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
21 changes: 15 additions & 6 deletions packages/scratch-core/src/computations/spatial.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,25 @@
from container_models.base import BinaryMask


def get_bounding_box(mask: BinaryMask) -> tuple[slice, slice]:
def get_bounding_box(mask: BinaryMask, margin: int) -> tuple[slice, slice]:
Comment thread
Raytesnel marked this conversation as resolved.
"""
Compute the minimal bounding box of a 2D mask.

Finds the smallest axis-aligned rectangle containing all non-zero (or True) values.

:param mask: 2D mask (non-zero/True values indicate the region of interest)
:returns: Tuple (y_slice, x_slice) as slices for NumPy indexing, covering all mask pixels
:param margin: Margin around the bounding box to either crop (positive) or extend (negative) the bounding box
:returns: Tuple (y_slice, x_slice) as slices for bounding_box.
"""
coordinates = np.nonzero(mask)
y_min, x_min = np.min(coordinates, axis=1)
y_max, x_max = np.max(coordinates, axis=1)
return slice(y_min, y_max + 1), slice(x_min, x_max + 1)
y_coords, x_coords = np.nonzero(mask)
y_min = max(0, y_coords.min() + margin)
y_max = min(mask.shape[0], y_coords.max() - margin + 1)
x_min = max(0, x_coords.min() + margin)
x_max = min(mask.shape[1], x_coords.max() - margin + 1)

if x_min >= x_max:
raise ValueError("Slice results in x_min >= x_max. Margin may be too large.")
if y_min >= y_max:
raise ValueError("Slice results in y_min >= y_max. Margin may be too large.")

return slice(y_min, y_max), slice(x_min, x_max)
32 changes: 3 additions & 29 deletions packages/scratch-core/src/conversion/mask.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import numpy as np

from container_models.base import FloatArray2D, BinaryMask
from computations.spatial import get_bounding_box
from container_models.base import BinaryMask, FloatArray2D
from container_models.scan_image import ScanImage


Expand Down Expand Up @@ -36,37 +37,10 @@ def crop_to_mask(
:param margin: Margin around the bounding box to either crop (positive) or extend (negative) the bounding box
:return: Cropped image containing only the masked region
"""
x_slice, y_slice = get_bounding_box(mask, margin)
y_slice, x_slice = get_bounding_box(mask, margin)
return image[y_slice, x_slice]


def get_bounding_box(mask: BinaryMask, margin: int = 0) -> tuple[slice, slice]:
"""
Determines the bounding box of non-zero values in a mask. If a margin is given, the bounding box will be expanded
(in case of a negative margin) or cropped (in case of a positive margin) by `margin` pixels per side.

:param mask: Binary mask array
:param margin: Margin around the bounding box to either crop (positive) or extend (negative) the bounding box
:return: Tuple of (x_slice, y_slice) for the bounding box
"""
non_zero_coords = np.nonzero(mask)
if not non_zero_coords[0].size:
raise ValueError("Mask is empty")

y_coords, x_coords = np.nonzero(mask)
y_min = max(0, y_coords.min() + margin)
y_max = min(mask.shape[0], y_coords.max() - margin + 1)
x_min = max(0, x_coords.min() + margin)
x_max = min(mask.shape[1], x_coords.max() - margin + 1)

if x_min >= x_max:
raise ValueError("Slice results in x_min >= x_max. Margin may be too large.")
if y_min >= y_max:
raise ValueError("Slice results in y_min >= y_max. Margin may be too large.")

return slice(x_min, x_max), slice(y_min, y_max)


def mask_and_crop_2d_array(
image: FloatArray2D, mask: BinaryMask, crop: bool = False
) -> FloatArray2D:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import numpy as np
from scipy.ndimage import binary_erosion
from skimage.measure import ransac, CircleModel
from skimage.measure import CircleModel, ransac

from computations.spatial import get_bounding_box
from container_models.base import BinaryMask, FloatArray2D
from conversion.data_formats import Mark, MarkType
from conversion.mask import get_bounding_box
from conversion.preprocess_impression.utils import Point2D

RANDOM_SEED = 1234
Expand Down Expand Up @@ -84,7 +84,7 @@ def _get_bounding_box_center(mask: BinaryMask) -> Point2D:
:param mask: Boolean mask array.
:return: Center (x, y) in pixel coordinates.
"""
x_slice, y_slice = get_bounding_box(mask)
y_slice, x_slice = get_bounding_box(mask, margin=0)
return (
(x_slice.start + x_slice.stop) / 2,
(y_slice.start + y_slice.stop) / 2,
Expand Down
166 changes: 0 additions & 166 deletions packages/scratch-core/src/conversion/remove_needles.py

This file was deleted.

112 changes: 1 addition & 111 deletions packages/scratch-core/src/conversion/rotate.py
Original file line number Diff line number Diff line change
@@ -1,117 +1,7 @@
import numpy as np
from scipy.ndimage import binary_dilation, rotate
from scipy.ndimage import rotate

from container_models.base import BinaryMask
from container_models.scan_image import ScanImage
from conversion.data_formats import BoundingBox
from conversion.mask import crop_to_mask
from conversion.remove_needles import mask_and_remove_needles
from conversion.utils import update_scan_image_data
from mutations.spatial import Rotate

# Number of iterations to dilate a mask before it is rotated
DILATE_STEPS = 3


def rotate_crop_and_mask_image_by_crop(
scan_image: ScanImage,
mask: BinaryMask,
bounding_box: BoundingBox | None,
median_factor: float = 15,
) -> ScanImage:
"""
Rotates, crops and masks a scan image based on the given mask and rectangle.

Implements the following flow:
- Determine the rotation angle for the image and mask by the bounding box of rectangle, if a rectangle is given.
Otherwise, the rotation angle is 0.
- If the rotation angle is not 0, the mask is binary dilated using DILATE_STEPS iterations to correct for
imperfections when rotating. A margin is determined to reduce the final image to compensate for the dilation.
- The mask and image are cropped to the bounds of the mask.
- The scan image is masked using the cropped mask and cleaned of needles (i.e. steep slopes). The parameter
`times_median` is used to determine the threshold to find outliers.
- The image and mask are rotated by rotation_angle.
- The rotated image is cropped to the bounds of the rotated mask, using margin to compensate for dilation.

:param scan_image: Scan image to rotate, mask and crop.
:param mask: Binary mask array.
:param bounding_box: Bounding box of a rectangular crop region used to determine the rotation of an
image, or None. Expects pixel coordinates, i.e. top-left origin.
:param median_factor: Parameter used to determine what is considered an outlier when removing outliers/needles.
:return: The cropped, rotated and masked scan image.
"""
if (
bounding_box is None
): # TODO: This check should belong to higher level calls like API and determin to skip rotation
rotator = Rotate(rotation_angle=0.0)
else:
rotator = Rotate.from_bounding_box(bounding_box=bounding_box)
margin = 0
if not np.isclose(rotator.rotation_angle, 0.0):
mask = binary_dilation(mask, iterations=DILATE_STEPS).astype(bool)
# Define a margin to reverse dilation later on
margin = DILATE_STEPS + 2

scan_image_cropped, mask_cropped = crop_image_and_mask_to_mask(
Comment thread
SimoneAriens marked this conversation as resolved.
scan_image, mask, margin
)

scan_image_cleaned_and_masked = mask_and_remove_needles(
scan_image_cropped, mask_cropped, median_factor
)

scan_image_rotated = rotator(scan_image=scan_image_cleaned_and_masked).unwrap()
mask_rotated = rotate_mask(mask=mask_cropped, rotation_angle=rotator.rotation_angle)

scan_image_cropped = update_scan_image_data(
scan_image, crop_to_mask(scan_image_rotated.data, mask_rotated, margin)
)
return scan_image_cropped


def get_rotation_angle(bounding_box: BoundingBox) -> float:
"""
Calculate the rotation angle of a rectangular crop region.

Determines the rotation angle by computing the angles between edges and the x-axis, and selecting the angle with
the smallest absolute value.

:param bounding_box: Bounding box of a rectangular crop region. Expects pixel coordinates,
i.e. top-left origin, in the order [x, y].
:return: The rotation angle in degrees, ranging from -180 to 180 (inclusive).
"""
angles = []
for i in range(4):
point1 = bounding_box[i]
point2 = bounding_box[(i + 1) % 4]
angles.append(
np.degrees(np.arctan2(point2[1] - point1[1], point2[0] - point1[0]))
)

# find smallest absolute angle
rotation_angle = min(angles, key=lambda x: abs(x))

return rotation_angle


def crop_image_and_mask_to_mask(
scan_image: ScanImage, mask: BinaryMask, margin: int
) -> tuple[ScanImage, BinaryMask]:
"""
Crop scan_image.data and the mask itself to the bounding box of the mask. If a margin is given, the bounding box
will be expanded (in case of a negative margin) or cropped (in case of a positive margin) by that amount.

:param scan_image: Scan image to crop.
:param mask: Binary mask array.
:param margin: Margin around the bounding box to either crop (positive) or extend (negative) the bounding box.
:return: Tuple of the cropped scan_image and mask.
"""
scan_image_cropped = update_scan_image_data(
scan_image, crop_to_mask(scan_image.data, mask, margin)
)
mask_cropped = crop_to_mask(mask.astype(float), mask, margin).astype(bool)

return scan_image_cropped, mask_cropped


def rotate_mask(mask: BinaryMask, rotation_angle: float) -> BinaryMask:
Expand Down
Loading
Loading