What a 3 by 3 kernel does
Blur, sharpen, emboss, and edge detection are one operation with nine numbers changed. Eight kernels on the same photograph, then a handle you drag to wipe the edges across the original.
What a 3 by 3 kernel does
Blur, sharpen, emboss, and edge detection are the same operation with nine numbers changed. Each output pixel is a weighted sum of its neighbors, and the weights are the whole story.
Nothing here needs an imaging library. The convolution is nine multiplications of a shifted array, which numpy does in one pass each.
1import matplotlib.pyplot as plt2import matplotlib.cbook as cbook3import numpy as np456def load_gray():7 """A photograph that ships with matplotlib, averaged down to gray."""8 with cbook.get_sample_data("grace_hopper.jpg") as handle:9 rgb = plt.imread(handle)10 return rgb.astype(np.float32) @ np.array([0.299, 0.587, 0.114], dtype=np.float32)111213def convolve(image, kernel):14 """Slide the kernel over the image, one offset at a time."""15 kh, kw = kernel.shape16 padded = np.pad(image, ((kh // 2, kh // 2), (kw // 2, kw // 2)), mode="edge")17 out = np.zeros_like(image, dtype=np.float32)18 for i in range(kh):19 for j in range(kw):20 out += kernel[i, j] * padded[i:i + image.shape[0], j:j + image.shape[1]]21 return out222324SOBEL_X = np.array([[1, 0, -1], [2, 0, -2], [1, 0, -1]], dtype=np.float32)25SOBEL_Y = SOBEL_X.T262728def edges(image):29 return np.hypot(convolve(image, SOBEL_X), convolve(image, SOBEL_Y))303132KERNELS = {33 "original": np.array([[0, 0, 0], [0, 1, 0], [0, 0, 0]], dtype=np.float32),34 "box blur": np.full((3, 3), 1 / 9, dtype=np.float32),35 "gaussian": np.array([[1, 2, 1], [2, 4, 2], [1, 2, 1]], dtype=np.float32) / 16,36 "sharpen": np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]], dtype=np.float32),37 "outline": np.array([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]], dtype=np.float32),38 "emboss": np.array([[-2, -1, 0], [-1, 1, 1], [0, 1, 2]], dtype=np.float32),39 "sobel x": SOBEL_X,40 "sobel y": SOBEL_Y,41}4243gray = load_gray()4445fig, axes = plt.subplots(2, 4, figsize=(11, 7.4), dpi=82, constrained_layout=True)46for ax, (label, kernel) in zip(axes.ravel(), KERNELS.items()):47 ax.imshow(convolve(gray, kernel), cmap="gray")48 ax.set_title(label, fontsize=10)49 ax.set_xticks([])50 ax.set_yticks([])51plt.show()
Two of them, side by side
The grid is useful for comparing eight results at once and useless for judging any one of them. So here are two at full size with a handle between them: drag it to wipe the Sobel magnitude across the original.
Python renders both frames to PNG and publishes them as ordinary strings. The cell after it is an HTML cell that reads those strings by name.
1import base642import io34from PIL import Image567def to_png(array, width=360):8 """Scale to a sensible width and encode, because both frames travel in the page."""9 clipped = np.clip(array, 0, 255).astype(np.uint8)10 image = Image.fromarray(clipped)11 height = round(image.height * width / image.width)12 image = image.resize((width, height), Image.LANCZOS)1314 buffer = io.BytesIO()15 image.save(buffer, format="PNG", optimize=True)16 return base64.b64encode(buffer.getvalue()).decode("ascii")171819source = load_gray()20original_png = to_png(source)21edges_png = to_png(edges(source))2223print(f"original {len(original_png) // 1024} KB, edges {len(edges_png) // 1024} KB")
original 123 KB, edges 154 KB
1<div style="font-family:var(--verso-prose-font-family,sans-serif);">2 <div id="ik-stage" style="position:relative;width:360px;max-width:100%;margin:0 auto;3 border:1px solid var(--verso-border-default,#d9d9d9);border-radius:8px;overflow:hidden;4 cursor:ew-resize;touch-action:none;user-select:none;">5 <img id="ik-base" src="data:image/png;base64,@original_png" alt="original"6 style="display:block;width:100%;" draggable="false" />7 <div id="ik-clip" style="position:absolute;inset:0;width:50%;overflow:hidden;">8 <img id="ik-top" src="data:image/png;base64,@edges_png" alt="edge magnitude"9 style="display:block;width:360px;max-width:none;" draggable="false" />10 </div>11 <div id="ik-handle" style="position:absolute;top:0;bottom:0;left:50%;width:2px;12 background:#f5c542;box-shadow:0 0 0 1px rgba(0,0,0,0.35);"></div>13 </div>14 <p style="text-align:center;font-size:13px;color:var(--verso-fg-muted,#666);margin:10px 0 0;">15 left of the handle: Sobel magnitude · right: the original16 </p>17</div>18<script>19(function () {20 var stage = document.getElementById('ik-stage');21 var clip = document.getElementById('ik-clip');22 var handle = document.getElementById('ik-handle');23 if (!stage || !clip || !handle) return;2425 function place(clientX) {26 var box = stage.getBoundingClientRect();27 var pct = Math.max(0, Math.min(1, (clientX - box.left) / box.width)) * 100;28 clip.style.width = pct + '%';29 handle.style.left = pct + '%';30 }3132 var dragging = false;33 stage.addEventListener('pointerdown', function (e) {34 dragging = true;35 stage.setPointerCapture(e.pointerId);36 place(e.clientX);37 });38 stage.addEventListener('pointermove', function (e) { if (dragging) place(e.clientX); });39 stage.addEventListener('pointerup', function () { dragging = false; });40 stage.addEventListener('pointercancel', function () { dragging = false; });41})();42</script>
left of the handle: Sobel magnitude · right: the original
Make it yours
Download the notebook and change nine numbers. A kernel whose weights sum to one preserves brightness, which is why blur and sharpen look like the same photograph; a kernel summing to zero returns darkness everywhere the image is flat, which is why the edge results are mostly black.
The emboss kernel is the interesting one to fiddle with: it is asymmetric, so rotating the weights changes which direction the light appears to come from.
Run it yourself
Nothing on this page is executable; the outputs were baked in by a real run. Download the notebook and it runs anywhere Verso does: VS Code, the browser, or the terminal.
dotnet tool install --global Verso.Cliverso serve image-kernels.versoWhat this shows
Blur, sharpen, emboss, and edge detection are one operation with nine numbers changed. Eight kernels on the same photograph, then a handle you drag to wipe the edges across the original.
Every language in this notebook reads and writes the same variable store, so a value produced in one cell is simply there in the next, whatever the language.