import numpy as np, matplotlib.pyplot as plt
img = np.zeros((40, 40))
img[8:20, 8:28] = 1.0 # a rectangle
yy, xx = np.mgrid[0:40, 0:40]
img[(yy - 28)**2 + (xx - 26)**2 < 64] = 1.0 # a disk
def conv2d(x, k):
kh, kw = k.shape
out = np.zeros((x.shape[0]-kh+1, x.shape[1]-kw+1))
for i in range(out.shape[0]):
for j in range(out.shape[1]):
out[i, j] = np.sum(x[i:i+kh, j:j+kw] * k)
return out
Kx = np.array([[-1,0,1],[-2,0,2],[-1,0,1]]) # vertical edges
gx, gy = conv2d(img, Kx), conv2d(img, Kx.T) # Kx.T → horizontal
fig, ax = plt.subplots(1, 3, figsize=(6.2, 2.2))
for a, im, t in zip(ax, [img, np.abs(gx), np.abs(gy)],
["input", "vertical-edge filter", "horizontal-edge filter"]):
a.imshow(im, cmap="gray"); a.set_title(t, fontsize=8); a.axis("off")
plt.tight_layout(); plt.show()