"""Check the integer Sobel reference against SciPy and basic properties.""" from __future__ import annotations import numpy as np from scipy import ndimage from sobel_model import KX, KY, rgb_to_gray, sobel_abs_sum, stream_expected, synthetic_image def test_gray_weights() -> None: assert 77 + 150 + 29 == 256 px = np.array([[[255, 255, 255], [255, 0, 0], [0, 255, 0], [0, 0, 255], [0, 0, 0]]], dtype=np.uint8) assert rgb_to_gray(px).tolist() == [[255, 77, 149, 29, 0]] rng = np.random.default_rng(20) img = rng.integers(0, 256, (50, 50, 3)).astype(np.uint8) exact = 0.299 * img[..., 0] + 0.587 * img[..., 1] + 0.114 * img[..., 2] assert np.max(np.abs(rgb_to_gray(img) - exact)) < 1.0 def test_matches_scipy_on_the_interior() -> None: gray = rgb_to_gray(synthetic_image(64, 48, seed=7)).astype(np.int64) s = sobel_abs_sum(gray) gx = ndimage.correlate(gray, KX) gy = ndimage.correlate(gray, KY) assert np.array_equal(s[1:-1, 1:-1], (np.abs(gx) + np.abs(gy))[1:-1, 1:-1]) # scipy.ndimage.sobel computes the same gradients (axis 1 is x, axis 0 is y). sx = ndimage.sobel(gray, axis=1) sy = ndimage.sobel(gray, axis=0) assert np.array_equal(s[1:-1, 1:-1], (np.abs(sx) + np.abs(sy))[1:-1, 1:-1]) assert not s[0].any() and not s[-1].any() and not s[:, 0].any() and not s[:, -1].any() def test_range_and_step_edge() -> None: step = np.zeros((5, 6), dtype=np.uint8) step[:, 3:] = 255 s = sobel_abs_sum(step) assert s[2, 2] == 4 * 255 and s[2, 3] == 4 * 255 and s[2, 1] == 0 # |Gx| + |Gy| is convex in the pixel values, so its maximum over 8-bit # windows is reached with every pixel at 0 or 255: check all 512. best = 0 for code in range(512): win = np.array([255 * ((code >> k) & 1) for k in range(9)], dtype=np.uint8).reshape(3, 3) best = max(best, int(sobel_abs_sum(win)[1, 1])) assert best == 1530 and (best >> 3) == 191 def test_stream_shift() -> None: img = synthetic_image(16, 12, seed=1) mag, edge = stream_expected(img, 400) s = sobel_abs_sum(rgb_to_gray(img)) assert np.array_equal(mag[1:, 1:], (s[:-1, :-1] >> 3).astype(np.uint8)) assert not mag[0].any() and not mag[:, 0].any() assert edge.dtype == np.uint8 and set(np.unique(edge)) <= {0, 1}