diff --git a/src/machinevisiontoolbox/ImageSpatial.py b/src/machinevisiontoolbox/ImageSpatial.py index f3adea6b..bf5cb5ce 100644 --- a/src/machinevisiontoolbox/ImageSpatial.py +++ b/src/machinevisiontoolbox/ImageSpatial.py @@ -1239,7 +1239,8 @@ def sad( # for im in self: # m = np.abs(im._A - image2._A) # out.append(np.sum(m)) - m = np.abs(image1._A - image2._A) + # convert first: subtracting uint8 arrays would wrap around at 256 + m = np.abs(image1._A.astype(float) - image2._A) out = np.sum(m) return out @@ -1284,7 +1285,8 @@ def ssd( if not np.all(image1.shape == image2.shape): raise ValueError("image2 shape is not equal to image1") - m = np.power((image1._A - image2._A), 2) + # convert first: subtracting uint8 arrays would wrap around at 256 + m = np.power(image1._A.astype(float) - image2._A, 2) return np.sum(m) def ncc( @@ -1330,12 +1332,15 @@ def ncc( if not np.all(image1.shape == image2.shape): raise ValueError("image2 shape is not equal to image1") - denom = np.sqrt(np.sum(image1._A**2) * np.sum(image2._A**2)) + # convert first: squaring uint8 arrays would wrap around at 256 + a = image1._A.astype(float) + b = image2._A.astype(float) + denom = np.sqrt(np.sum(a**2) * np.sum(b**2)) if denom < 1e-10: return 0 else: - return np.sum(image1._A * image2._A) / denom + return np.sum(a * b) / denom def zsad( image1: Any, image2: Any diff --git a/tests/test_image_spatial_extra.py b/tests/test_image_spatial_extra.py index 73712110..dbbb1128 100644 --- a/tests/test_image_spatial_extra.py +++ b/tests/test_image_spatial_extra.py @@ -445,16 +445,22 @@ def test_correlation_of_flat_images_is_zero(self): assert zero.ncc(zero) == 0 assert one.zncc(one) == 0 - @pytest.mark.xfail( - strict=True, - reason="sad, ssd and ncc subtract and square uint8 arrays without " - "converting them, so the arithmetic wraps around at 256", - ) def test_uint8_images(self): + # subtracting or squaring uint8 values must not wrap around at 256 a = Image(A.astype(np.uint8)) b = Image(B.astype(np.uint8)) assert a.sad(b) == pytest.approx(np.abs(A - B).sum()) - assert a.ncc(b) <= 1 + assert a.ssd(b) == pytest.approx(((A - B) ** 2).sum()) + expected = (A * B).sum() / np.sqrt((A**2).sum() * (B**2).sum()) + assert a.ncc(b) == pytest.approx(expected, rel=1e-5) + + def test_uint8_images_with_large_differences(self): + # 200 - 10 wraps to 190 and 10 - 200 to 66 in uint8 arithmetic + a = Image(np.array([[10, 200]], dtype=np.uint8)) + b = Image(np.array([[200, 10]], dtype=np.uint8)) + assert a.sad(b) == 380 + assert a.ssd(b) == 2 * 190**2 + assert 0 <= a.ncc(b) <= 1 class TestSimilarity: