Every image is a landscape.

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.

  1. 1Plot an image in 3D
  2. 2Five ways to blur
  3. 3Edge detectors
  4. 4Inside Canny, stage by stage
  5. 5Thresholding
  6. 6Morphological transformations
  7. 7Image pyramids
  8. 8Contours
  9. 9Hough line transform
  10. 10Playground
  11. 11Experiments and your own images

It stays in your browser, shrunk and turned gray first.

GaussianBlur ksize (1, 1)

The text “cv2” as terrain. Drag sideways to turn it, slide to blur it.

1Plot an image in 3D

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:

  1. Load the image as grayscale, so there’s one number (one height) per pixel: cv2.imread(path, cv2.IMREAD_GRAYSCALE).
  2. Read its size: h, w = img.shape gives rows, then columns.
  3. List the coordinates: np.arange(w) for columns and np.arange(h) for rows.
  4. Grid them: X, Y = np.meshgrid(x, y) makes two arrays with the same shape as the image.
  5. Make a figure and a 3D axes: fig.add_subplot(projection="3d").
  6. Draw: ax.plot_surface(X, Y, img, cmap="gray").
  7. Fix the view: set_zlim, invert_yaxis, view_init, set_title.
  8. Show it: plt.show().

What meshgrid actually builds

A tiny 4 × 5 “image” so every number fits on screen. Step through it, then hover or tap any cell.


        
img: the heights
x and y: just lists
x
y
X: column of every pixel
Y: row of every pixel
Nothing to plot yet: plot_surface needs X and Y as well as the heights.

The function, line by line

def 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 callWhat it changesWorth trying
cmap="gray"Colours each tile by its height."viridis", "terrain"
vmin, vmaxWhich values count as black and white. Fixing them stops matplotlib from stretching each image’s contrast separately.0, 255 for uint8 images
rcount, ccountThe 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=0Removes 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

Try the settings

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.

imshow (2D)
plot_surface (3D) drag sideways to turn

2Five ways to blur

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

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 and cv2.boxFilter

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

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

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

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)

Which blur?

Your image hasReach forBecause
Fine, even grainGaussianBlurSmooth weighting averages grain away without blocky artefacts.
Isolated black or white specksmedianBlurOutliers never become the median.
Noise, but the edges must stay sharpbilateralFilterIt ignores neighbours across an edge. Slower.
Nothing special, speed mattersblurThe cheapest possible average.
A specific kernel in mindfilter2DIt runs any kernel you write.
Edge detection coming nextGaussianBlur, 3 × 3 to 5 × 5Removes the speckle that would otherwise become fake edges.

3Edge detectors

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

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)

The CV_8U trap

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 lost
cv2.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

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

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

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 with MORPH_GRADIENT

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)

Which edge detector?

FunctionMeasuresOutputGood for
SobelFirst derivative in x or ySigned floatDirection, your own magnitude and threshold
ScharrSame, more accurate at 3 × 3Signed floatSmall, direction-sensitive gradients
LaplacianSecond derivative, all directionsSigned float, edges at zero crossingsFine detail, sharpness scores
CannyThinned, connected gradient ridgesBinary, 0 or 255Clean outlines, contours, lines
MORPH_GRADIENTDilation minus erosionGrayscale bandOutlines of masks and shapes

4Inside Canny, stage by stage

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.

Your blur: Canny won’t do this for you
Gradient strength from Sobel x and y
Thin ridges after non-max suppression
Hysteresis: the final edges
Above high: sure edge Between low and high, kept because it touches a sure edge

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()

5Thresholding

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.

cv2.threshold

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)

THRESH_OTSU

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

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.

Input
Histogram: how many pixels have each brightness (bar heights square-rooted so small counts show)
Global, your T
Otsu, one T chosen for you

Adaptive, a T for every neighbourhood

6Morphological transformations

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.

OperationCallWhat it doesUse it for
Erosioncv2.erode(img, kernel)Shrinks white regionsRemoving thin specks, separating touching objects
Dilationcv2.dilate(img, kernel)Grows white regionsJoining broken strokes, thickening thin lines
Openingcv2.MORPH_OPENErode, then dilateRemoving white specks while keeping objects their size
Closingcv2.MORPH_CLOSEDilate, then erodeFilling small black holes inside objects
Gradientcv2.MORPH_GRADIENTDilation minus erosionOutlines
Top hatcv2.MORPH_TOPHATImage minus its openingSmall bright details on an uneven background
Black hatcv2.MORPH_BLACKHATClosing minus the imageSmall dark details on a bright background

Stays in your browser.

Input
Output
What changed: added and removed
The structuring element

7Image pyramids

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.

Gaussian pyramid, built with cv2.pyrDown

Laplacian pyramid: the detail each step threw away (contrast stretched per level; the last level is the small Gaussian image itself)

Going back up

Original
pyrUp from the smallest level only
pyrUp plus the Laplacian level at each step

Blending two images

The 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.

Left
Right
Direct join
Pyramid blend

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.

8Contours

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.

cv2.findContours

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 = all

Measuring a contour

contourArea, 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"]   # centre

Stays in your browser.

Contours tap a shape or a table row to pick it
Outer outlineHole outlinePicked, with its stored points
Binary input to findContours

9Hough line transform

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.

cv2.HoughLines

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

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.

Canny edges: the voters
Accumulator: θ from 0° to 180° across, ρ down hover a spot

Detected lines

10Playground

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.

Input
Output

Output in 3D drag sideways to turn

11Experiments and your own images

Each one sets up the playground for you. Make your prediction before you look, then change the one setting it mentions.

Starter script for your own images

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".

The OpenCV docs, and where each one lives on this page