Your ad could be here - Reach CV/ML engineers
Contact for advertisingContactInterested in advertising?
Contact usStay updated
News & Insightsalbumentations.augmentations.geometric.functional
Functional implementations of geometric image transformations. This module provides low-level functions for geometric operations such as rotation, resizing, flipping, perspective transforms, and affine transformations on images, bounding boxes and keypoints.
Members
- functionadjust_padding_by_position
- functionalmost_equal_intervals
- functionapply_affine_to_points
- functionbbox_distort_image
- functionbboxes_affine
- functionbboxes_affine_ellipse
- functionbboxes_affine_largest_box
- functionbboxes_d4
- functionbboxes_grid_shuffle
- functionbboxes_hflip
- functionbboxes_morphology
- functionbboxes_piecewise_affine
- functionbboxes_rot90
- functionbboxes_transpose
- functionbboxes_vflip
- functioncalculate_affine_transform_padding
- functioncenter
- functioncenter_bbox
- functioncompute_affine_warp_output_shape
- functioncompute_pairwise_distances
- functioncompute_perspective_params
- functioncompute_tps_weights
- functioncompute_transformed_image_bounds
- functioncopy_make_border_with_value_extension
- functioncreate_affine_transformation_matrix
- functioncreate_piecewise_affine_maps
- functioncreate_shape_groups
- functiond4
- functiondilate
- functiondistort_image
- functiondistort_image_keypoints
- functionerode
- functionexpand_transform
- functionextend_value
- functionfind_keypoint
- functionflip_bboxes
- functionflip_keypoints
- functionfrom_distance_maps
- functiongenerate_control_points
- functiongenerate_displacement_fields
- functiongenerate_distorted_grid_polygons
- functiongenerate_grid
- functiongenerate_inverse_distortion_map
- functiongenerate_perspective_points
- functiongenerate_reflected_bboxes
- functiongenerate_reflected_keypoints
- functiongenerate_shuffled_splits
- functionget_camera_matrix_distortion_maps
- functionget_dimension_padding
- functionget_fisheye_distortion_maps
- functionget_pad_grid_dimensions
- functionget_padding_params
- functionis_identity_matrix
- functionis_valid_component
- functionkeypoints_affine
- functionkeypoints_d4
- functionkeypoints_hflip
- functionkeypoints_rot90
- functionkeypoints_scale
- functionkeypoints_transpose
- functionkeypoints_vflip
- functionmorphology
- functionnormalize_grid_distortion_steps
- functionorder_points
- functionpad
- functionpad_bboxes
- functionpad_images_with_params
- functionpad_keypoints
- functionpad_with_params
- functionperspective
- functionperspective_bboxes
- functionperspective_keypoints
- functionremap
- functionremap_bboxes
- functionremap_keypoints
- functionremap_keypoints_via_mask
- functionresize
- functionrot90
- functionrotation2d_matrix_to_euler_angles
- functionscale
- functionshift_bboxes
- functionshift_keypoints
- functionshuffle_tiles_within_shape_groups
- functionsplit_uniform_grid
- functionswap_tiles_on_image
- functionswap_tiles_on_keypoints
- functionto_distance_maps
- functiontps_transform
- functiontranspose
- functionvalidate_bboxes
- functionvalidate_if_not_found_coords
- functionvalidate_keypoints
- functionvolume_hflip
- functionvolume_rot90
- functionvolume_vflip
- functionvolumes_hflip
- functionvolumes_rot90
- functionvolumes_vflip
- functionwarp_affine
- functionwarp_affine_with_value_extension
adjust_padding_by_positionfunction
Adjust padding values based on desired position.
Parameters
Name | Type | Default | Description |
---|---|---|---|
h_top | int | - | - |
h_bottom | int | - | - |
w_left | int | - | - |
w_right | int | - | - |
position | One of:
| - | - |
py_random | np.random.RandomState | - | - |
almost_equal_intervalsfunction
Generates an array of nearly equal integer intervals that sum up to `n`. This function divides the number `n` into `parts` nearly equal parts. It ensures that the sum of all parts equals `n`, and the difference between any two parts is at most one. This is useful for distributing a total amount into nearly equal discrete parts.
Parameters
Name | Type | Default | Description |
---|---|---|---|
n | int | - | The total value to be split. |
parts | int | - | The number of parts to split into. |
Returns
- np.ndarray: An array of integers where each integer represents the size of a part.
Examples
>>> almost_equal_intervals(20, 3)
array([7, 7, 6]) # Splits 20 into three parts: 7, 7, and 6
>>> almost_equal_intervals(16, 4)
array([4, 4, 4, 4]) # Splits 16 into four equal parts
apply_affine_to_pointsfunction
Apply affine transformation to a set of points. This function handles potential division by zero by replacing zero values in the homogeneous coordinate with a small epsilon value.
Parameters
Name | Type | Default | Description |
---|---|---|---|
points | np.ndarray | - | Array of points with shape (N, 2). |
matrix | np.ndarray | - | 3x3 affine transformation matrix. |
Returns
- np.ndarray: Transformed points with shape (N, 2).
bbox_distort_imagefunction
Distort bounding boxes based on a generated mesh. This function applies a perspective transformation to each bounding box based on the provided generated mesh. It ensures that the bounding boxes are clipped to the image boundaries after transformation.
Parameters
Name | Type | Default | Description |
---|---|---|---|
bboxes | np.ndarray | - | The bounding boxes to distort. |
generated_mesh | np.ndarray | - | The generated mesh to distort the bounding boxes with. |
image_shape | tuple[int, int] | - | The shape of the image as (height, width). |
Returns
- np.ndarray: The distorted bounding boxes.
bboxes_affinefunction
Apply an affine transformation to bounding boxes. For reflection border modes (cv2.BORDER_REFLECT_101, cv2.BORDER_REFLECT), this function: 1. Calculates necessary padding to avoid information loss 2. Applies padding to the bounding boxes 3. Adjusts the transformation matrix to account for padding 4. Applies the affine transformation 5. Validates the transformed bounding boxes For other border modes, it directly applies the affine transformation without padding.
Parameters
Name | Type | Default | Description |
---|---|---|---|
bboxes | np.ndarray | - | Input bounding boxes |
matrix | np.ndarray | - | Affine transformation matrix |
rotate_method | One of:
| - | Method for rotating bounding boxes ('largest_box' or 'ellipse') |
image_shape | tuple[int, int] | - | Shape of the input image |
border_mode | int | - | OpenCV border mode |
output_shape | tuple[int, int] | - | Shape of the output image |
Returns
- np.ndarray: Transformed and normalized bounding boxes
bboxes_affine_ellipsefunction
Apply an affine transformation to bounding boxes using an ellipse approximation method. This function transforms bounding boxes by approximating each box with an ellipse, transforming points along the ellipse's circumference, and then computing the new bounding box that encloses the transformed ellipse.
Parameters
Name | Type | Default | Description |
---|---|---|---|
bboxes | np.ndarray | - | An array of bounding boxes with shape (N, 4+) where N is the number of bounding boxes. Each row should contain [x_min, y_min, x_max, y_max] followed by any additional attributes (e.g., class labels). |
matrix | np.ndarray | - | The 3x3 affine transformation matrix to apply. |
Returns
- np.ndarray: An array of transformed bounding boxes with the same shape as the input.
Notes
- This function assumes that the input bounding boxes are in the format [x_min, y_min, x_max, y_max]. - The ellipse approximation method can provide a tighter bounding box compared to the largest box method, especially for rotations. - 360 points are used to approximate each ellipse, which provides a good balance between accuracy and computational efficiency. - Any additional attributes beyond the first 4 coordinates are preserved unchanged. - This method may be more suitable for objects that are roughly elliptical in shape.
bboxes_affine_largest_boxfunction
Apply an affine transformation to bounding boxes and return the largest enclosing boxes. This function transforms each corner of every bounding box using the given affine transformation matrix, then computes the new bounding boxes that fully enclose the transformed corners.
Parameters
Name | Type | Default | Description |
---|---|---|---|
bboxes | np.ndarray | - | An array of bounding boxes with shape (N, 4+) where N is the number of bounding boxes. Each row should contain [x_min, y_min, x_max, y_max] followed by any additional attributes (e.g., class labels). |
matrix | np.ndarray | - | The 3x3 affine transformation matrix to apply. |
Returns
- np.ndarray: An array of transformed bounding boxes with the same shape as the input.
Examples
>>> bboxes = np.array([[10, 10, 20, 20, 1], [30, 30, 40, 40, 2]]) # Two boxes with class labels
>>> matrix = np.array([[2, 0, 5], [0, 2, 5], [0, 0, 1]]) # Scale by 2 and translate by (5, 5)
>>> transformed_bboxes = bboxes_affine_largest_box(bboxes, matrix)
>>> print(transformed_bboxes)
[[ 25. 25. 45. 45. 1.]
[ 65. 65. 85. 85. 2.]]
Notes
- This function assumes that the input bounding boxes are in the format [x_min, y_min, x_max, y_max]. - The resulting bounding boxes are the smallest axis-aligned boxes that completely enclose the transformed original boxes. They may be larger than the minimal possible bounding box if the original box becomes rotated. - Any additional attributes beyond the first 4 coordinates are preserved unchanged. - This method is called "largest box" because it returns the largest axis-aligned box that encloses all corners of the transformed bounding box.
bboxes_d4function
Applies a `D_4` symmetry group transformation to a bounding box. The function transforms a bounding box according to the specified group member from the `D_4` group. These transformations include rotations and reflections, specified to work on an image's bounding box given its dimensions. Args: bboxes (np.ndarray): A numpy array of bounding boxes with shape (num_bboxes, 4+). Each row represents a bounding box (x_min, y_min, x_max, y_max, ...). group_member (Literal["e", "r90", "r180", "r270", "v", "hvt", "h", "t"]): A string identifier for the `D_4` group transformation to apply. Returns: BoxInternalType: The transformed bounding box. Raises: ValueError: If an invalid group member is specified.
Parameters
Name | Type | Default | Description |
---|---|---|---|
bboxes | np.ndarray | - | - |
group_member | One of:
| - | - |
Returns
- BoxInternalType: The transformed bounding box.
bboxes_grid_shufflefunction
Shuffle bounding boxes according to grid mapping.
Parameters
Name | Type | Default | Description |
---|---|---|---|
bboxes | np.ndarray | - | Array of bounding boxes with shape (num_boxes, 4+) |
tiles | np.ndarray | - | Array of grid tiles |
mapping | list[int] | - | Mapping of tile indices |
image_shape | tuple[int, int] | - | Shape of the image (height, width) |
min_area | float | - | Minimum area of a bounding box to keep |
min_visibility | float | - | Minimum visibility ratio of a bounding box to keep |
Returns
- np.ndarray: Shuffled bounding boxes
bboxes_hflipfunction
Flip bounding boxes horizontally.
Parameters
Name | Type | Default | Description |
---|---|---|---|
bboxes | np.ndarray | - | Array of bounding boxes with shape (num_boxes, 4+) |
Returns
- np.ndarray: Horizontally flipped bounding boxes
bboxes_morphologyfunction
Apply morphology to bounding boxes. This function applies morphology to bounding boxes by first converting the bounding boxes to a mask and then applying the morphology to the mask.
Parameters
Name | Type | Default | Description |
---|---|---|---|
bboxes | np.ndarray | - | Bounding boxes as a numpy array. |
kernel | np.ndarray | - | Kernel as a numpy array. |
operation | One of:
| - | The operation to apply. |
image_shape | tuple[int, int] | - | The shape of the image. |
Returns
- np.ndarray: The morphology applied to the bounding boxes.
bboxes_piecewise_affinefunction
Apply a piecewise affine transformation to bounding boxes. This function applies a piecewise affine transformation to the bounding boxes of an image. It first converts the bounding boxes to masks, then applies the transformation, and finally converts the transformed masks back to bounding boxes.
Parameters
Name | Type | Default | Description |
---|---|---|---|
bboxes | np.ndarray | - | The bounding boxes to transform. |
map_x | np.ndarray | - | The x-coordinates of the transformation. |
map_y | np.ndarray | - | The y-coordinates of the transformation. |
border_mode | int | - | The border mode to use for the transformation. |
image_shape | tuple[int, int] | - | The shape of the image. |
Returns
- np.ndarray: The transformed bounding boxes.
bboxes_rot90function
Rotates bounding boxes by 90 degrees CCW (see np.rot90)
Parameters
Name | Type | Default | Description |
---|---|---|---|
bboxes | np.ndarray | - | Array of bounding boxes with shape (num_boxes, 4+) |
factor | int | - | Number of 90-degree rotations (1, 2, or 3) |
Returns
- np.ndarray: Rotated bounding boxes
bboxes_transposefunction
Transpose bounding boxes along the main diagonal.
Parameters
Name | Type | Default | Description |
---|---|---|---|
bboxes | np.ndarray | - | Array of bounding boxes with shape (num_boxes, 4+) |
Returns
- np.ndarray: Transposed bounding boxes
bboxes_vflipfunction
Flip bounding boxes vertically.
Parameters
Name | Type | Default | Description |
---|---|---|---|
bboxes | np.ndarray | - | Array of bounding boxes with shape (num_boxes, 4+) |
Returns
- np.ndarray: Vertically flipped bounding boxes
calculate_affine_transform_paddingfunction
Calculate the necessary padding for an affine transformation to avoid empty spaces.
Parameters
Name | Type | Default | Description |
---|---|---|---|
matrix | np.ndarray | - | - |
image_shape | tuple[int, int] | - | - |
centerfunction
Calculate the center coordinates if image. Used by images, masks and keypoints.
Parameters
Name | Type | Default | Description |
---|---|---|---|
image_shape | tuple[int, int] | - | The shape of the image. |
Returns
- tuple[float, float]: center_x, center_y
center_bboxfunction
Calculate the center coordinates for of image for bounding boxes.
Parameters
Name | Type | Default | Description |
---|---|---|---|
image_shape | tuple[int, int] | - | The shape of the image. |
Returns
- tuple[float, float]: center_x, center_y
compute_affine_warp_output_shapefunction
Compute the output shape of an affine warp. This function computes the output shape of an affine warp based on the input matrix and input shape. It calculates the transformed image bounds and then determines the output shape based on the input shape.
Parameters
Name | Type | Default | Description |
---|---|---|---|
matrix | np.ndarray | - | The 3x3 affine transformation matrix. |
input_shape | tuple[int, ...] | - | The shape of the input image as (height, width, ...). |
Returns
- tuple[np.ndarray, tuple[int, int]]: A tuple containing:
compute_pairwise_distancesfunction
Compute pairwise distances between two sets of points.
Parameters
Name | Type | Default | Description |
---|---|---|---|
points1 | np.ndarray | - | First set of points with shape (N, 2) |
points2 | np.ndarray | - | Second set of points with shape (M, 2) |
Returns
- np.ndarray: Matrix of pairwise distances with shape (N, M)
compute_perspective_paramsfunction
Compute perspective transformation parameters. This function computes the perspective transformation parameters for a given set of points. It adjusts the points to ensure that the transformed image retains its original dimensions.
Parameters
Name | Type | Default | Description |
---|---|---|---|
points | np.ndarray | - | The points to compute the perspective transformation parameters for. |
image_shape | tuple[int, int] | - | The shape of the image. |
Returns
- tuple[np.ndarray, int, int]: The perspective transformation parameters and the maximum
compute_tps_weightsfunction
Compute Thin Plate Spline weights.
Parameters
Name | Type | Default | Description |
---|---|---|---|
src_points | np.ndarray | - | Source control points with shape (num_points, 2) |
dst_points | np.ndarray | - | Destination control points with shape (num_points, 2) |
Returns
- tuple[np.ndarray, np.ndarray]: Tuple of (nonlinear_weights, affine_weights)
compute_transformed_image_boundsfunction
Compute the bounds of an image after applying an affine transformation.
Parameters
Name | Type | Default | Description |
---|---|---|---|
matrix | np.ndarray | - | The 3x3 affine transformation matrix. |
image_shape | tuple[int, int] | - | The shape of the image as (height, width). |
Returns
- tuple[np.ndarray, np.ndarray]: A tuple containing:
copy_make_border_with_value_extensionfunction
Copy and make border with value extension. This function copies and makes border with value extension. It is used to pad an image with a given value.
Parameters
Name | Type | Default | Description |
---|---|---|---|
img | np.ndarray | - | The image to pad. |
top | int | - | The amount to pad the top of the image. |
bottom | int | - | The amount to pad the bottom of the image. |
left | int | - | The amount to pad the left of the image. |
right | int | - | The amount to pad the right of the image. |
border_mode | int | - | The border mode to use. |
value | One of:
| - | The value to pad the image with. |
Returns
- np.ndarray: The padded image.
create_affine_transformation_matrixfunction
Create an affine transformation matrix combining translation, shear, scale, and rotation.
Parameters
Name | Type | Default | Description |
---|---|---|---|
translate | Mapping[str, float] | - | Translation in x and y directions. |
shear | dict[str, float] | - | Shear in x and y directions (in degrees). |
scale | dict[str, float] | - | Scale factors for x and y directions. |
rotate | float | - | Rotation angle in degrees. |
shift | tuple[float, float] | - | Shift to apply before and after transformations. |
Returns
- np.ndarray: The resulting 3x3 affine transformation matrix.
create_piecewise_affine_mapsfunction
Create maps for piecewise affine transformation using OpenCV's remap function. This function creates maps for piecewise affine transformation using OpenCV's remap function. It generates the control points for the transformation, then uses the remap function to create the transformation maps.
Parameters
Name | Type | Default | Description |
---|---|---|---|
image_shape | tuple[int, int] | - | The shape of the image as (height, width). |
grid | tuple[int, int] | - | The grid size as (rows, columns). |
scale | float | - | The scale of the transformation. |
absolute_scale | bool | - | Whether to use absolute scale. |
random_generator | np.random.Generator | - | The random generator to use for generating the points. |
Returns
- tuple[np.ndarray | None, np.ndarray | None]: The transformation maps.
create_shape_groupsfunction
Groups tiles by their shape and stores the indices for each shape.
Parameters
Name | Type | Default | Description |
---|---|---|---|
tiles | np.ndarray | - | - |
d4function
Applies a `D_4` symmetry group transformation to an image array. This function manipulates an image using transformations such as rotations and flips, corresponding to the `D_4` dihedral group symmetry operations. Each transformation is identified by a unique group member code.
Parameters
Name | Type | Default | Description |
---|---|---|---|
img | np.ndarray | - | The input image array to transform. |
group_member | One of:
| - | A string identifier indicating the specific transformation to apply. Valid codes include: - 'e': Identity (no transformation). - 'r90': Rotate 90 degrees counterclockwise. - 'r180': Rotate 180 degrees. - 'r270': Rotate 270 degrees counterclockwise. - 'v': Vertical flip. - 'hvt': Transpose over second diagonal - 'h': Horizontal flip. - 't': Transpose (reflect over the main diagonal). |
Returns
- np.ndarray: The transformed image array.
dilatefunction
Apply dilation to an image. This function applies dilation to an image using the cv2.dilate function.
Parameters
Name | Type | Default | Description |
---|---|---|---|
img | np.ndarray | - | Input image as a numpy array. |
kernel | np.ndarray | - | Kernel as a numpy array. |
Returns
- np.ndarray: The dilated image.
distort_imagefunction
Apply perspective distortion to an image based on a generated mesh. This function applies a perspective transformation to each cell of the image defined by the generated mesh. The distortion is applied using OpenCV's perspective transformation and blending techniques.
Parameters
Name | Type | Default | Description |
---|---|---|---|
image | np.ndarray | - | The input image to be distorted. Can be a 2D grayscale image or a 3D color image. |
generated_mesh | np.ndarray | - | A 2D array where each row represents a quadrilateral cell as [x1, y1, x2, y2, dst_x1, dst_y1, dst_x2, dst_y2, dst_x3, dst_y3, dst_x4, dst_y4]. The first four values define the source rectangle, and the last eight values define the destination quadrilateral. |
interpolation | int | - | Interpolation method to be used in the perspective transformation. Should be one of the OpenCV interpolation flags (e.g., cv2.INTER_LINEAR). |
Returns
- np.ndarray: The distorted image with the same shape and dtype as the input image.
Examples
>>> image = np.random.randint(0, 255, (100, 100, 3), dtype=np.uint8)
>>> mesh = np.array([[0, 0, 50, 50, 5, 5, 45, 5, 45, 45, 5, 45]])
>>> distorted = distort_image(image, mesh, cv2.INTER_LINEAR)
>>> distorted.shape
(100, 100, 3)
Notes
- The function preserves the channel dimension of the input image. - Each cell of the generated mesh is transformed independently and then blended into the output image. - The distortion is applied using perspective transformation, which allows for more complex distortions compared to affine transformations.
distort_image_keypointsfunction
Distort keypoints based on a generated mesh. This function applies a perspective transformation to each keypoint based on the provided generated mesh. It ensures that the keypoints are clipped to the image boundaries after transformation.
Parameters
Name | Type | Default | Description |
---|---|---|---|
keypoints | np.ndarray | - | The keypoints to distort. |
generated_mesh | np.ndarray | - | The generated mesh to distort the keypoints with. |
image_shape | tuple[int, int] | - | The shape of the image as (height, width). |
Returns
- np.ndarray: The distorted keypoints.
erodefunction
Apply erosion to an image. This function applies erosion to an image using the cv2.erode function.
Parameters
Name | Type | Default | Description |
---|---|---|---|
img | np.ndarray | - | Input image as a numpy array. |
kernel | np.ndarray | - | Kernel as a numpy array. |
Returns
- np.ndarray: The eroded image.
expand_transformfunction
Expand a transformation matrix to include padding. This function expands a transformation matrix to include padding, ensuring that the transformed image retains its original dimensions. It first calculates the destination points of the transformed image, then adjusts the matrix to include padding, and finally returns the expanded matrix and the maximum dimensions of the transformed image.
Parameters
Name | Type | Default | Description |
---|---|---|---|
matrix | np.ndarray | - | The transformation matrix to expand. |
shape | tuple[int, int] | - | The shape of the image. |
Returns
- tuple[np.ndarray, int, int]: The expanded matrix and the maximum dimensions of the transformed image.
extend_valuefunction
Extend value to a sequence of floats. This function extends a value to a sequence of floats. It is used to pad an image with a given value.
Parameters
Name | Type | Default | Description |
---|---|---|---|
value | One of:
| - | The value to extend. |
num_channels | int | - | The number of channels in the image. |
Returns
- Sequence[float]: The extended value.
find_keypointfunction
Determine if a valid keypoint can be found at the given position.
Parameters
Name | Type | Default | Description |
---|---|---|---|
position | tuple[int, int] | - | - |
distance_map | np.ndarray | - | - |
threshold | One of:
| - | - |
inverted | bool | - | - |
flip_bboxesfunction
Flip bounding boxes horizontally and/or vertically.
Parameters
Name | Type | Default | Description |
---|---|---|---|
bboxes | np.ndarray | - | Array of bounding boxes with shape (n, m) where each row is [x_min, y_min, x_max, y_max, ...]. |
flip_horizontal | bool | False | Whether to flip horizontally. |
flip_vertical | bool | False | Whether to flip vertically. |
image_shape | tuple[int, int] | (0, 0) | Shape of the image as (height, width). |
Returns
- np.ndarray: Flipped bounding boxes.
flip_keypointsfunction
Flip keypoints horizontally or vertically. This function flips keypoints horizontally or vertically based on the provided parameters. It also flips the angle of the keypoints when flipping horizontally.
Parameters
Name | Type | Default | Description |
---|---|---|---|
keypoints | np.ndarray | - | The keypoints to flip. |
flip_horizontal | bool | False | Whether to flip horizontally. |
flip_vertical | bool | False | Whether to flip vertically. |
image_shape | tuple[int, int] | (0, 0) | The shape of the image as (height, width). |
Returns
- np.ndarray: The flipped keypoints.
from_distance_mapsfunction
Convert distance maps back to keypoints coordinates. This function is the inverse of `to_distance_maps`. It takes distance maps generated for a set of keypoints and reconstructs the original keypoint coordinates. The function supports both regular and inverted distance maps, and can handle cases where keypoints are not found or fall outside a specified threshold.
Parameters
Name | Type | Default | Description |
---|---|---|---|
distance_maps | np.ndarray | - | A 3D numpy array of shape (height, width, nb_keypoints) containing distance maps for each keypoint. Each channel represents the distance map for one keypoint. |
inverted | bool | - | If True, treats the distance maps as inverted (where higher values indicate closer proximity to keypoints). If False, treats them as regular distance maps (where lower values indicate closer proximity). |
if_not_found_coords | One of:
| None | Coordinates to use for keypoints that are not found or fall outside the threshold. Can be: - None: Drop keypoints that are not found. - Sequence of two integers: Use these as (x, y) coordinates for not found keypoints. - Dict with 'x' and 'y' keys: Use these values for not found keypoints. Defaults to None. |
threshold | One of:
| None | A threshold value to determine valid keypoints. For inverted maps, values >= threshold are considered valid. For regular maps, values <= threshold are considered valid. If None, all keypoints are considered valid. Defaults to None. |
Returns
- np.ndarray: A 2D numpy array of shape (nb_keypoints, 2) containing the (x, y) coordinates
Examples
>>> distance_maps = np.random.rand(100, 100, 3) # 3 keypoints
>>> inverted = True
>>> if_not_found_coords = [0, 0]
>>> threshold = 0.5
>>> keypoints = from_distance_maps(distance_maps, inverted, if_not_found_coords, threshold)
>>> print(keypoints.shape)
(3, 2)
Notes
- The function uses vectorized operations for improved performance, especially with large numbers of keypoints. - When `threshold` is None, all keypoints are considered valid, and `if_not_found_coords` is not used. - The function assumes that the input distance maps are properly normalized and scaled according to the original image dimensions.
generate_control_pointsfunction
Generate control points for TPS transformation.
Parameters
Name | Type | Default | Description |
---|---|---|---|
num_control_points | int | - | Number of control points per side |
Returns
- np.ndarray: Control points with shape (N, 2)
generate_displacement_fieldsfunction
Generate displacement fields for elastic transform. This function generates displacement fields for elastic transform based on the provided parameters. It generates noise either from a Gaussian or uniform distribution and normalizes it to the range [-1, 1].
Parameters
Name | Type | Default | Description |
---|---|---|---|
image_shape | tuple[int, int] | - | The shape of the image as (height, width). |
alpha | float | - | The alpha parameter for the elastic transform. |
sigma | float | - | The sigma parameter for the elastic transform. |
same_dxdy | bool | - | Whether to use the same displacement field for both x and y directions. |
kernel_size | tuple[int, int] | - | The size of the kernel for the elastic transform. |
random_generator | np.random.Generator | - | The random number generator to use. |
noise_distribution | One of:
| - | The distribution of the noise. |
Returns
- tuple[np.ndarray, np.ndarray]: A tuple containing:
generate_distorted_grid_polygonsfunction
Generate distorted grid polygons based on input dimensions and magnitude. This function creates a grid of polygons and applies random distortions to the internal vertices, while keeping the boundary vertices fixed. The distortion is applied consistently across shared vertices to avoid gaps or overlaps in the resulting grid.
Parameters
Name | Type | Default | Description |
---|---|---|---|
dimensions | np.ndarray | - | A 3D array of shape (grid_height, grid_width, 4) where each element is [x_min, y_min, x_max, y_max] representing the dimensions of a grid cell. |
magnitude | int | - | Maximum pixel-wise displacement for distortion. The actual displacement will be randomly chosen in the range [-magnitude, magnitude]. |
random_generator | np.random.Generator | - | A random number generator. |
Returns
- np.ndarray: A 2D array of shape (total_cells, 8) where each row represents a distorted polygon
Examples
>>> dimensions = np.array([[[0, 0, 50, 50], [50, 0, 100, 50]],
... [[0, 50, 50, 100], [50, 50, 100, 100]]])
>>> distorted = generate_distorted_grid_polygons(dimensions, magnitude=10)
>>> distorted.shape
(4, 8)
Notes
- Only internal grid points are distorted; boundary points remain fixed. - The function ensures consistent distortion across shared vertices of adjacent cells. - The distortion is applied to the following points of each internal cell: * Bottom-right of the cell above and to the left * Bottom-left of the cell above * Top-right of the cell to the left * Top-left of the current cell - Each square represents a cell, and the X marks indicate the coordinates where displacement occurs. +--+--+--+--+ | | | | | +--X--X--X--+ | | | | | +--X--X--X--+ | | | | | +--X--X--X--+ | | | | | +--+--+--+--+ - For each X, the coordinates of the left, right, top, and bottom edges in the four adjacent cells are displaced.
generate_gridfunction
Generate a distorted grid for image transformation based on given step sizes. This function creates two 2D arrays (map_x and map_y) that represent a distorted version of the original image grid. These arrays can be used with OpenCV's remap function to apply grid distortion to an image.
Parameters
Name | Type | Default | Description |
---|---|---|---|
image_shape | tuple[int, int] | - | The shape of the image as (height, width). |
steps_x | list[float] | - | List of step sizes for the x-axis distortion. The length should be num_steps + 1. Each value represents the relative step size for a segment of the grid in the x direction. |
steps_y | list[float] | - | List of step sizes for the y-axis distortion. The length should be num_steps + 1. Each value represents the relative step size for a segment of the grid in the y direction. |
num_steps | int | - | The number of steps to divide each axis into. This determines the granularity of the distortion grid. |
Returns
- tuple[np.ndarray, np.ndarray]: A tuple containing two 2D numpy arrays:
Examples
>>> image_shape = (100, 100)
>>> steps_x = [1.1, 0.9, 1.0, 1.2, 0.95, 1.05]
>>> steps_y = [0.9, 1.1, 1.0, 1.1, 0.9, 1.0]
>>> num_steps = 5
>>> map_x, map_y = generate_grid(image_shape, steps_x, steps_y, num_steps)
>>> distorted_image = cv2.remap(image, map_x, map_y, cv2.INTER_LINEAR)
Notes
- The function generates a grid where each cell can be distorted independently. - The distortion is controlled by the steps_x and steps_y parameters, which determine how much each grid line is shifted. - The resulting map_x and map_y can be used directly with cv2.remap() to apply the distortion to an image. - The distortion is applied smoothly across each grid cell using linear interpolation.
generate_inverse_distortion_mapfunction
Generate inverse mapping for strong distortions.
Parameters
Name | Type | Default | Description |
---|---|---|---|
map_x | np.ndarray | - | - |
map_y | np.ndarray | - | - |
shape | tuple[int, int] | - | - |
generate_perspective_pointsfunction
Generate perspective points for a given image shape and scale. This function generates perspective points for a given image shape and scale. It uses a normal distribution to generate the points, and then modulates them to be within the image bounds.
Parameters
Name | Type | Default | Description |
---|---|---|---|
image_shape | tuple[int, int] | - | The shape of the image as (height, width). |
scale | float | - | The scale of the perspective points. |
random_generator | np.random.Generator | - | The random generator to use for generating the points. |
Returns
- np.ndarray: The perspective points.
generate_reflected_bboxesfunction
Generate reflected bounding boxes for the entire reflection grid.
Parameters
Name | Type | Default | Description |
---|---|---|---|
bboxes | np.ndarray | - | Original bounding boxes. |
grid_dims | dict[str, tuple[int, int]] | - | Grid dimensions and original position. |
image_shape | tuple[int, int] | - | Shape of the original image as (height, width). |
center_in_origin | bool | False | If True, center the grid at the origin. Default is False. |
Returns
- np.ndarray: Array of reflected and shifted bounding boxes for the entire grid.
generate_reflected_keypointsfunction
Generate reflected keypoints for the entire reflection grid. This function creates a grid of keypoints by reflecting and shifting the original keypoints. It handles both centered and non-centered grids based on the `center_in_origin` parameter.
Parameters
Name | Type | Default | Description |
---|---|---|---|
keypoints | np.ndarray | - | Original keypoints array of shape (N, 4+), where N is the number of keypoints, and each keypoint is represented by at least 4 values (x, y, angle, scale, ...). |
grid_dims | dict[str, tuple[int, int]] | - | A dictionary containing grid dimensions and original position. It should have the following keys: - "grid_shape": tuple[int, int] representing (grid_rows, grid_cols) - "original_position": tuple[int, int] representing (original_row, original_col) |
image_shape | tuple[int, int] | - | Shape of the original image as (height, width). |
center_in_origin | bool | False | If True, center the grid at the origin. Default is False. |
Returns
- np.ndarray: Array of reflected and shifted keypoints for the entire grid. The shape is
Notes
- The function handles keypoint flipping and shifting to create a grid of reflected keypoints. - It preserves the angle and scale information of the keypoints during transformations. - The resulting grid can be either centered at the origin or positioned based on the original grid.
generate_shuffled_splitsfunction
Generate shuffled splits for a given dimension size and number of divisions.
Parameters
Name | Type | Default | Description |
---|---|---|---|
size | int | - | Total size of the dimension (height or width). |
divisions | int | - | Number of divisions (rows or columns). |
random_generator | np.random.Generator | - | The random generator to use for shuffling the splits. If None, the splits are not shuffled. |
Returns
- np.ndarray: Cumulative edges of the shuffled intervals.
get_camera_matrix_distortion_mapsfunction
Generate distortion maps using camera matrix model.
Parameters
Name | Type | Default | Description |
---|---|---|---|
image_shape | tuple[int, int] | - | Image shape (height, width) |
k | float | - | Distortion coefficient |
Returns
- tuple[np.ndarray, np.ndarray]: Tuple of (map_x, map_y) distortion maps
get_dimension_paddingfunction
Calculate padding for a single dimension.
Parameters
Name | Type | Default | Description |
---|---|---|---|
current_size | int | - | Current size of the dimension |
min_size | One of:
| - | Minimum size requirement, if any |
divisor | One of:
| - | Divisor for padding to make size divisible, if any |
Returns
- tuple[int, int]: (pad_before, pad_after)
get_fisheye_distortion_mapsfunction
Generate distortion maps using fisheye model.
Parameters
Name | Type | Default | Description |
---|---|---|---|
image_shape | tuple[int, int] | - | Image shape (height, width) |
k | float | - | Distortion coefficient |
Returns
- tuple[np.ndarray, np.ndarray]: Tuple of (map_x, map_y) distortion maps
get_pad_grid_dimensionsfunction
Calculate the dimensions of the grid needed for reflection padding and the position of the original image.
Parameters
Name | Type | Default | Description |
---|---|---|---|
pad_top | int | - | Number of pixels to pad above the image. |
pad_bottom | int | - | Number of pixels to pad below the image. |
pad_left | int | - | Number of pixels to pad to the left of the image. |
pad_right | int | - | Number of pixels to pad to the right of the image. |
image_shape | tuple[int, int] | - | Shape of the original image as (height, width). |
Returns
- dict[str, tuple[int, int]]: A dictionary containing:
get_padding_paramsfunction
Calculate padding parameters based on target dimensions.
Parameters
Name | Type | Default | Description |
---|---|---|---|
image_shape | tuple[int, int] | - | (height, width) of the image |
min_height | One of:
| - | Minimum height requirement, if any |
min_width | One of:
| - | Minimum width requirement, if any |
pad_height_divisor | One of:
| - | Divisor for height padding, if any |
pad_width_divisor | One of:
| - | Divisor for width padding, if any |
Returns
- tuple[int, int, int, int]: (pad_top, pad_bottom, pad_left, pad_right)
is_identity_matrixfunction
Check if the given matrix is an identity matrix.
Parameters
Name | Type | Default | Description |
---|---|---|---|
matrix | np.ndarray | - | A 3x3 affine transformation matrix. |
Returns
- bool: True if the matrix is an identity matrix, False otherwise.
is_valid_componentfunction
Validate if a component meets the minimum requirements.
Parameters
Name | Type | Default | Description |
---|---|---|---|
component_area | float | - | - |
original_area | float | - | - |
min_area | One of:
| - | - |
min_visibility | One of:
| - | - |
keypoints_affinefunction
Apply an affine transformation to keypoints. This function transforms keypoints using the given affine transformation matrix. It handles reflection padding if necessary, updates coordinates, angles, and scales.
Parameters
Name | Type | Default | Description |
---|---|---|---|
keypoints | np.ndarray | - | Array of keypoints with shape (N, 4+) where N is the number of keypoints. Each keypoint is represented as [x, y, angle, scale, ...]. |
matrix | np.ndarray | - | The 2x3 or 3x3 affine transformation matrix. |
image_shape | tuple[int, int] | - | Shape of the image (height, width). |
scale | dict[str, float] | - | Dictionary containing scale factors for x and y directions. Expected keys are 'x' and 'y'. |
border_mode | int | - | Border mode for handling keypoints near image edges. Use cv2.BORDER_REFLECT_101, cv2.BORDER_REFLECT, etc. |
Returns
- np.ndarray: Transformed keypoints array with the same shape as input.
Examples
>>> keypoints = np.array([[100, 100, 0, 1]])
>>> matrix = np.array([[1.5, 0, 10], [0, 1.2, 20]])
>>> scale = {'x': 1.5, 'y': 1.2}
>>> transformed_keypoints = keypoints_affine(keypoints, matrix, (480, 640), scale, cv2.BORDER_REFLECT_101)
Notes
- The function applies reflection padding if the mode is in REFLECT_BORDER_MODES. - Coordinates (x, y) are transformed using the affine matrix. - Angles are adjusted based on the rotation component of the affine transformation. - Scales are multiplied by the maximum of x and y scale factors. - The @angle_2pi_range decorator ensures angles remain in the [0, 2Ï€] range.
keypoints_d4function
Applies a `D_4` symmetry group transformation to a keypoint. This function adjusts a keypoint's coordinates according to the specified `D_4` group transformation, which includes rotations and reflections suitable for image processing tasks. These transformations account for the dimensions of the image to ensure the keypoint remains within its boundaries.
Parameters
Name | Type | Default | Description |
---|---|---|---|
keypoints | np.ndarray | - | An array of keypoints with shape (N, 4+) in the format (x, y, angle, scale, ...). |
group_member | One of:
| - | A string identifier for the `D_4` group transformation to apply. Valid values are 'e', 'r90', 'r180', 'r270', 'v', 'hv', 'h', 't'. |
image_shape | tuple[int, int] | - | The shape of the image. |
Returns
- KeypointInternalType: The transformed keypoint.
keypoints_hflipfunction
Flip keypoints horizontally.
Parameters
Name | Type | Default | Description |
---|---|---|---|
keypoints | np.ndarray | - | Array of keypoints with shape (num_keypoints, 2+) |
cols | int | - | Number of columns in the image |
Returns
- np.ndarray: Horizontally flipped keypoints
keypoints_rot90function
Rotate keypoints by 90 degrees counter-clockwise (CCW) a specified number of times.
Parameters
Name | Type | Default | Description |
---|---|---|---|
keypoints | np.ndarray | - | An array of keypoints with shape (N, 4+) in the format (x, y, angle, scale, ...). |
factor | One of:
| - | The number of 90 degree CCW rotations to apply. Must be in the range [0, 3]. |
image_shape | tuple[int, int] | - | The shape of the image (height, width). |
Returns
- np.ndarray: The rotated keypoints with the same shape as the input.
keypoints_scalefunction
Scale keypoints by given factors.
Parameters
Name | Type | Default | Description |
---|---|---|---|
keypoints | np.ndarray | - | Array of keypoints with shape (num_keypoints, 2+) |
scale_x | float | - | Scale factor for x coordinates |
scale_y | float | - | Scale factor for y coordinates |
Returns
- np.ndarray: Scaled keypoints
keypoints_transposefunction
Transpose keypoints along the main diagonal.
Parameters
Name | Type | Default | Description |
---|---|---|---|
keypoints | np.ndarray | - | Array of keypoints with shape (num_keypoints, 2+) |
Returns
- np.ndarray: Transposed keypoints
keypoints_vflipfunction
Flip keypoints vertically.
Parameters
Name | Type | Default | Description |
---|---|---|---|
keypoints | np.ndarray | - | Array of keypoints with shape (num_keypoints, 2+) |
rows | int | - | Number of rows in the image |
Returns
- np.ndarray: Vertically flipped keypoints
morphologyfunction
Apply morphology to an image. This function applies morphology to an image using the cv2.morphologyEx function.
Parameters
Name | Type | Default | Description |
---|---|---|---|
img | np.ndarray | - | Input image as a numpy array. |
kernel | np.ndarray | - | Kernel as a numpy array. |
operation | One of:
| - | The operation to apply. |
Returns
- np.ndarray: The morphology applied to the image.
normalize_grid_distortion_stepsfunction
Normalize the grid distortion steps. This function normalizes the grid distortion steps, ensuring that the distortion never leaves the image bounds. It compensates for smaller last steps in the source image and normalizes the steps such that the distortion never leaves the image bounds.
Parameters
Name | Type | Default | Description |
---|---|---|---|
image_shape | tuple[int, int] | - | The shape of the image as (height, width). |
num_steps | int | - | The number of steps to divide each axis into. This determines the granularity of the distortion grid. |
x_steps | list[float] | - | List of step sizes for the x-axis distortion. The length should be num_steps + 1. Each value represents the relative step size for a segment of the grid in the x direction. |
y_steps | list[float] | - | List of step sizes for the y-axis distortion. The length should be num_steps + 1. Each value represents the relative step size for a segment of the grid in the y direction. |
Returns
- dict[str, np.ndarray]: A dictionary containing the normalized step sizes for the x and y axes.
order_pointsfunction
Order points in a clockwise manner. This function orders the points in a clockwise manner, ensuring that the points are in the correct order for perspective transformation.
Parameters
Name | Type | Default | Description |
---|---|---|---|
pts | np.ndarray | - | The points to order. |
Returns
- np.ndarray: The ordered points.
padfunction
Pad an image to ensure minimum dimensions. This function adds padding to an image if its dimensions are smaller than the specified minimum dimensions. Padding is added evenly on all sides.
Parameters
Name | Type | Default | Description |
---|---|---|---|
img | np.ndarray | - | Input image to pad. |
min_height | int | - | Minimum height of the output image. |
min_width | int | - | Minimum width of the output image. |
border_mode | int | - | OpenCV border mode for padding. |
value | One of:
| - | Value(s) to fill the border pixels. |
Returns
- np.ndarray: Padded image with dimensions at least (min_height, min_width).
pad_bboxesfunction
Pad bounding boxes by a given amount. This function pads bounding boxes by a given amount. It handles both reflection and padding.
Parameters
Name | Type | Default | Description |
---|---|---|---|
bboxes | np.ndarray | - | The bounding boxes to pad. |
pad_top | int | - | The amount to pad the top of the bounding boxes. |
pad_bottom | int | - | The amount to pad the bottom of the bounding boxes. |
pad_left | int | - | The amount to pad the left of the bounding boxes. |
pad_right | int | - | The amount to pad the right of the bounding boxes. |
border_mode | int | - | The border mode to use. |
image_shape | tuple[int, int] | - | The shape of the image as (height, width). |
Returns
- np.ndarray: The padded bounding boxes.
pad_images_with_paramsfunction
Pad a batch of images with explicitly defined padding on each side. This function adds specified amounts of padding to each side of the image for each image in the batch.
Parameters
Name | Type | Default | Description |
---|---|---|---|
images | np.ndarray | - | Input batch of images to pad. |
h_pad_top | int | - | Number of pixels to add at the top. |
h_pad_bottom | int | - | Number of pixels to add at the bottom. |
w_pad_left | int | - | Number of pixels to add on the left. |
w_pad_right | int | - | Number of pixels to add on the right. |
border_mode | int | - | OpenCV border mode for padding. |
value | One of:
| - | Value(s) to fill the border pixels. |
Returns
- np.ndarray: Padded batch of images.
pad_keypointsfunction
Pad keypoints by a given amount. This function pads keypoints by a given amount. It handles both reflection and padding.
Parameters
Name | Type | Default | Description |
---|---|---|---|
keypoints | np.ndarray | - | The keypoints to pad. |
pad_top | int | - | The amount to pad the top of the keypoints. |
pad_bottom | int | - | The amount to pad the bottom of the keypoints. |
pad_left | int | - | The amount to pad the left of the keypoints. |
pad_right | int | - | The amount to pad the right of the keypoints. |
border_mode | int | - | The border mode to use. |
image_shape | tuple[int, int] | - | The shape of the image as (height, width). |
Returns
- np.ndarray: The padded keypoints.
pad_with_paramsfunction
Pad an image with explicitly defined padding on each side. This function adds specified amounts of padding to each side of the image.
Parameters
Name | Type | Default | Description |
---|---|---|---|
img | np.ndarray | - | Input image to pad. |
h_pad_top | int | - | Number of pixels to add at the top. |
h_pad_bottom | int | - | Number of pixels to add at the bottom. |
w_pad_left | int | - | Number of pixels to add on the left. |
w_pad_right | int | - | Number of pixels to add on the right. |
border_mode | int | - | OpenCV border mode for padding. |
value | One of:
| - | Value(s) to fill the border pixels. |
Returns
- np.ndarray: Padded image.
perspectivefunction
Apply perspective transformation to an image. This function warps an image according to a perspective transformation matrix. It can either maintain the original dimensions or use the specified max dimensions.
Parameters
Name | Type | Default | Description |
---|---|---|---|
img | np.ndarray | - | Input image to transform. |
matrix | np.ndarray | - | 3x3 perspective transformation matrix. |
max_width | int | - | Maximum width of the output image if keep_size is False. |
max_height | int | - | Maximum height of the output image if keep_size is False. |
border_val | One of:
| - | Border value(s) to fill areas outside the transformed image. |
border_mode | int | - | OpenCV border mode (e.g., cv2.BORDER_CONSTANT, cv2.BORDER_REFLECT). |
keep_size | bool | - | If True, maintain the original image dimensions. |
interpolation | int | - | Interpolation method for resampling (cv2 interpolation flag). |
Returns
- np.ndarray: Perspective-transformed image.
perspective_bboxesfunction
Applies perspective transformation to bounding boxes. This function transforms bounding boxes using the given perspective transformation matrix. It handles bounding boxes with additional attributes beyond the standard coordinates.
Parameters
Name | Type | Default | Description |
---|---|---|---|
bboxes | np.ndarray | - | An array of bounding boxes with shape (num_bboxes, 4+). Each row represents a bounding box (x_min, y_min, x_max, y_max, ...). Additional columns beyond the first 4 are preserved unchanged. |
image_shape | tuple[int, int] | - | The shape of the image (height, width). |
matrix | np.ndarray | - | The perspective transformation matrix. |
max_width | int | - | The maximum width of the output image. |
max_height | int | - | The maximum height of the output image. |
keep_size | bool | - | If True, maintains the original image size after transformation. |
Returns
- np.ndarray: An array of transformed bounding boxes with the same shape as input.
Examples
>>> bboxes = np.array([[0.1, 0.1, 0.3, 0.3, 1], [0.5, 0.5, 0.8, 0.8, 2]])
>>> image_shape = (100, 100)
>>> matrix = np.array([[1.5, 0.2, -20], [-0.1, 1.3, -10], [0.002, 0.001, 1]])
>>> transformed_bboxes = perspective_bboxes(bboxes, image_shape, matrix, 150, 150, False)
Notes
- This function modifies only the coordinate columns (first 4) of the input bounding boxes. - Any additional attributes (columns beyond the first 4) are kept unchanged. - The function handles denormalization and renormalization of coordinates internally.
perspective_keypointsfunction
Apply perspective transformation to keypoints.
Parameters
Name | Type | Default | Description |
---|---|---|---|
keypoints | np.ndarray | - | Array of shape (N, 5+) in format [x, y, z, angle, scale, ...] |
image_shape | tuple[int, int] | - | Original image shape (height, width) |
matrix | np.ndarray | - | 3x3 perspective transformation matrix |
max_width | int | - | Maximum width after transformation |
max_height | int | - | Maximum height after transformation |
keep_size | bool | - | Whether to keep original size |
Returns
- np.ndarray: Transformed keypoints array with same shape as input
remapfunction
Remap an image according to given coordinate maps. This function applies a generic geometrical transformation using mapping functions that specify the position of each pixel in the output image.
Parameters
Name | Type | Default | Description |
---|---|---|---|
img | np.ndarray | - | Input image to transform. |
map_x | np.ndarray | - | Map of x-coordinates with same height and width as the input image. |
map_y | np.ndarray | - | Map of y-coordinates with same height and width as the input image. |
interpolation | int | - | Interpolation method for resampling. |
border_mode | int | - | OpenCV border mode for handling pixels outside the image boundaries. |
value | One of:
| None | Border value(s) if border_mode is BORDER_CONSTANT. |
Returns
- np.ndarray: Remapped image with the same shape as the input image.
remap_bboxesfunction
Remap bounding boxes using displacement maps.
Parameters
Name | Type | Default | Description |
---|---|---|---|
bboxes | np.ndarray | - | - |
map_x | np.ndarray | - | - |
map_y | np.ndarray | - | - |
image_shape | tuple[int, int] | - | - |
remap_keypointsfunction
Transform keypoints using coordinate mapping functions. This function applies the inverse of the mapping defined by map_x and map_y to keypoint coordinates. The inverse mapping is necessary because the mapping functions define how pixels move from the source to the destination image, while keypoints need to be transformed from the destination back to the source.
Parameters
Name | Type | Default | Description |
---|---|---|---|
keypoints | np.ndarray | - | Array of keypoints with shape (N, 2+), where the first two columns are x and y coordinates. |
map_x | np.ndarray | - | Map of x-coordinates with shape equal to image_shape. |
map_y | np.ndarray | - | Map of y-coordinates with shape equal to image_shape. |
image_shape | tuple[int, int] | - | Shape (height, width) of the original image. |
Returns
- np.ndarray: Transformed keypoints with the same shape as the input keypoints.
remap_keypoints_via_maskfunction
Remap keypoints using mask and cv2.remap method.
Parameters
Name | Type | Default | Description |
---|---|---|---|
keypoints | np.ndarray | - | - |
map_x | np.ndarray | - | - |
map_y | np.ndarray | - | - |
image_shape | tuple[int, int] | - | - |
resizefunction
Resize an image to the specified dimensions. This function resizes an input image to the target shape using the specified interpolation method. If the image is already the target size, it is returned unchanged.
Parameters
Name | Type | Default | Description |
---|---|---|---|
img | np.ndarray | - | Input image to resize. |
target_shape | tuple[int, int] | - | Target (height, width) dimensions. |
interpolation | int | - | Interpolation method to use (cv2 interpolation flag). Examples: cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_NEAREST, etc. |
Returns
- np.ndarray: Resized image with shape target_shape + original channel dimensions.
rot90function
Rotate an image 90 degrees counterclockwise.
Parameters
Name | Type | Default | Description |
---|---|---|---|
img | np.ndarray | - | The input image to rotate. |
factor | One of:
| - | The number of 90-degree rotations to apply. |
Returns
- np.ndarray: The rotated image.
rotation2d_matrix_to_euler_anglesfunction
Args: matrix (np.ndarray): Rotation matrix y_up (bool): is Y axis looks up or down
Parameters
Name | Type | Default | Description |
---|---|---|---|
matrix | np.ndarray | - | - |
y_up | bool | - | - |
scalefunction
Scale an image by a factor while preserving aspect ratio. This function scales both height and width dimensions of the image by the same factor.
Parameters
Name | Type | Default | Description |
---|---|---|---|
img | np.ndarray | - | Input image to scale. |
scale | float | - | Scale factor. Values > 1 will enlarge the image, values < 1 will shrink it. |
interpolation | int | - | Interpolation method to use (cv2 interpolation flag). |
Returns
- np.ndarray: Scaled image.
shift_bboxesfunction
Shift bounding boxes by a given vector.
Parameters
Name | Type | Default | Description |
---|---|---|---|
bboxes | np.ndarray | - | Array of bounding boxes with shape (n, m) where n is the number of bboxes and m >= 4. The first 4 columns are [x_min, y_min, x_max, y_max]. |
shift_vector | np.ndarray | - | Vector to shift the bounding boxes by, with shape (4,) for [shift_x, shift_y, shift_x, shift_y]. |
Returns
- np.ndarray: Shifted bounding boxes with the same shape as input.
shift_keypointsfunction
Shift keypoints by a given shift vector. This function shifts the keypoints by a given shift vector. It only shifts the x, y and z coordinates of the keypoints.
Parameters
Name | Type | Default | Description |
---|---|---|---|
keypoints | np.ndarray | - | The keypoints to shift. |
shift_vector | np.ndarray | - | The shift vector to apply to the keypoints. |
Returns
- np.ndarray: The shifted keypoints.
shuffle_tiles_within_shape_groupsfunction
Shuffles indices within each group of similar shapes and creates a list where each index points to the index of the tile it should be mapped to.
Parameters
Name | Type | Default | Description |
---|---|---|---|
shape_groups | dict[tuple[int, int], list[int]] | - | Groups of tile indices categorized by shape. |
random_generator | np.random.Generator | - | The random generator to use for shuffling the indices. If None, a new random generator will be used. |
Returns
- list[int]: A list where each index is mapped to the new index of the tile after shuffling.
split_uniform_gridfunction
Splits an image shape into a uniform grid specified by the grid dimensions.
Parameters
Name | Type | Default | Description |
---|---|---|---|
image_shape | tuple[int, int] | - | The shape of the image as (height, width). |
grid | tuple[int, int] | - | The grid size as (rows, columns). |
random_generator | np.random.Generator | - | The random generator to use for shuffling the splits. If None, the splits are not shuffled. |
Returns
- np.ndarray: An array containing the tiles' coordinates in the format (start_y, start_x, end_y, end_x).
Notes
The function uses `generate_shuffled_splits` to generate the splits for the height and width of the image. The splits are then used to calculate the coordinates of the tiles.
swap_tiles_on_imagefunction
Swap tiles on the image according to the new format.
Parameters
Name | Type | Default | Description |
---|---|---|---|
image | np.ndarray | - | Input image. |
tiles | np.ndarray | - | Array of tiles with each tile as [start_y, start_x, end_y, end_x]. |
mapping | One of:
| None | list of new tile indices. |
Returns
- np.ndarray: Output image with tiles swapped according to the random shuffle.
swap_tiles_on_keypointsfunction
Swap the positions of keypoints based on a tile mapping. This function takes a set of keypoints and repositions them according to a mapping of tile swaps. Keypoints are moved from their original tiles to new positions in the swapped tiles.
Parameters
Name | Type | Default | Description |
---|---|---|---|
keypoints | np.ndarray | - | A 2D numpy array of shape (N, 2) where N is the number of keypoints. Each row represents a keypoint's (x, y) coordinates. |
tiles | np.ndarray | - | A 2D numpy array of shape (M, 4) where M is the number of tiles. Each row represents a tile's (start_y, start_x, end_y, end_x) coordinates. |
mapping | np.ndarray | - | A 1D numpy array of shape (M,) where M is the number of tiles. Each element i contains the index of the tile that tile i should be swapped with. |
Returns
- np.ndarray: A 2D numpy array of the same shape as the input keypoints, containing the new positions
Notes
- Keypoints that do not fall within any tile will remain unchanged. - The function assumes that the tiles do not overlap and cover the entire image space.
to_distance_mapsfunction
Generate a ``(H,W,N)`` array of distance maps for ``N`` keypoints. The ``n``-th distance map contains at every location ``(y, x)`` the euclidean distance to the ``n``-th keypoint. This function can be used as a helper when augmenting keypoints with a method that only supports the augmentation of images.
Parameters
Name | Type | Default | Description |
---|---|---|---|
keypoints | np.ndarray | - | A numpy array of shape (N, 2+) where N is the number of keypoints. Each row represents a keypoint's (x, y) coordinates. |
image_shape | tuple[int, int] | - | Shape of the image (height, width) |
inverted | bool | False | If ``True``, inverted distance maps are returned where each distance value d is replaced by ``d/(d+1)``, i.e. the distance maps have values in the range ``(0.0, 1.0]`` with ``1.0`` denoting exactly the position of the respective keypoint. |
Returns
- np.ndarray: A float32 array of shape (H, W, N) containing ``N`` distance maps for ``N``
tps_transformfunction
Apply TPS transformation with consistent types.
Parameters
Name | Type | Default | Description |
---|---|---|---|
target_points | np.ndarray | - | - |
control_points | np.ndarray | - | - |
nonlinear_weights | np.ndarray | - | - |
affine_weights | np.ndarray | - | - |
transposefunction
Transposes the first two dimensions of an array of any dimensionality. Retains the order of any additional dimensions.
Parameters
Name | Type | Default | Description |
---|---|---|---|
img | np.ndarray | - | Input array. |
Returns
- np.ndarray: Transposed array.
validate_bboxesfunction
Validate bounding boxes and remove invalid ones.
Parameters
Name | Type | Default | Description |
---|---|---|---|
bboxes | np.ndarray | - | Array of bounding boxes with shape (n, 4) where each row is [x_min, y_min, x_max, y_max]. |
image_shape | Sequence[int] | - | Shape of the image as (height, width). |
Returns
- np.ndarray: Array of valid bounding boxes, potentially with fewer boxes than the input.
Examples
>>> bboxes = np.array([[10, 20, 30, 40], [-10, -10, 5, 5], [100, 100, 120, 120]])
>>> valid_bboxes = validate_bboxes(bboxes, (100, 100))
>>> print(valid_bboxes)
[[10 20 30 40]]
validate_if_not_found_coordsfunction
Validate and process `if_not_found_coords` parameter.
Parameters
Name | Type | Default | Description |
---|---|---|---|
if_not_found_coords | One of:
| - | - |
validate_keypointsfunction
Validate keypoints and remove those that fall outside the image boundaries.
Parameters
Name | Type | Default | Description |
---|---|---|---|
keypoints | np.ndarray | - | Array of keypoints with shape (N, M) where N is the number of keypoints and M >= 2. The first two columns represent x and y coordinates. |
image_shape | tuple[int, int] | - | Shape of the image as (height, width). |
Returns
- np.ndarray: Array of valid keypoints that fall within the image boundaries.
Notes
This function only checks the x and y coordinates (first two columns) of the keypoints. Any additional columns (e.g., angle, scale) are preserved for valid keypoints.
volume_hflipfunction
Perform horizontal flip on a volume (numpy array). Flips the volume along the width axis (axis=2). Handles inputs with shapes (D, H, W) or (D, H, W, C).
Parameters
Name | Type | Default | Description |
---|---|---|---|
volume | np.ndarray | - | Input volume. |
Returns
- np.ndarray: Horizontally flipped volume.
volume_rot90function
Rotate a volume 90 degrees counter-clockwise multiple times. Rotates the volume in the height-width plane (axes 1 and 2). Handles inputs with shapes (D, H, W) or (D, H, W, C).
Parameters
Name | Type | Default | Description |
---|---|---|---|
volume | np.ndarray | - | Input volume. |
factor | One of:
| - | Number of 90-degree rotations. |
Returns
- np.ndarray: Rotated volume.
volume_vflipfunction
Perform vertical flip on a volume (numpy array). Flips the volume along the height axis (axis=1). Handles inputs with shapes (D, H, W) or (D, H, W, C).
Parameters
Name | Type | Default | Description |
---|---|---|---|
volume | np.ndarray | - | Input volume. |
Returns
- np.ndarray: Vertically flipped volume.
volumes_hflipfunction
Perform horizontal flip on a batch of volumes (numpy array). Flips the volumes along the width axis (axis=3). Handles inputs with shapes (B, D, H, W) or (B, D, H, W, C).
Parameters
Name | Type | Default | Description |
---|---|---|---|
volumes | np.ndarray | - | Input batch of volumes. |
Returns
- np.ndarray: Horizontally flipped batch of volumes.
volumes_rot90function
Rotate a batch of volumes 90 degrees counter-clockwise multiple times. Rotates the volumes in the height-width plane (axes 2 and 3). Handles inputs with shapes (B, D, H, W) or (B, D, H, W, C).
Parameters
Name | Type | Default | Description |
---|---|---|---|
volumes | np.ndarray | - | Input batch of volumes. |
factor | One of:
| - | Number of 90-degree rotations |
Returns
- np.ndarray: Rotated batch of volumes.
volumes_vflipfunction
Perform vertical flip on a batch of volumes (numpy array). Flips the volumes along the height axis (axis=2). Handles inputs with shapes (B, D, H, W) or (B, D, H, W, C).
Parameters
Name | Type | Default | Description |
---|---|---|---|
volumes | np.ndarray | - | Input batch of volumes. |
Returns
- np.ndarray: Vertically flipped batch of volumes.
warp_affinefunction
Apply an affine transformation to an image. This function transforms an image using the specified affine transformation matrix. If the transformation matrix is an identity matrix, the original image is returned.
Parameters
Name | Type | Default | Description |
---|---|---|---|
image | np.ndarray | - | Input image to transform. |
matrix | np.ndarray | - | 2x3 or 3x3 affine transformation matrix. |
interpolation | int | - | Interpolation method for resampling. |
fill | One of:
| - | Border value(s) to fill areas outside the transformed image. |
border_mode | int | - | OpenCV border mode for handling pixels outside the image boundaries. |
output_shape | tuple[int, int] | - | Shape (height, width) of the output image. |
Returns
- np.ndarray: Affine-transformed image with dimensions specified by output_shape.
warp_affine_with_value_extensionfunction
Warp affine with value extension. This function warps an image with a given affine transformation matrix. It also extends the value to a sequence of floats.
Parameters
Name | Type | Default | Description |
---|---|---|---|
image | np.ndarray | - | The image to warp. |
matrix | np.ndarray | - | The affine transformation matrix. |
dsize | tuple[int, int] | - | The size of the output image. |
flags | int | - | The flags for the warp. |
border_mode | int | - | The border mode to use. |
border_value | One of:
| - | The value to pad the image with. |
Returns
- np.ndarray: The warped image.