diff --git a/src/machinevisiontoolbox/ImageSpatial.py b/src/machinevisiontoolbox/ImageSpatial.py index 7a71972e..b1771e2f 100644 --- a/src/machinevisiontoolbox/ImageSpatial.py +++ b/src/machinevisiontoolbox/ImageSpatial.py @@ -192,6 +192,7 @@ def convolve( mode: str = "same", border: str = "reflect", bordervalue: int | float = 0, + dtype: Literal["same", "int16", "float32", "float64"] = "same", ) -> Any: """ Image convolution @@ -204,6 +205,9 @@ def convolve( :type border: str, optional :param bordervalue: padding value, defaults to 0 :type bordervalue: scalar, optional + :param dtype: datatype of the result, defaults to ``'same'``, the datatype + of the input image + :type dtype: str, optional :return: input image convolved with kernel :rtype: :class:`.Image` @@ -243,11 +247,35 @@ def convolve( >>> img = Image.Read('monalisa.png') >>> img.convolve(K=np.ones((11,11))).disp() + ============= ============================================================= + ``dtype`` description + ============= ============================================================= + ``'same'`` result has the datatype of the input image (default) + ``'int16'`` signed 16-bit integer, for ``uint8`` or ``int16`` input + ``'float32'`` single precision, for any input except ``float64`` + ``'float64'`` double precision, for any input + ============= ============================================================= + + .. versionchanged:: 2.5.0 + Added the ``dtype`` argument. + .. note:: - The kernel is typically square with an odd side length. - - The result has the same datatype as the input image. For a kernel - where the results could be negative (eg. edge detection kernel) - this will cause issues such as value wraparound. + - OpenCV sums the products of kernel and pixel values in a wider + type than the image, so the sum itself does not overflow. The + sum is then converted to the datatype of the result, and values + outside its range are **clipped** (saturated), not wrapped. With + the default ``dtype='same'`` a ``uint8`` result is limited to 0 + to 255, so for a kernel whose results can be negative (for + example an edge detection kernel) every negative result becomes 0, + and for a kernel that sums to more than one (for example + ``np.ones((11, 11))``) bright regions saturate at 255. Use + ``dtype='float32'`` to keep the sign and the magnitude. + - A ``uint8`` image convolved to ``dtype='int16'`` keeps the sign, + but also clips, at -32768 and 32767, which a large kernel can + reach. ``dtype='float32'`` holds the result of any realistic kernel. + - Only combinations OpenCV supports are allowed, a result cannot be + less precise than a floating point input. - If the image is color (has multiple planes) the kernel is applied to each plane, resulting in an output image with the same number of planes. @@ -279,6 +307,28 @@ def convolve( K = argcheck.getmatrix(K, shape=[None, None], dtype="float32") + # the output depth that cv2.filter2D accepts for each input datatype + ddepths = { + "same": -1, + "int16": cv2.CV_16S, + "float32": cv2.CV_32F, + "float64": cv2.CV_64F, + } + allowed = { + np.dtype("uint8"): ("same", "int16", "float32", "float64"), + np.dtype("uint16"): ("same", "float32", "float64"), + np.dtype("int16"): ("same", "int16", "float32", "float64"), + np.dtype("float32"): ("same", "float32"), + np.dtype("float64"): ("same", "float64"), + } + if dtype not in ddepths: + raise ValueError(f"dtype must be one of {list(ddepths)}, got {dtype!r}") + if self._A.dtype in allowed and dtype not in allowed[self._A.dtype]: + raise ValueError( + f"dtype {dtype!r} is not possible for a {self._A.dtype} image, " + f"must be one of {list(allowed[self._A.dtype])}" + ) + # OpenCV does correlation, not convolution, so we flip the kernel # to compensate. Flip horizontally and vertically. K = np.flip(K) @@ -324,7 +374,10 @@ def convolve( ) out = cv2.filter2D( - src=img, ddepth=-1, kernel=K, borderType=self._bordertype_cv(border) + src=img, + ddepth=ddepths[dtype], + kernel=K, + borderType=self._bordertype_cv(border), ) if mode == "valid" or crop: @@ -332,7 +385,9 @@ def convolve( out = out[kh : out.shape[0] - kh, kw : out.shape[1] - kw] else: out = out[kh : out.shape[0] - kh, kw : out.shape[1] - kw, :] - return self.__class__(out, colororder=self.colororder) + # name the datatype, otherwise Image narrows int16 and uint16 to uint8 + # and float64 to float32 + return self.__class__(out, colororder=self.colororder, dtype=out.dtype) # def sobel(self, kernel=None): # if kernel is None: @@ -365,6 +420,17 @@ def gradients( Compute horizontal and vertical gradient images. + The gradient images are ``float32``, or ``float64`` for a ``float64`` + image, whatever the type of the input image, since a gradient can be + negative and a ``uint8`` result would clip every negative value to zero. + With the default Sobel kernel, which is normalised, the gradients of a + ``uint8`` image lie between -127.5 and 127.5. + + .. versionchanged:: 2.5.0 + The gradients of an integer image are ``float32``. They were the + datatype of the image, so a ``uint8`` image lost all of its negative + gradients. + Example: .. runblock:: pycon @@ -381,8 +447,16 @@ def gradients( if K is None: K = Kernel.Sobel() - Iu = self.convolve(K, mode=mode, border=border, bordervalue=bordervalue) - Iv = self.convolve(K.T, mode=mode, border=border, bordervalue=bordervalue) + # a gradient is signed, so do not let it be clipped to the input datatype + dtype: Literal["float32", "float64"] = ( + "float64" if self._A.dtype == np.float64 else "float32" + ) + Iu = self.convolve( + K, mode=mode, border=border, bordervalue=bordervalue, dtype=dtype + ) + Iv = self.convolve( + K.T, mode=mode, border=border, bordervalue=bordervalue, dtype=dtype + ) return Iu, Iv def direction( diff --git a/tests/test_image_spatial_extra.py b/tests/test_image_spatial_extra.py index 7fefc635..bee7093f 100644 --- a/tests/test_image_spatial_extra.py +++ b/tests/test_image_spatial_extra.py @@ -68,6 +68,82 @@ def test_smooth_equals_convolution_with_a_gaussian(self, square): nt.assert_array_equal(square.smooth(2).array, square.convolve(K).array) +class TestConvolveDtype: + """The datatype of the result of convolve, and the clipping that the default has.""" + + @pytest.fixture + def falling_ramp(self): + # uint8, falling by 4 for each column + return Image(np.tile(np.arange(100, 0, -4, dtype=np.uint8), (10, 1))) + + @pytest.fixture + def central_difference(self): + return np.array([[1, 0, -1]], dtype=np.float32) / 2 + + def test_default_keeps_the_datatype_and_clips_negatives( + self, falling_ramp, central_difference + ): + out = falling_ramp.convolve(central_difference) + assert out.dtype == np.uint8 + # the true value is -4, which a uint8 cannot hold, so it is clipped to 0 + assert out.array[5, 10] == 0 + + def test_default_clips_at_the_top(self): + out = Image(np.full((9, 9), 200, dtype=np.uint8)).convolve(np.ones((3, 3))) + # the sum is 1800: OpenCV does not overflow, it clips on the way out + assert out.dtype == np.uint8 and out.array[4, 4] == 255 + + @pytest.mark.parametrize( + "dtype, expected", + [("int16", np.int16), ("float32", np.float32), ("float64", np.float64)], + ) + def test_dtype_keeps_the_sign_of_a_uint8_image( + self, falling_ramp, central_difference, dtype, expected + ): + out = falling_ramp.convolve(central_difference, dtype=dtype) + assert out.dtype == expected + assert out.array[5, 10] == pytest.approx(-4) + + def test_dtype_holds_a_sum_beyond_uint8(self): + img = Image(np.full((9, 9), 200, dtype=np.uint8)) + out = img.convolve(np.ones((3, 3)), dtype="float32") + assert out.array[4, 4] == pytest.approx(1800) + + @pytest.mark.parametrize( + "array, dtype", + [ + (np.ones((5, 5), dtype=np.float32), "float64"), + (np.ones((5, 5), dtype=np.float32), "int16"), + (np.ones((5, 5), dtype=np.float64), "float32"), + (np.ones((5, 5), dtype=np.uint16), "int16"), + ], + ) + def test_a_result_less_precise_than_the_input_is_refused(self, array, dtype): + with pytest.raises(ValueError, match="is not possible for a"): + Image(array, dtype=array.dtype).convolve(np.ones((3, 3)), dtype=dtype) + + def test_unknown_dtype(self): + with pytest.raises(ValueError, match="dtype must be one of"): + Image(np.ones((5, 5), dtype=np.float32)).convolve( + np.ones((3, 3)), dtype="uint8" + ) + + def test_float_input_is_unchanged_by_the_default(self): + out = Image(np.ones((5, 5), dtype=np.float32)).convolve(np.ones((3, 3))) + assert out.dtype == np.float32 and out.array[2, 2] == pytest.approx(9) + + @pytest.mark.parametrize("dtype", [np.uint16, np.int16, np.float64]) + def test_default_keeps_a_wider_datatype(self, dtype): + # Image() would narrow these to uint8 and float32 if not told otherwise + img = Image(np.ones((6, 6), dtype=dtype), dtype=dtype) + out = img.convolve(np.ones((3, 3)) / 9) + assert out.dtype == dtype + + def test_smooth_still_returns_the_input_datatype(self): + img = Image(np.full((9, 9), 100, dtype=np.uint8)) + assert img.smooth(1).dtype == np.uint8 + + class TestGradients: @pytest.fixture def ramp(self): @@ -85,6 +161,34 @@ def test_custom_kernel_and_mode(self, ramp): Iu, Iv = ramp.gradients(Kernel.Sobel(), mode="valid") assert Iu.shape == (18, 18) and Iv.shape == (18, 18) + def test_uint8_image_keeps_its_negative_gradients(self): + # falls by 4 in each column, which is a gradient of -4 + falling = Image(np.tile(np.arange(100, 0, -4, dtype=np.uint8), (10, 1))) + Iu, Iv = falling.gradients() + assert Iu.dtype == np.float32 and Iv.dtype == np.float32 + assert Iu.array[5, 10] == pytest.approx(-4) + assert Iv.array[5, 10] == pytest.approx(0) + + def test_uint8_and_float32_images_have_the_same_gradients(self): + rng = np.random.default_rng(1) + a = rng.integers(0, 256, (30, 40), dtype=np.uint8) + Iu8, Iv8 = Image(a).gradients() + Iu32, Iv32 = Image(a.astype(np.float32)).gradients() + nt.assert_allclose(Iu8.array, Iu32.array, atol=1e-4) + nt.assert_allclose(Iv8.array, Iv32.array, atol=1e-4) + + def test_uint8_gradients_stay_within_the_sobel_bound(self): + # a step from 0 to 255 is the largest edge: (1 + 2 + 1) * 255 / 8 + step = np.zeros((10, 10), dtype=np.uint8) + step[:, 5:] = 255 + Iu, _ = Image(step).gradients() + assert Iu.array.max() == pytest.approx(127.5) + assert Iu.array.min() == pytest.approx(0) + + def test_float64_image_gives_float64_gradients(self): + Iu, Iv = Image(np.ones((6, 6)), dtype=np.float64).gradients() + assert Iu.dtype == np.float64 and Iv.dtype == np.float64 + def test_direction(self): horizontal = Image(np.ones((3, 3), dtype=np.float32)) vertical = Image(np.ones((3, 3), dtype=np.float32))