cellects.image_analysis.morphological_operations
cellects.image_analysis.morphological_operations
This module provides methods to analyze and modify shapes in binary images. It includes functions for comparing neighboring pixels, generating shape descriptors, and performing morphological operations like expanding shapes and filling holes.
Classes:
| Name | Description |
|---|---|
CompareNeighborsWithValue : Class to compare neighboring pixels to a specified value |
|
Functions:
| Name | Description |
|---|---|
cc : Sort connected components according to size |
|
make_gravity_field : Create a gradient field around shapes |
|
find_median_shape : Generate median shape from multiple inputs |
|
make_numbered_rays : Create numbered rays for analysis |
|
CompareNeighborsWithFocal : Compare neighboring pixels to focal values |
|
ShapeDescriptors : Generate shape descriptors using provided functions |
|
get_radius_distance_against_time : Calculate radius distances over time |
|
expand_until_one : Expand shapes until a single connected component remains |
|
expand_and_rate_until_one : Expand and rate shapes until one remains |
|
expand_until_overlap : Expand shapes until overlap occurs |
|
dynamically_expand_to_fill_holes : Dynamically expand to fill holes in shapes |
|
expand_smalls_toward_biggest : Expand smaller shapes toward largest component |
|
change_thresh_until_one : Change threshold until one connected component remains |
|
create_ellipse : Generate ellipse shape descriptors |
|
get_rolling_window_coordinates_list : Get coordinates for rolling window operations |
|
CompareNeighborsWithValue
CompareNeighborsWithValue class to summarize each pixel by comparing its neighbors to a value.
This class analyzes pixels in a 2D array, comparing each pixel's neighbors to a specified value. The comparison can be equality, superiority, or inferiority, and neighbors can be the 4 or 8 nearest pixels based on the connectivity parameter.
Source code in src/cellects/image_analysis/morphological_operations.py
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 | |
__init__(array, connectivity=None, data_type=np.int8)
Initialize a class for array connectivity processing.
This class processes arrays based on given connectivities, creating windows around the original data for both 1D and 2D arrays. Depending on the connectivity value (4 or 8), it creates different windows with borders.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
array
|
ndarray
|
Input array to process, can be 1D or 2D. |
required |
connectivity
|
int
|
Connectivity type for processing (4 or 8), by default None. |
None
|
data_type
|
dtype
|
Data type for the array elements, by default np.int8. |
int8
|
Attributes:
| Name | Type | Description |
|---|---|---|
array |
ndarray
|
The processed array based on the given data type. |
connectivity |
int
|
Connectivity value used for processing. |
on_the_right |
ndarray
|
Array with shifted elements to the right. |
on_the_left |
ndarray
|
Array with shifted elements to the left. |
on_the_bot |
(ndarray, optional)
|
Array with shifted elements to the bottom (for 2D arrays). |
on_the_top |
(ndarray, optional)
|
Array with shifted elements to the top (for 2D arrays). |
on_the_topleft |
(ndarray, optional)
|
Array with shifted elements to the top left (for 2D arrays). |
on_the_topright |
(ndarray, optional)
|
Array with shifted elements to the top right (for 2D arrays). |
on_the_botleft |
(ndarray, optional)
|
Array with shifted elements to the bottom left (for 2D arrays). |
on_the_botright |
(ndarray, optional)
|
Array with shifted elements to the bottom right (for 2D arrays). |
Source code in src/cellects/image_analysis/morphological_operations.py
is_equal(value, and_itself=False)
Check equality of neighboring values in an array.
This method compares the neighbors of each element in self.array to a given value.
Depending on the dimensionality and connectivity settings, it checks different neighboring
elements.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
int or float
|
The value to check equality with neighboring elements. |
required |
and_itself
|
bool
|
If True, also check equality with the element itself. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
None
|
|
Attributes (not standard Qt properties)
equal_neighbor_nb : ndarray of uint8 Array that holds the number of equal neighbors for each element.
Examples:
>>> matrix = np.array([[9, 0, 4, 6], [4, 9, 1, 3], [7, 2, 1, 4], [9, 0, 8, 5]], dtype=np.int8)
>>> compare = CompareNeighborsWithValue(matrix, connectivity=4)
>>> compare.is_equal(1)
>>> print(compare.equal_neighbor_nb)
[[0 0 1 0]
[0 1 1 1]
[0 1 1 1]
[0 0 1 0]]
Source code in src/cellects/image_analysis/morphological_operations.py
is_inf(value, and_itself=False)
is_inf(value and_itself=False)
Determine the number of neighbors that are infinitely small relative to a given value, considering optional connectivity and exclusion of the element itself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
numeric
|
The value to compare neighbor elements against. |
required |
and_itself
|
bool
|
If True, excludes the element itself from being counted. Default is False. |
False
|
Examples:
>>> matrix = np.array([[9, 0, 4, 6], [4, 9, 1, 3], [7, 2, 1, 4], [9, 0, 8, 5]], dtype=np.int8)
>>> compare = CompareNeighborsWithValue(matrix, connectivity=4)
>>> compare.is_inf(1)
>>> print(compare.inf_neighbor_nb)
[[1 1 1 0]
[0 1 0 0]
[0 1 0 0]
[1 1 1 0]]
Source code in src/cellects/image_analysis/morphological_operations.py
is_sup(value, and_itself=False)
Determine if pixels have more neighbors with higher values than a given threshold.
This method computes the number of neighboring pixels that have values greater
than a specified value for each pixel in the array. Optionally, it can exclude
the pixel itself if its value is less than or equal to value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
int
|
The threshold value used to determine if a neighboring pixel's value is greater. |
required |
and_itself
|
bool
|
If True, exclude the pixel itself if its value is less than or equal to |
False
|
Examples:
>>> matrix = np.array([[9, 0, 4, 6], [4, 9, 1, 3], [7, 2, 1, 4], [9, 0, 8, 5]], dtype=np.int8)
>>> compare = CompareNeighborsWithValue(matrix, connectivity=4)
>>> compare.is_sup(1)
>>> print(compare.sup_neighbor_nb)
[[3 3 2 4]
[4 2 3 3]
[4 2 3 3]
[3 3 2 4]]
Source code in src/cellects/image_analysis/morphological_operations.py
box_counting_dimension(zoomed_binary, side_lengths, display=False)
Box counting dimension calculation.
This function calculates the box-counting dimension of a binary image by analyzing the number of boxes (of varying sizes) that contain at least one pixel of the image. The function also provides the R-squared value from linear regression and the number of boxes used.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
zoomed_binary
|
NDArray[uint8]
|
Binary image (0 or 255 values) for which the box-counting dimension is calculated. |
required |
side_lengths
|
NDArray
|
Array of side lengths for the boxes used in the box-counting calculation. |
required |
display
|
bool
|
If True, displays a scatter plot of the log-transformed box counts and diameters, along with the linear regression fit. Default is False. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
out |
Tuple[float, float, float]
|
A tuple containing the calculated box-counting dimension ( |
Examples:
>>> binary_image = np.zeros((10, 10), dtype=np.uint8)
>>> binary_image[2:4, 2:6] = 1
>>> binary_image[7:9, 4:7] = 1
>>> binary_image[4:7, 5] = 1
>>> zoomed_binary, side_lengths = prepare_box_counting(binary_image, min_im_side=2, min_mesh_side=2)
>>> dimension, r_value, box_nb = box_counting_dimension(zoomed_binary, side_lengths)
>>> print(dimension, r_value, box_nb)
(np.float64(1.1699250014423126), np.float64(0.9999999999999998), 2)
Source code in src/cellects/image_analysis/morphological_operations.py
1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 | |
cc(binary_img)
Processes a binary image to reorder and label connected components.
This function takes a binary image, analyses the connected components, reorders them by size, ensures background is correctly labeled as 0, and returns the new ordered labels along with their statistics and centers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
binary_img
|
ndarray of uint8
|
Input binary image with connected components. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
new_order |
ndarray of uint8, uint16 or uint32
|
Image with reordered labels for connected components. |
stats |
ndarray of ints
|
Statistics for each component (x, y, width, height, area). |
centers |
ndarray of floats
|
Centers for each component (x, y). |
Examples:
>>> binary_img = np.array([[0, 1, 0], [0, 1, 0]], dtype=np.uint8)
>>> new_order, stats, centers = cc(binary_img)
>>> print(stats)
array([[0, 0, 3, 2, 4],
[1, 0, 2, 2, 2]], dtype=int32)
Source code in src/cellects/image_analysis/morphological_operations.py
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 | |
close_holes(binary_img)
Close holes in a binary image using connected components analysis.
This function identifies and closes small holes within the foreground objects of a binary image. It uses connected component analysis to find and fill holes that are smaller than the main object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
binary_img
|
ndarray of uint8
|
Binary input image where holes need to be closed. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
out |
ndarray of uint8
|
Binary image with closed holes. |
Examples:
>>> binary_img = np.zeros((10, 10), dtype=np.uint8)
>>> binary_img[2:8, 2:8] = 1
>>> binary_img[4:6, 4:6] = 0 # Creating a hole
>>> result = close_holes(binary_img)
>>> print(result)
[[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 1 1 1 1 1 1 0 0]
[0 0 1 1 1 1 1 1 0 0]
[0 0 1 1 1 1 1 1 0 0]
[0 0 1 1 1 1 1 1 0 0]
[0 0 1 1 1 1 1 1 0 0]
[0 0 1 1 1 1 1 1 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]]
Source code in src/cellects/image_analysis/morphological_operations.py
create_ellipse(vsize, hsize, min_size=0)
Create a 2D array representing an ellipse with given vertical and horizontal sizes.
This function generates a NumPy boolean array where each element is True if the point lies within or on
the boundary of an ellipse defined by its vertical and horizontal radii. The ellipse is centered at the center
of the array, which corresponds to the midpoint of the given dimensions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vsize
|
int
|
Vertical size (number of rows) in the output 2D array. |
required |
hsize
|
int
|
Horizontal size (number of columns) in the output 2D array. |
required |
Returns:
| Type | Description |
|---|---|
NDArray[bool]
|
A boolean NumPy array of shape |
Source code in src/cellects/image_analysis/morphological_operations.py
create_mask(dims, minmax, shape)
Create a boolean mask based on given dimensions and min/max coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dims
|
Tuple[int, int]
|
The dimensions of the mask (height and width). |
required |
minmax
|
Tuple[int, int, int, int]
|
The minimum and maximum coordinates for the mask (x_min, x_max, y_min, y_max). |
required |
shape
|
str
|
The shape of the mask. Should be either 'circle' or any other value for a rectangular mask. |
required |
Returns:
| Type | Description |
|---|---|
ndarray[bool]
|
A boolean NumPy array with the same dimensions as |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the shape is 'circle' and the ellipse creation fails. |
Notes
If shape is not 'circle', a rectangular mask will be created. The ellipse
creation method used may have specific performance considerations.
Examples:
>>> mask = create_mask((5, 6), (0, 5, 1, 5), 'circle')
>>> print(mask)
[[False False False True False False]
[False False True True True False]
[False True True True True False]
[False False True True True False]
[False False False True False False]]
Source code in src/cellects/image_analysis/morphological_operations.py
draw_img_with_mask(img, dims, minmax, shape, drawing, only_contours=False, dilate_mask=0)
Draw an image with a mask and optional contours.
Draws a subregion of the input image using a specified shape (circle or rectangle), which can be dilated. The mask can be limited to contours only, and an optional drawing (overlay) can be applied within the masked region.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img
|
NDArray
|
The input image to draw on. |
required |
dims
|
Tuple[int, int]
|
Dimensions of the subregion (width, height). |
required |
minmax
|
Tuple[int, int, int, int]
|
Coordinates of the subregion (x_start, x_end, y_start, y_end). |
required |
shape
|
str
|
Shape of the mask to draw ('circle' or 'rectangle'). |
required |
drawing
|
Tuple[NDArray, NDArray, NDArray]
|
Optional drawing (overlay) to apply within the masked region. |
required |
only_contours
|
bool
|
If True, draw only the contours of the shape. Default is False. |
False
|
dilate_mask
|
int
|
Number of iterations for dilating the mask. Default is 0. |
0
|
Returns:
| Type | Description |
|---|---|
NDArray
|
The modified image with the applied mask and drawing. |
Notes
This function assumes that the input image is in BGR format (OpenCV style).
Examples:
>>> dim = (100, 100, 3)
>>> img = np.zeros(dim)
>>> result = draw_img_with_mask(img, dim, (50, 75, 50, 75), 'circle', (0, 255, 0))
>>> print((result == 255).sum())
441
Source code in src/cellects/image_analysis/morphological_operations.py
2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 | |
draw_me_a_sun(main_shape, ray_length_coef=4)
Draw a sun-shaped pattern on an image based on the main shape and ray length coefficient.
This function takes an input binary image (main_shape) and draws sun rays from the perimeter of that shape. The length of the rays is controlled by a coefficient. The function ensures that rays do not extend beyond the image borders.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
main_shape
|
ndarray of bool or int
|
Binary input image where the main shape is defined. |
required |
ray_length_coef
|
float
|
Coefficient to control the length of sun rays. Defaults to 2. |
4
|
Returns:
| Name | Type | Description |
|---|---|---|
rays |
ndarray
|
Indices of the rays drawn. |
sun |
ndarray
|
Image with sun rays drawn on it. |
Examples:
>>> main_shape = np.zeros((10, 10), dtype=np.uint8)
>>> main_shape[4:7, 3:6] = 1
>>> rays, sun = draw_me_a_sun(main_shape)
>>> print(sun)
Source code in src/cellects/image_analysis/morphological_operations.py
dynamically_expand_to_fill_holes(binary_video, holes)
Fill the holes in a binary video by progressively expanding the shape made of ones.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
binary_video
|
ndarray of uint8
|
The binary video where holes need to be filled. |
required |
holes
|
ndarray of uint8
|
Array representing the holes in the binary video. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
out |
tuple of ndarray of uint8, int, and ndarray of float32
|
The modified binary video with filled holes, the end time when all holes are filled, and an array of distances against time used to fill the holes. |
Examples:
>>> binary_video = np.zeros((10, 640, 480), dtype=np.uint8)
>>> binary_video[:, 300:400, 220:240] = 1
>>> holes = np.zeros((640, 480), dtype=np.uint8)
>>> holes[340:360, 228:232] = 1
>>> filled_video, end_time, distances = dynamically_expand_to_fill_holes(binary_video, holes)
>>> print(filled_video.shape) # Should print (10, 640, 480)
(10, 640, 480)
Source code in src/cellects/image_analysis/morphological_operations.py
expand_until_neighbor_center_gets_nearer_than_own(shape_to_expand, without_shape_i, shape_original_centroid, ref_centroids, kernel)
Expand a shape until its neighbor's centroid is closer than its own.
This function takes in several numpy arrays representing shapes and their centroids, and expands the input shape until the distance to the nearest neighboring centroid is less than or equal to the distance between the shape's contour and its own centroid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shape_to_expand
|
ndarray of uint8
|
The binary shape to be expanded. |
required |
without_shape_i
|
ndarray of uint8
|
A binary array representing the area without the shape. |
required |
shape_original_centroid
|
ndarray
|
The centroid of the original shape. |
required |
ref_centroids
|
ndarray
|
Reference centroids to compare distances with. |
required |
kernel
|
ndarray
|
The kernel for dilation operation. |
required |
Returns:
| Type | Description |
|---|---|
ndarray of uint8
|
The expanded shape. |
Source code in src/cellects/image_analysis/morphological_operations.py
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 | |
find_major_incline(vector, natural_noise)
Find the major incline section in a vector.
This function identifies the segment of a vector that exhibits the most significant change in values, considering a specified natural noise level. It returns the left and right indices that define this segment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vector
|
ndarray of float64
|
Input data vector where the incline needs to be detected. |
required |
natural_noise
|
float
|
The acceptable noise level for determining the incline. |
required |
Returns:
| Type | Description |
|---|---|
Tuple[int, int]
|
A tuple containing two integers: the left and right indices of the major incline section in the vector. |
Examples:
>>> vector = np.array([3, 5, 7, 9, 10])
>>> natural_noise = 2.5
>>> left, right = find_major_incline(vector, natural_noise)
>>> (left, right)
(0, 1)
Source code in src/cellects/image_analysis/morphological_operations.py
find_median_shape(binary_3d_matrix)
Find the median shape from a binary 3D matrix.
This function computes the median 2D slice of a binary (0/1) 3D matrix by finding which voxels appear in at least half of the slices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
binary_3d_matrix
|
ndarray of uint8
|
Input 3D binary matrix where each slice is a 2D array. |
required |
Returns:
| Type | Description |
|---|---|
ndarray of uint8
|
Median shape as a 2D binary matrix where the same voxels that appear in at least half of the input slices are set to 1. |
Examples:
>>> binary_3d_matrix = np.random.randint(0, 2, (10, 5, 5), dtype=np.uint8)
>>> median_shape = find_median_shape(binary_3d_matrix)
>>> print(median_shape)
Source code in src/cellects/image_analysis/morphological_operations.py
get_all_line_coordinates(start_point, end_points)
Get all line coordinates between start point and end points.
This function computes the coordinates of lines connecting a start point to multiple end points, converting input arrays to float if necessary before processing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start_point
|
NDArray[float]
|
Starting coordinate point for the lines. Can be of any numeric type, will be converted to float if needed. |
required |
end_points
|
NDArray[float]
|
Array of end coordinate points for the lines. Can be of any numeric type, will be converted to float if needed. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
out |
List[NDArray[int]]
|
A list of numpy arrays containing the coordinates of each line as integer values. |
Examples:
>>> start_point = np.array([0, 0])
>>> end_points = np.array([[1, 2], [3, 4]])
>>> get_all_line_coordinates(start_point, end_points)
[array([[0, 0],
[0, 1],
[1, 2]], dtype=uint64), array([[0, 0],
[1, 1],
[1, 2],
[2, 3],
[3, 4]], dtype=uint64)]
Source code in src/cellects/image_analysis/morphological_operations.py
get_bb_with_moving_centers(motion_list, all_specimens_have_same_direction, original_shape_hsize, binary_image, y_boundaries)
Get the bounding boxes with moving centers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
motion_list
|
list
|
List of binary images representing the motion frames. |
required |
all_specimens_have_same_direction
|
bool
|
Boolean indicating if all specimens move in the same direction. |
required |
original_shape_hsize
|
int or None
|
Original height size of the shape. If |
required |
binary_image
|
NDArray
|
Binary image of the initial frame. |
required |
y_boundaries
|
NDArray
|
Array defining the y-boundaries for ranking shapes. |
required |
Returns:
| Type | Description |
|---|---|
tuple
|
A tuple containing: - top : NDArray Array of top coordinates for each bounding box. - bot : NDArray Array of bottom coordinates for each bounding box. - left : NDArray Array of left coordinates for each bounding box. - right : NDArray Array of right coordinates for each bounding box. - ordered_image_i : NDArray Updated binary image with the final ranked shapes. |
Notes
This function processes each frame to expand and confirm shapes, updating centroids if necessary. It uses morphological operations like dilation to detect shape changes over frames.
Examples:
>>> top, bot, left, right, ordered_image = _get_bb_with_moving_centers(motion_frames, True, None, binary_img, y_bounds)
>>> print("Top coordinates:", top)
>>> print("Bottom coordinates:", bot)
Source code in src/cellects/image_analysis/morphological_operations.py
1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 | |
get_contours(binary_image)
Find and return the contours of a binary image.
This function erodes the input binary image using a 3x3 cross-shaped structuring element and then subtracts the eroded image from the original to obtain the contours.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
binary_image
|
ndarray of uint8
|
Input binary image from which to extract contours. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
out |
ndarray of uint8
|
Image containing only the contours extracted from |
Examples:
>>> binary_image = np.zeros((10, 10), dtype=np.uint8)
>>> binary_image[2:8, 2:8] = 1
>>> result = get_contours(binary_image)
>>> print(result)
[[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 1 1 1 1 1 1 0 0]
[0 0 1 0 0 0 0 1 0 0]
[0 0 1 0 0 0 0 1 0 0]
[0 0 1 0 0 0 0 1 0 0]
[0 0 1 0 0 0 0 1 0 0]
[0 0 1 1 1 1 1 1 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]]
Source code in src/cellects/image_analysis/morphological_operations.py
get_largest_connected_component(segmentation)
Find the largest connected component in a segmentation image.
This function labels all connected components in a binary segmentation image, determines the size of each component, and returns information about the largest connected component.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
segmentation
|
ndarray of uint8
|
Binary segmentation image where different integer values represent different connected components. |
required |
Returns:
| Type | Description |
|---|---|
Tuple[int, ndarray of bool]
|
A tuple containing: - The size of the largest connected component. - A boolean mask representing the largest connected component in the input segmentation image. |
Examples:
>>> segmentation = np.zeros((10, 10), dtype=np.uint8)
>>> segmentation[2:6, 2:5] = 1
>>> segmentation[6:9, 6:9] = 1
>>> size, mask = get_largest_connected_component(segmentation)
>>> print(size)
12
Source code in src/cellects/image_analysis/morphological_operations.py
get_line_points(start, end)
Get line points between two endpoints using Bresenham's line algorithm.
This function calculates all the integer coordinate points that form a line between two endpoints using Bresenham's line algorithm. It is optimized for performance using Numba's just-in-time compilation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start
|
tuple of int
|
The starting point coordinates (y0, x0). |
required |
end
|
tuple of int
|
The ending point coordinates (y1, x1). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
out |
ndarray of int
|
Array of points representing the line, with shape (N, 2), where N is the number of points on the line. |
Examples:
>>> start = (0, 0)
>>> end = (1, 2)
>>> points = get_line_points(start, end)
>>> print(points)
[[0 0]
[0 1]
[1 2]]
Source code in src/cellects/image_analysis/morphological_operations.py
get_min_or_max_euclidean_pair(coords, min_or_max='max')
Find the pair of points in a given set with the minimum or maximum Euclidean distance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coords
|
Union[ndarray, Tuple]
|
An Nx2 numpy array or a tuple of two arrays, each containing the x and y coordinates of points. |
required |
min_or_max
|
str
|
Whether to find the 'min' or 'max' distance pair. Default is 'max'. |
'max'
|
Returns:
| Type | Description |
|---|---|
Tuple[ndarray, ndarray]
|
A tuple containing the coordinates of the two points that form the minimum or maximum distance pair. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Notes
- The function first computes all pairwise distances in condensed form using
pdist. - Then, it finds the index of the minimum or maximum distance.
- Finally, it maps this index to the actual point indices using a binary search method.
Examples:
>>> coords = np.array([[0, 1], [2, 3], [4, 5]])
>>> point1, point2 = get_min_or_max_euclidean_pair(coords, min_or_max="max")
>>> print(point1)
[0 1]
>>> print(point2)
[4 5]
>>> coords = (np.array([0, 2, 4, 8, 1, 5]), np.array([0, 2, 4, 8, 0, 5]))
>>> point1, point2 = get_min_or_max_euclidean_pair(coords, min_or_max="min")
>>> print(point1)
[0 0]
>>> print(point2)
[1 0]
Source code in src/cellects/image_analysis/morphological_operations.py
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 | |
get_minimal_distance_between_2_shapes(image_of_2_shapes, increase_speed=True)
Get the minimal distance between two shapes in an image.
This function calculates the minimal Euclidean distance between two different shapes represented by binary values 1 and 2 in a given image. It can optionally reduce the image size for faster processing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image_of_2_shapes
|
ndarray of int8
|
Binary image containing two shapes to measure distance between. |
required |
increase_speed
|
bool
|
Flag to reduce image size for faster computation. Default is True. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
min_distance |
float64
|
The minimal Euclidean distance between the two shapes. |
Examples:
>>> import numpy as np
>>> image = np.array([[1, 0], [0, 2]])
>>> distance = get_minimal_distance_between_2_shapes(image)
>>> print(distance)
expected output
Source code in src/cellects/image_analysis/morphological_operations.py
get_quick_bounding_boxes(binary_image, ordered_image, ordered_stats)
Compute bounding boxes for shapes in a binary image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
binary_image
|
NDArray[uint8]
|
A 2D array representing the binary image. |
required |
ordered_image
|
NDArray
|
An array containing the ordered image data. |
required |
ordered_stats
|
NDArray
|
A 2D array with statistics about the shapes in the image. |
required |
Returns:
| Type | Description |
|---|---|
Tuple[NDArray, NDArray, NDArray, NDArray]
|
A tuple containing four arrays: - top: Array of y-coordinates for the top edge of bounding boxes. - bot: Array of y-coordinates for the bottom edge of bounding boxes. - left: Array of x-coordinates for the left edge of bounding boxes. - right: Array of x-coordinates for the right edge of bounding boxes. |
Examples:
>>> binary_image = np.array([[0, 1], [0, 0], [1, 0]], dtype=np.uint8)
>>> ordered_image = np.array([[0, 1], [0, 0], [2, 0]], dtype=np.uint8)
>>> ordered_stats = np.array([[1, 0, 1, 1, 1], [0, 2, 1, 1, 1]], dtype=np.int32)
>>> top, bot, left, right = get_quick_bounding_boxes(binary_image, ordered_image, ordered_stats)
>>> print(top)
[-1 1]
>>> print(bot)
[2 4]
>>> print(left)
[0 -1]
>>> print(right)
[3 2]
Source code in src/cellects/image_analysis/morphological_operations.py
1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 | |
get_radius_distance_against_time(binary_video, field)
Calculate the radius distance against time from a binary video and field.
This function computes the change in radius distances over time by analyzing a binary video and mapping it to corresponding field values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
binary_video
|
ndarray of uint8
|
Binary video data. |
required |
field
|
ndarray
|
Field values to analyze the radius distances against. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
distance_against_time |
ndarray of float32
|
Radius distances over time. |
time_start |
int
|
Starting time index where the radius distance measurement begins. |
time_end |
int
|
Ending time index where the radius distance measurement ends. |
Examples:
>>> distance_against_time, time_start, time_end = get_radius_distance_against_time(binary_video, field)
Source code in src/cellects/image_analysis/morphological_operations.py
image_borders(dimensions, shape='rectangular')
Create an image with borders, either rectangular or circular.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dimensions
|
tuple
|
The dimensions of the image (height, width). |
required |
shape
|
str
|
The shape of the borders. Options are "rectangular" or "circular". Defaults to "rectangular". |
'rectangular'
|
Returns:
| Name | Type | Description |
|---|---|---|
out |
ndarray of uint8
|
The image with borders. If the shape is "circular", an ellipse border; if "rectangular", a rectangular border. |
Examples:
Source code in src/cellects/image_analysis/morphological_operations.py
inverted_distance_transform(original_shape, max_distance=None, with_erosion=0)
Calculate the distance transform around ones in a binary image, with optional erosion.
This function computes the Euclidean distance transform where zero values represent the background and ones represent the foreground. Optionally, it erodes the input image before computing the distance transform, and limits distances based on a maximum value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
original_shape
|
ndarray of uint8
|
Input binary image where ones represent the foreground. |
required |
max_distance
|
int
|
Maximum distance value to threshold. If None (default), no thresholding is applied. |
None
|
with_erosion
|
int
|
Number of iterations for erosion. If 0 (default), no erosion is applied. |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
out |
ndarray of uint32
|
Distance transform array where each element represents the distance to the nearest zero value in the input image. |
See also
rounded_distance_transform : less precise (outputs int) and faster for small max_distance values.
Examples:
>>> segmentation = np.zeros((4, 4), dtype=np.uint8)
>>> segmentation[1:3, 1:3] = 1
>>> gravity = inverted_distance_transform(segmentation, max_distance=2)
>>> print(gravity)
[[1. 1.41421356 1.41421356 1. ]
[1.41421356 0. 0. 1.41421356]
[1.41421356 0. 0. 1.41421356]
[1. 1.41421356 1.41421356 1. ]]
Source code in src/cellects/image_analysis/morphological_operations.py
keep_largest_shape(indexed_shapes)
Keep the largest shape from an array of indexed shapes.
This function identifies the most frequent non-zero shape in the input array and returns a binary mask where elements matching this shape are set to 1, and others are set to 0. The function uses NumPy's bincount to count occurrences of each shape and assumes that the first element (index 0) is not part of any shape classification.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
indexed_shapes
|
ndarray of int32
|
Input array containing indexed shapes. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
out |
ndarray of uint8
|
Binary mask where the largest shape is marked as 1. |
Examples:
>>> indexed_shapes = np.array([0, 2, 2, 3, 1], dtype=np.int32)
>>> keep_largest_shape(indexed_shapes)
array([0, 1, 1, 0, 0], dtype=uint8)
Source code in src/cellects/image_analysis/morphological_operations.py
keep_one_connected_component(binary_image)
Keep only one connected component in a binary image.
This function filters out all but the largest connected component in a binary image, effectively isolating it from other noise or objects. The function ensures the input is in uint8 format before processing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
binary_image
|
ndarray of uint8
|
Binary image containing one or more connected components. |
required |
Returns:
| Type | Description |
|---|---|
ndarray of uint8
|
Image with only the largest connected component retained. |
Examples:
>>> all_shapes = np.zeros((5, 5), dtype=np.uint8)
>>> all_shapes[0:2, 0:2] = 1
>>> all_shapes[3:4, 3:4] = 1
>>> res = keep_one_connected_component(all_shapes)
>>> print(res)
[[1 1 0 0 0]
[1 1 0 0 0]
[0 0 0 0 0]
[0 0 0 0 0]
[0 0 0 0 0]]
Source code in src/cellects/image_analysis/morphological_operations.py
keep_shape_connected_with_ref(all_shapes, reference_shape)
Keep shape connected with reference.
This function analyzes the connected components of a binary image represented by all_shapes
and returns the first component that intersects with the reference_shape.
If no such component is found, it returns None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
all_shapes
|
ndarray of uint8
|
Binary image containing all shapes to analyze. |
required |
reference_shape
|
ndarray of uint8
|
Binary reference shape used for intersection check. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
out |
ndarray of uint8 or None
|
The first connected component that intersects with the reference shape, or None if no such component is found. |
Examples:
>>> all_shapes = np.zeros((5, 5), dtype=np.uint8)
>>> reference_shape = np.zeros((5, 5), dtype=np.uint8)
>>> reference_shape[3, 3] = 1
>>> all_shapes[0:2, 0:2] = 1
>>> all_shapes[3:4, 3:4] = 1
>>> res = keep_shape_connected_with_ref(all_shapes, reference_shape)
>>> print(res)
[[0 0 0 0 0]
[0 0 0 0 0]
[0 0 0 0 0]
[0 0 0 1 0]
[0 0 0 0 0]]
Source code in src/cellects/image_analysis/morphological_operations.py
prepare_box_counting(binary_image, min_im_side=128, min_mesh_side=8, zoom_step=0, contours=True)
Prepare box counting parameters for image analysis.
Prepares parameters for box counting method based on binary image input. Adjusts image size, computes side lengths, and applies contour extraction if specified.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
binary_image
|
ndarray of uint8
|
Binary image for analysis. |
required |
min_im_side
|
int
|
Minimum side length threshold. Default is 128. |
128
|
min_mesh_side
|
int
|
Minimum mesh side length. Default is 8. |
8
|
zoom_step
|
int
|
Zoom step for side lengths computation. Default is 0. |
0
|
contours
|
bool
|
Whether to apply contour extraction. Default is True. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
out |
tuple of ndarray of uint8, ndarray (or None)
|
Cropped binary image and computed side lengths. |
Examples:
>>> binary_image = np.zeros((10, 10), dtype=np.uint8)
>>> binary_image[2:4, 2:6] = 1
>>> binary_image[7:9, 4:7] = 1
>>> binary_image[4:7, 5] = 1
>>> cropped_img, side_lengths = prepare_box_counting(binary_image, min_im_side=2, min_mesh_side=2)
>>> print(cropped_img), print(side_lengths)
[[0 0 0 0 0 0 0]
[0 1 1 1 1 0 0]
[0 1 1 1 1 0 0]
[0 0 0 0 1 0 0]
[0 0 0 0 1 0 0]
[0 0 0 0 1 0 0]
[0 0 0 1 0 1 0]
[0 0 0 1 1 1 0]
[0 0 0 0 0 0 0]]
[4 2]
Source code in src/cellects/image_analysis/morphological_operations.py
1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 | |
rank_from_top_to_bottom_from_left_to_right(binary_image, y_boundaries, get_ordered_image=False)
Rank components in a binary image from top to bottom and from left to right.
This function processes a binary image to rank its components based on their centroids. It first sorts the components row by row and then orders them within each row from left to right. If the ordering fails, it attempts an alternative algorithm and returns the ordered statistics and centroids.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
binary_image
|
ndarray of uint8
|
The input binary image to process. |
required |
y_boundaries
|
ndarray of int
|
Boundary information for the y-coordinates. |
required |
get_ordered_image
|
bool
|
If True, returns an ordered image in addition to the statistics and centroids. Default is False. |
False
|
Returns:
| Type | Description |
|---|---|
tuple
|
If If |
Source code in src/cellects/image_analysis/morphological_operations.py
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 | |
reduce_image_size_for_speed(image_of_2_shapes)
Reduces the size of an image containing two shapes for faster processing.
The function iteratively divides the image into quadrants and keeps only those that contain both shapes until a minimal size is reached.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image_of_2_shapes
|
ndarray of uint8
|
The input image containing two shapes. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
out |
tuple of tuples
|
The indices of the first and second shape in the reduced image. |
Examples:
>>> image_of_2_shapes = np.zeros((10, 10), dtype=np.uint8)
>>> image_of_2_shapes[1:3, 1:3] = 1
>>> image_of_2_shapes[1:3, 4:6] = 2
>>> shape1_idx, shape2_idx = reduce_image_size_for_speed(image_of_2_shapes)
>>> print(shape1_idx)
(array([1, 1, 2, 2]), array([1, 2, 1, 2]))
Source code in src/cellects/image_analysis/morphological_operations.py
rounded_inverted_distance_transform(original_shape, max_distance=None, with_erosion=0)
Perform rounded inverted distance transform on a binary image.
This function computes the inverse of the Euclidean distance transform, where each pixel value represents its distance to the nearest zero pixel. The operation can include erosion and will stop either at a given max distance or until no further expansion is needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
original_shape
|
ndarray of uint8
|
Input binary image to be processed. |
required |
max_distance
|
int
|
Maximum distance for the expansion. If None, no limit is applied. |
None
|
with_erosion
|
int
|
Number of erosion iterations to apply before the transform. Default is 0. |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
out |
ndarray of uint32
|
Output image containing the rounded inverted distance transform. |
Examples:
>>> segmentation = np.zeros((4, 4), dtype=np.uint8)
>>> segmentation[1:3, 1:3] = 1
>>> gravity = rounded_inverted_distance_transform(segmentation, max_distance=2)
>>> print(gravity)
[[1 2 2 1]
[2 0 0 2]
[2 0 0 2]
[1 2 2 1]]
Source code in src/cellects/image_analysis/morphological_operations.py
shape_selection(binary_image, several_blob_per_arena, true_shape_number=None, horizontal_size=None, spot_shape=None, bio_mask=None, back_mask=None)
Process the binary image to identify and validate shapes.
This method processes a binary image to detect connected components, validate their sizes, and handle bio and back masks if specified. It ensures that the number of validated shapes matches the expected sample number or applies additional filtering if necessary.
Args: use_bio_and_back_masks (bool): Whether to use bio and back masks during the processing. Default is False.
Selects and validates the shapes of stains based on their size and shape.
This method performs two main tasks: 1. Removes stains whose horizontal size varies too much from a reference value. 2. Determines the shape of each remaining stain and only keeps those that correspond to a reference shape.
The method first removes stains whose horizontal size is outside the specified confidence interval. Then, it identifies shapes that do not correspond to a predefined reference shape and removes them as well.
Args: horizontal_size (int): The expected horizontal size of the stains to use as a reference. shape (str): The shape type ('circle' or 'rectangle') that the stains should match. Other shapes are not currently supported. confint (float): The confidence interval as a decimal representing the percentage within which the size of the stains should fall. do_not_delete (NDArray, optional): An array of stain indices that should not be deleted. Default is None.
Source code in src/cellects/image_analysis/morphological_operations.py
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 | |