"""NumPy reference for sobel_pipeline.sv. All arithmetic is integer and matches the RTL bit for bit: gray = (77 R + 150 G + 29 B + 128) >> 8 S = |Gx| + |Gy| with 3x3 Sobel kernels, 0 on the one-pixel border mag = S >> 3, edge = S >= thresh The RTL emits the result centred one line up and one pixel left of the input pixel, so stream_expected() shifts the images by (1, 1). """ from __future__ import annotations import numpy as np KX = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]) # d/dx: right minus left KY = KX.T # d/dy: bottom minus top def rgb_to_gray(img: np.ndarray) -> np.ndarray: r, g, b = (img[..., k].astype(np.int64) for k in range(3)) return ((77 * r + 150 * g + 29 * b + 128) >> 8).astype(np.uint8) def sobel_abs_sum(gray: np.ndarray) -> np.ndarray: """|Gx| + |Gy| for every interior pixel, 0 on the border.""" p = gray.astype(np.int64) h, w = p.shape gx = np.zeros((h, w), dtype=np.int64) gy = np.zeros((h, w), dtype=np.int64) for dy in range(3): for dx in range(3): win = p[dy:h - 2 + dy, dx:w - 2 + dx] gx[1:-1, 1:-1] += KX[dy, dx] * win gy[1:-1, 1:-1] += KY[dy, dx] * win return np.abs(gx) + np.abs(gy) def stream_expected(img: np.ndarray, thresh: int) -> tuple[np.ndarray, np.ndarray]: """What the RTL outputs at each input position: (mag, edge) images.""" s = sobel_abs_sum(rgb_to_gray(img)) shifted = np.zeros_like(s) shifted[1:, 1:] = s[:-1, :-1] return (shifted >> 3).astype(np.uint8), (shifted >= thresh).astype(np.uint8) def synthetic_image(w: int, h: int, seed: int) -> np.ndarray: """Synthetic RGB test picture: gradient, disc, rectangle, line and noise.""" rng = np.random.default_rng(seed) yy, xx = np.mgrid[0:h, 0:w] img = np.zeros((h, w, 3), dtype=np.float64) img[..., 0] = 40 + 120 * xx / max(w - 1, 1) # red ramp left to right img[..., 1] = 30 + 60 * yy / max(h - 1, 1) # green ramp top to bottom img[..., 2] = 60 disc = (xx - 0.35 * w) ** 2 + (yy - 0.5 * h) ** 2 < (0.25 * h) ** 2 img[disc] = (250, 220, 40) rect = (xx > 0.6 * w) & (xx < 0.85 * w) & (yy > 0.2 * h) & (yy < 0.75 * h) img[rect] = (20, 40, 200) line = np.abs((yy - 0.9 * h) + 0.3 * (xx - 0.1 * w)) < 1.0 img[line] = (255, 255, 255) img += rng.normal(0.0, 4.0, img.shape) return np.clip(np.round(img), 0, 255).astype(np.uint8)