Treat each pixel’s brightness as a height and a photo turns into terrain: blurring sands the hills down, and edges are the cliffs. This page shows how to plot that terrain in matplotlib, then works through OpenCV’s image-processing tutorials (blurs, edges, thresholds, morphology, pyramids, contours and Hough lines) with live demos you can run on your own pictures.
It stays in your browser, shrunk and turned gray first.
The text “cv2” as terrain. Drag sideways to turn it, slide to blur it.
matplotlib’s plot_surface draws a sheet through points in space. For every point it needs three numbers: how far across (X), how far back (Y) and how high (Z). A grayscale image only stores the heights. It has no x or y values anywhere, just positions in an array. np.meshgrid builds the missing X and Y so all three line up.
Here’s the order to write it in:
cv2.imread(path, cv2.IMREAD_GRAYSCALE).h, w = img.shape gives rows, then columns.np.arange(w) for columns and np.arange(h) for rows.X, Y = np.meshgrid(x, y) makes two arrays with the same shape as the image.fig.add_subplot(projection="3d").ax.plot_surface(X, Y, img, cmap="gray").set_zlim, invert_yaxis, view_init, set_title.plt.show().A tiny 4 × 5 “image” so every number fits on screen. Step through it, then hover or tap any cell.
img: the heightsx and y: just listsX: column of every pixelY: row of every pixeldef plot_surface(ax, image, title, vmin=0, vmax=255):
h, w = image.shape # rows, columns
X, Y = np.meshgrid(np.arange(w), np.arange(h)) # column and row of every pixel
ax.plot_surface(X, Y, image, cmap="gray", # height = brightness, colour = brightness
vmin=vmin, vmax=vmax, # same black and white points for every plot
rcount=200, ccount=200, # draw up to 200 x 200 tiles (default is 50)
linewidth=0) # no wireframe lines between tiles
ax.set_zlim(vmin, vmax) # same height axis, so flatter really looks flatter
ax.invert_yaxis() # row 0 at the back, like imshow
ax.set_title(title)
fig = plt.figure(figsize=(10, 8), layout="constrained")
ax3d = fig.add_subplot(2, 2, 3, projection="3d") # grid of 2 x 2, third cell, 3D
plot_surface(ax3d, img, "Original (surface)")| Argument or call | What it changes | Worth trying |
|---|---|---|
cmap="gray" | Colours each tile by its height. | "viridis", "terrain" |
vmin, vmax | Which values count as black and white. Fixing them stops matplotlib from stretching each image’s contrast separately. | 0, 255 for uint8 images |
rcount, ccount | The most rows and columns of tiles drawn. Above that, matplotlib skips pixels. The default of 50 hides fine texture on real photos. | 150 to 300 |
linewidth=0 | Removes the lines between tiles. | 0.2 to see the tiles |
ax.set_zlim(0, 255) | Fixes the height axis. Without it, a blurred image gets auto-zoomed and looks as tall as the original. | Remove it and compare |
ax.invert_yaxis() | Puts row 0 at the back so the surface isn’t a mirror image of imshow. | Toggle it below |
ax.view_init(elev, azim) | Camera angle: elev is degrees above the floor, azim is how far you walk around it. | elev=60, azim=-90 |
The amber dot marks pixel [0, 0], the top-left of the image, in both views. Turn invert_yaxis on and off and watch where it lands.
Every blur slides a small window, the kernel, across the image and replaces each pixel with some mix of its neighbours. Blurs are low-pass filters: they keep slow changes and remove fast ones. Noise is a fast change, which is why blurring removes it. Edges are fast changes too, so most blurs soften them a little. The five functions below differ only in how they mix the neighbours.
cv2.filter2D(src, ddepth, kernel)
Applies any kernel you hand it. A 5 × 5 kernel of 1/25s is a plain average. Other numbers sharpen, emboss, or become your own Sobel filter.
ddepth=-1 keeps the input type, so uint8 results get clipped to 0–255. Pass cv2.CV_64F to keep negative values. Strictly, it computes correlation (the kernel isn’t flipped), which only matters for lopsided kernels.
Use it when you know exactly which kernel you want, including ones you designed.
kernel = np.ones((5, 5), np.float32) / 25 # average
out = cv2.filter2D(img, -1, kernel)
sharpen = np.array([[ 0, -1, 0],
[-1, 5, -1],
[ 0, -1, 0]])
out = cv2.filter2D(img, -1, sharpen)cv2.blur(src, (kw, kh)) cv2.boxFilter(src, -1, (kw, kh), normalize=True)
Takes the plain average of every pixel in a box. boxFilter does the same, and with normalize=False it adds them up instead of averaging, which turns most of an 8-bit image white.
Use it for the fastest rough smoothing, or as a baseline to compare the other blurs against.
out = cv2.blur(img, (5, 5)) out = cv2.boxFilter(img, -1, (5, 5), normalize=False) # sum
cv2.GaussianBlur(src, (kw, kh), sigmaX, sigmaY=0)
A weighted average where the centre pixel counts most and the weights fall off like a bell curve. Kernel width and height must be positive and odd. If sigmaY is left out it copies sigmaX, and if both are 0 OpenCV works sigma out from the kernel size. You can also go the other way: pass (0, 0) as the size and a sigma, and the size is worked out for you.
Use it for general fine-grain noise, and almost always just before edge detection.
out = cv2.GaussianBlur(img, (5, 5), 0) # sigma from ksize out = cv2.GaussianBlur(img, (0, 0), 3) # ksize from sigma print(cv2.getGaussianKernel(5, 0).ravel()) # the weights
cv2.medianBlur(src, ksize)
Replaces each pixel with the median of its window. Unlike the averaging blurs, the result is always a value that was already in the image. A single bright speck can’t drag the median, so it simply vanishes. ksize must be odd.
Use it for salt-and-pepper noise: isolated black and white specks.
out = cv2.medianBlur(img, 5)
cv2.bilateralFilter(src, d, sigmaColor, sigmaSpace)
Combines two Gaussians: one for distance, like GaussianBlur, and one for brightness difference. Neighbours that look very different from the centre pixel get almost no weight, so it smooths flat regions while leaving edges sharp. It’s noticeably slower.
d is the window diameter. sigmaColor sets how different a neighbour’s brightness can be and still count. sigmaSpace sets how far away it can be.
Use it to smooth texture or skin while keeping outlines, or before edge detection when you want crisp edges.
out = cv2.bilateralFilter(img, 9, 75, 75)
| Your image has | Reach for | Because |
|---|---|---|
| Fine, even grain | GaussianBlur | Smooth weighting averages grain away without blocky artefacts. |
| Isolated black or white specks | medianBlur | Outliers never become the median. |
| Noise, but the edges must stay sharp | bilateralFilter | It ignores neighbours across an edge. Slower. |
| Nothing special, speed matters | blur | The cheapest possible average. |
| A specific kernel in mind | filter2D | It runs any kernel you write. |
| Edge detection coming next | GaussianBlur, 3 × 3 to 5 × 5 | Removes the speckle that would otherwise become fake edges. |
An edge is a place where brightness changes quickly: a cliff in the 3D view. Edge detectors are high-pass filters. They respond to change and go quiet on flat ground. Most of them give signed output, positive for dark-to-light and negative for light-to-dark, which is why the playground draws them in blue and red.
cv2.Sobel(src, ddepth, dx, dy, ksize=3)
The first derivative in one direction, with a little smoothing built in, which makes it more tolerant of noise than a bare difference. dx=1, dy=0 measures change from left to right, so it lights up vertical edges. dx=0, dy=1 finds horizontal ones. ksize can be 1, 3, 5 or 7.
Use it when you want the direction of an edge, or want to build your own magnitude and threshold.
gx = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=3) # vertical edges gy = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=3) # horizontal edges mag = cv2.magnitude(gx, gy) # sqrt(gx**2 + gy**2) edges = np.where(mag > 100, 255, 0).astype(np.uint8)
If you ask for an 8-bit output, every negative value is clipped to 0. Light-to-dark edges are negative, so half of every outline disappears. Keep a float type (cv2.CV_64F or cv2.CV_16S), then take the absolute value.
cv2.Sobel(img, cv2.CV_8U, 1, 0): right side lostcv2.convertScaleAbs(cv2.Sobel(img, cv2.CV_64F, 1, 0))gx = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=3) gx_8u = cv2.convertScaleAbs(gx) # absolute value, capped at 255, back to uint8
Prefer cv2.convertScaleAbs over np.uint8(np.abs(gx)): values above 255 are capped instead of wrapping around to dark.
cv2.Scharr(src, ddepth, dx, dy)
A 3 × 3 derivative with weights 3, 10, 3 instead of Sobel’s 1, 2, 1. It measures diagonal edges more accurately than a 3 × 3 Sobel. cv2.Sobel(..., ksize=-1) gives the same thing.
Use it when you want small-kernel gradients and care about edge direction.
gx = cv2.Scharr(img, cv2.CV_64F, 1, 0) gy = cv2.Scharr(img, cv2.CV_64F, 0, 1)
cv2.Laplacian(src, ddepth, ksize=1)
The second derivative in both directions at once, so one call covers every orientation. With ksize=1 the kernel is [[0, 1, 0], [1, -4, 1], [0, 1, 0]]. It fires on both sides of an edge, positive on one side and negative on the other, and the edge itself sits where it crosses zero.
It’s very sensitive to noise, so blur first. That combination is called a Laplacian of Gaussian.
Use it for fine detail, and as a quick sharpness score: cv2.Laplacian(img, cv2.CV_64F).var() is low for blurry photos.
lap = cv2.Laplacian(img, cv2.CV_64F, ksize=3) smooth = cv2.GaussianBlur(img, (5, 5), 0) log = cv2.Laplacian(smooth, cv2.CV_64F) # "LoG" sharpness = cv2.Laplacian(img, cv2.CV_64F).var()
cv2.Canny(src, threshold1, threshold2, apertureSize=3, L2gradient=False)
A whole pipeline in one call that returns thin, connected, black-and-white edges. threshold1 and threshold2 are the low and high limits for hysteresis, apertureSize is the Sobel kernel size, and L2gradient=True switches the strength formula from |gx| + |gy| to the square-root version.
One catch: the OpenCV tutorial lists noise reduction as the first stage, but cv2.Canny has no blur argument and starts at the gradient step. Blurring is your job.
Use it for clean outline maps, and as input to contours or Hough line detection.
smooth = cv2.GaussianBlur(img, (5, 5), 0) edges = cv2.Canny(smooth, 50, 150) # low, high edges = cv2.Canny(smooth, 50, 150, L2gradient=True)
cv2.morphologyEx(src, cv2.MORPH_GRADIENT, kernel)
Not a derivative at all: it grows the image (dilation), shrinks it (erosion) and subtracts the two. What’s left is a band around every boundary, as thick as the kernel.
Use it on masks and black-and-white images, where you want a quick outline of each shape.
kernel = np.ones((3, 3), np.uint8) outline = cv2.morphologyEx(img, cv2.MORPH_GRADIENT, kernel)
| Function | Measures | Output | Good for |
|---|---|---|---|
Sobel | First derivative in x or y | Signed float | Direction, your own magnitude and threshold |
Scharr | Same, more accurate at 3 × 3 | Signed float | Small, direction-sensitive gradients |
Laplacian | Second derivative, all directions | Signed float, edges at zero crossings | Fine detail, sharpness scores |
Canny | Thinned, connected gradient ridges | Binary, 0 or 255 | Clean outlines, contours, lines |
MORPH_GRADIENT | Dilation minus erosion | Grayscale band | Outlines of masks and shapes |
Canny is Sobel plus two clean-up steps. First, non-maximum suppression walks along each pixel’s gradient direction and keeps the pixel only if it’s the peak, which shrinks thick ridges to one-pixel lines. Then hysteresis uses two thresholds: lines above the high one are sure edges, lines below the low one are thrown away, and anything in between survives only if it touches a sure edge.
Set low and high to the same value and the in-between band disappears, so nothing can be rescued. Pull low down and watch the amber pixels appear.
Stays in your browser.
The tutorial’s exercise is to drive the two thresholds with trackbars. Here’s that app in plain OpenCV:
import cv2
img = cv2.imread("your_image.jpg", cv2.IMREAD_GRAYSCALE)
img = cv2.GaussianBlur(img, (5, 5), 0) # Canny doesn't blur for you
cv2.namedWindow("canny")
cv2.createTrackbar("low", "canny", 100, 500, lambda v: None)
cv2.createTrackbar("high", "canny", 200, 500, lambda v: None)
while True:
low = cv2.getTrackbarPos("low", "canny")
high = cv2.getTrackbarPos("high", "canny")
cv2.imshow("canny", cv2.Canny(img, low, high))
if cv2.waitKey(30) & 0xFF == 27: # Esc quits
break
cv2.destroyAllWindows()Thresholding turns grayscale into black and white by asking every pixel one question: are you brighter than T? Your Sobel cutoff was exactly this, applied to edge strength. The hard part is choosing T. You can pick it by hand, let Otsu’s method choose one value for the whole image, or let adaptive thresholding choose a different value for every neighbourhood.
ret, out = cv2.threshold(src, thresh, maxval, type)
Pixels brighter than thresh become maxval and the rest become 0. That’s THRESH_BINARY. The other types change what happens on each side: BINARY_INV flips it, TRUNC caps bright pixels at thresh, TOZERO keeps bright pixels and zeroes dark ones, and TOZERO_INV does the reverse.
It returns two things: the threshold it used, then the image. The input should be grayscale.
Use it when the lighting is even and you know roughly where the cutoff should be.
ret, binary = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) ret, capped = cv2.threshold(img, 127, 255, cv2.THRESH_TRUNC)
cv2.threshold(src, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
Instead of you choosing T, Otsu’s method reads the histogram and picks the value that splits the pixels into two groups as cleanly as possible, with the least spread inside each group. The thresh you pass is ignored, and the value it chose comes back as ret.
It works best when the histogram has two clear humps. Noise blurs the humps together, so blur first.
Use it for objects on a background with fairly even light, when you don’t want to hand-tune T.
blur = cv2.GaussianBlur(img, (5, 5), 0)
ret, otsu = cv2.threshold(blur, 0, 255,
cv2.THRESH_BINARY + cv2.THRESH_OTSU)
print("Otsu chose", ret)cv2.adaptiveThreshold(src, maxval, method, type, blockSize, C)
Works out a separate threshold for every pixel from the blockSize × blockSize square around it: the plain mean with ADAPTIVE_THRESH_MEAN_C, or a Gaussian-weighted mean with ADAPTIVE_THRESH_GAUSSIAN_C, minus the constant C. A shadow darkens the neighbourhood along with the pixel, so the shadow stops mattering.
blockSize must be odd. A larger C makes fewer pixels count as bright.
Use it for documents, whiteboards and anything lit unevenly.
out = cv2.adaptiveThreshold(img, 255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY, 11, 2)Stays in your browser.
Morphology changes the shape of white regions rather than their brightness. A small mask called the structuring element (or kernel) slides over the image. Erosion keeps a pixel white only if the whole kernel fits inside white, so shapes shrink and thin specks vanish. Dilation turns a pixel white if the kernel touches any white, so shapes grow and gaps close. Everything else is built from those two.
It’s designed for binary images with the objects in white. If your objects are dark, threshold with THRESH_BINARY_INV first.
| Operation | Call | What it does | Use it for |
|---|---|---|---|
| Erosion | cv2.erode(img, kernel) | Shrinks white regions | Removing thin specks, separating touching objects |
| Dilation | cv2.dilate(img, kernel) | Grows white regions | Joining broken strokes, thickening thin lines |
| Opening | cv2.MORPH_OPEN | Erode, then dilate | Removing white specks while keeping objects their size |
| Closing | cv2.MORPH_CLOSE | Dilate, then erode | Filling small black holes inside objects |
| Gradient | cv2.MORPH_GRADIENT | Dilation minus erosion | Outlines |
| Top hat | cv2.MORPH_TOPHAT | Image minus its opening | Small bright details on an uneven background |
| Black hat | cv2.MORPH_BLACKHAT | Closing minus the image | Small dark details on a bright background |
Stays in your browser.
A pyramid is the same image at several sizes. cv2.pyrDown blurs with a 5 × 5 Gaussian and drops every other row and column, so each level has a quarter of the pixels. cv2.pyrUp goes the other way, but it can’t bring back the detail that was dropped. Pyramids let a detector search for things at many sizes, and let you blend images without a visible seam.
A Laplacian pyramid stores exactly that missing detail: each level is a Gaussian level minus the pyrUp of the level above it. Keep those differences and you can rebuild the original perfectly.
Stays in your browser.
cv2.pyrDownpyrUp from the smallest level onlypyrUp plus the Laplacian level at each stepThe tutorial’s “orapple”: join the left half of one image to the right half of another at every Laplacian level, then rebuild. Coarse levels blend over a wide band, fine levels over a narrow one, so the seam disappears without blurring the detail.
Your photo goes on the left.
The tutorial builds its Laplacian levels with cv2.subtract on uint8 images. That clips every negative difference to 0, and it fails outright when a size doesn’t halve evenly. The code here works in float32 and passes dstsize to pyrUp, which avoids both.
A contour is the outline of a white region, stored as a list of points. cv2.findContours traces every one in a binary image, so the usual pipeline is blur, threshold (or Canny), then find contours. Once you have them you can measure each shape: its area, perimeter, bounding box, corners and centre.
contours, hierarchy = cv2.findContours(binary, mode, method)
It looks for white objects on a black background. mode decides which outlines you get: RETR_EXTERNAL only the outermost ones, RETR_LIST every outline with no family tree, and RETR_TREE every outline plus which one sits inside which.
method decides how many points are stored. CHAIN_APPROX_NONE keeps every boundary pixel. CHAIN_APPROX_SIMPLE keeps only the ends of straight runs, so a rectangle needs just 4 points.
hierarchy[0][i] is [next, previous, first_child, parent] for contour i, with -1 meaning none.
blur = cv2.GaussianBlur(img, (5, 5), 0)
ret, binary = cv2.threshold(blur, 0, 255,
cv2.THRESH_BINARY + cv2.THRESH_OTSU)
contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE)
color = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
cv2.drawContours(color, contours, -1, (0, 255, 0), 2) # -1 = allcontourArea, arcLength, boundingRect, approxPolyDP, convexHull, moments
approxPolyDP simplifies the outline until no point is further than epsilon from it. With epsilon around 2% of the perimeter, the number of corners left is a quick shape test: 3 is a triangle, 4 a quadrilateral, many a curve.
Comparing a contour’s area with its convex hull’s area (solidity) tells convex shapes from ones with dents, like stars.
Use these to filter detections by size, find rectangular things like documents and screens, or count objects.
for cnt in contours:
area = cv2.contourArea(cnt)
perimeter = cv2.arcLength(cnt, True) # True = closed
x, y, w, h = cv2.boundingRect(cnt)
corners = cv2.approxPolyDP(cnt, 0.02 * perimeter, True)
hull = cv2.convexHull(cnt)
solidity = area / max(cv2.contourArea(hull), 1)
M = cv2.moments(cnt)
if M["m00"]:
cx, cy = M["m10"] / M["m00"], M["m01"] / M["m00"] # centreStays in your browser.
Any straight line can be described by two numbers: ρ, its distance from the top-left corner, and θ, the angle of the shortest path to it. In OpenCV’s convention a vertical line has θ = 0° and a horizontal line has θ = 90°.
The Hough transform makes every edge pixel vote for all the lines that could pass through it. Each vote lands in a grid of (ρ, θ) cells called the accumulator. A real line gets votes from all of its pixels, so it shows up as a bright spot. Hover over the accumulator below to see which line each spot stands for.
lines = cv2.HoughLines(edges, rho, theta, threshold)
Takes a binary edge map, usually from Canny. rho and theta are the cell sizes (1 pixel and 1° are typical), and threshold is the fewest votes a line needs. Since every pixel on a line is one vote, the threshold is roughly the shortest line you’ll accept.
It returns infinite lines as (ρ, θ) pairs, or None if nothing passes, so check before looping.
edges = cv2.Canny(img, 50, 150)
lines = cv2.HoughLines(edges, 1, np.pi / 180, 80)
color = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
if lines is not None:
for rho, theta in lines[:, 0]:
a, b = np.cos(theta), np.sin(theta)
x0, y0 = a * rho, b * rho # closest point to the corner
p1 = (int(x0 - 1000 * b), int(y0 + 1000 * a))
p2 = (int(x0 + 1000 * b), int(y0 - 1000 * a))
cv2.line(color, p1, p2, (0, 0, 255), 1)cv2.HoughLinesP(edges, rho, theta, threshold, minLineLength, maxLineGap)
The probabilistic version votes with a random subset of edge pixels, which is faster, and returns finite segments as x1, y1, x2, y2 instead of infinite lines. minLineLength drops short segments and maxLineGap joins pieces separated by small gaps.
Use it when you want where a line starts and ends: lane markings, table borders, building edges.
segments = cv2.HoughLinesP(edges, 1, np.pi / 180, 50,
minLineLength=30, maxLineGap=5)
if segments is not None:
for x1, y1, x2, y2 in segments[:, 0]:
cv2.line(color, (x1, y1), (x2, y2), (0, 255, 0), 2)Stays in your browser.
Pick an image, add noise, choose a function and tune it. The Python underneath updates as you go, so you can paste it straight into your own script.
Stays in your browser. It’s shrunk and turned gray first.
Each one sets up the playground for you. Make your prediction before you look, then change the one setting it mentions.
A checkerboard through an 11 × 11 cv2.blur. Predict the 3D shape of each square, then switch to GaussianBlur at the same size. Which keeps flatter tops?
10% salt and pepper through a 5 × 5 Gaussian. Do the specks vanish or just spread out? Then try medianBlur with ksize 5.
Bilateral filter with sigmaColor at 10. Is any grain removed? Raise it to 150 and watch what happens to the edges.
Sobel x saved as CV_8U. For the bright disc and the dark square, predict which side of each survives before you look. Why are they opposite?
A Laplacian of a lightly noisy image. Can you find the shapes at all? Turn on “GaussianBlur 5 × 5 first” and compare.
In the Canny section, start with low and high both at 150. How many amber pixels are there? Slide low down to 40 and count again.
The rings image, no filter, rcount 20. Do you see the true pattern? Slowly raise rcount and note where the fake pattern goes away.
Upload a picture, then use Sobel magnitude with a blur first. Find the cutoff where texture like fur or grass disappears but the main outline survives. Does Canny do better at the same strength?
The page of text. Which of the three results keeps the dark bottom-right corner readable? Slide your T up and down: is there any single value that works for the whole page?
Shapes with noise at σ 30 and no clean-up. Where does Otsu’s T land, and how speckled is its result? Then switch “Clean up first” to GaussianBlur and watch the histogram change.
Opening on the speckled letters. Predict which disappear, the white specks outside or the black holes inside. Then switch to closing.
Pyramid blending with 1 level, then 6. How wide is the transition band each time, and why does it grow with more levels?
The shape set with RETR_EXTERNAL. How many contours are there? Predict the count for RETR_TREE before you switch, then check which ones have a parent.
Start the Hough threshold at 120 and lower it slowly. At what value does the sun circle start producing fake lines?
HoughLinesP on the dashed centre line of the road, with maxLineGap at 0. Raise it until the dashes join into one segment. How big were the gaps?
The same 2D-over-3D layout as before, with one line to swap for any function on this page.
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread("your_image.jpg", cv2.IMREAD_GRAYSCALE)
assert img is not None, "Check the file path"
def plot_surface(ax, image, title, vmin=0, vmax=255):
h, w = image.shape
X, Y = np.meshgrid(np.arange(w), np.arange(h))
ax.plot_surface(X, Y, image, cmap="gray", vmin=vmin, vmax=vmax,
rcount=150, ccount=150, linewidth=0)
ax.set_zlim(vmin, vmax)
ax.invert_yaxis()
ax.set_title(title)
result = cv2.GaussianBlur(img, (11, 11), 0) # swap in any function from this page
fig = plt.figure(figsize=(10, 8), layout="constrained")
for i, (name, im) in enumerate({"Original": img, "Result": result}.items()):
ax = fig.add_subplot(2, 2, i + 1) # top row: 2D
ax.imshow(im, cmap="gray", vmin=0, vmax=255)
ax.set_title(name)
ax.axis("off")
ax3d = fig.add_subplot(2, 2, i + 3, projection="3d") # bottom row: 3D
plot_surface(ax3d, im, name + " (3D)")
plt.show()For signed results like Sobel or Laplacian, convert them first with cv2.convertScaleAbs, or pass vmin=-m, vmax=m and cmap="RdBu_r".