Simple image transformation using one of two available filter functions: Erosion and Dilation. Args: image: binarized input image, onto which to apply transformation kind: Can be either 'erosion', in which case the :func:np.max function is called, or 'dila
(
image: np.ndarray, kind: str, kernel: np.ndarray | None = None
)
| 102 | |
| 103 | |
| 104 | def transform( |
| 105 | image: np.ndarray, kind: str, kernel: np.ndarray | None = None |
| 106 | ) -> np.ndarray: |
| 107 | """ |
| 108 | Simple image transformation using one of two available filter functions: |
| 109 | Erosion and Dilation. |
| 110 | |
| 111 | Args: |
| 112 | image: binarized input image, onto which to apply transformation |
| 113 | kind: Can be either 'erosion', in which case the :func:np.max |
| 114 | function is called, or 'dilation', when :func:np.min is used instead. |
| 115 | kernel: n x n kernel with shape < :attr:image.shape, |
| 116 | to be used when applying convolution to original image |
| 117 | |
| 118 | Returns: |
| 119 | returns a numpy array with same shape as input image, |
| 120 | corresponding to applied binary transformation. |
| 121 | |
| 122 | Examples: |
| 123 | >>> img = np.array([[1, 0.5], [0.2, 0.7]]) |
| 124 | >>> img = binarize(img, threshold=0.5) |
| 125 | >>> transform(img, 'erosion') |
| 126 | array([[1, 1], |
| 127 | [1, 1]], dtype=uint8) |
| 128 | >>> transform(img, 'dilation') |
| 129 | array([[0, 0], |
| 130 | [0, 0]], dtype=uint8) |
| 131 | """ |
| 132 | if kernel is None: |
| 133 | kernel = np.ones((3, 3)) |
| 134 | |
| 135 | if kind == "erosion": |
| 136 | constant = 1 |
| 137 | apply = np.max |
| 138 | else: |
| 139 | constant = 0 |
| 140 | apply = np.min |
| 141 | |
| 142 | center_x, center_y = (x // 2 for x in kernel.shape) |
| 143 | |
| 144 | # Use padded image when applying convolution |
| 145 | # to not go out of bounds of the original the image |
| 146 | transformed = np.zeros(image.shape, dtype=np.uint8) |
| 147 | padded = np.pad(image, 1, "constant", constant_values=constant) |
| 148 | |
| 149 | for x in range(center_x, padded.shape[0] - center_x): |
| 150 | for y in range(center_y, padded.shape[1] - center_y): |
| 151 | center = padded[ |
| 152 | x - center_x : x + center_x + 1, y - center_y : y + center_y + 1 |
| 153 | ] |
| 154 | # Apply transformation method to the centered section of the image |
| 155 | transformed[x - center_x, y - center_y] = apply(center[kernel == 1]) |
| 156 | |
| 157 | return transformed |
| 158 | |
| 159 | |
| 160 | def opening_filter(image: np.ndarray, kernel: np.ndarray | None = None) -> np.ndarray: |
no outgoing calls
no test coverage detected