Sub topic 9
The Laplacian and zero-crossing edges
Sobel finds edges at the peak of the first derivative. The Laplacian takes the second derivative instead. An edge then shows up as a place where the response changes sign, called a zero crossing. This chapter covers how cv2.Laplacian works, why the output depth matters, and how to turn its output into a binary edge map.
This chapter assumes you can read a grayscale image with cv2.imread, you know the difference between uint8 and float32 arrays, and you have seen Gaussian smoothing and Sobel gradients from the earlier chapters.
From first to second derivative
Take one row of pixels that steps from dark to bright:
import numpy as np
signal = np.array([10, 10, 10, 50, 50, 50], dtype=np.float32)
# Second difference: f[i-1] - 2*f[i] + f[i+1]
second = signal[:-2] - 2 * signal[1:-1] + signal[2:]
print(second) # [ 0. 40. -40. 0.]The second difference is zero on the flat areas, positive on the dark side of the step, and negative on the bright side. The edge lies between the +40 and the -40, where the sign flips. A first-derivative filter gives one hump at the edge, and you search for its peak. A second-derivative filter gives a positive lobe next to a negative lobe, and you search for the crossing between them.
The Laplacian adds the second derivatives in both image directions:
∇²f = ∂²f/∂x² + ∂²f/∂y²
It responds to intensity changes in every direction at once, so it is isotropic. It does not tell you the direction of an edge. Sobel gives you gx and gy for that.
The Laplacian kernel
For ksize=1, OpenCV convolves the image with the 4-neighbour kernel:
0 1 0
1 -4 1
0 1 0Its coefficients sum to zero, so a flat region gives exactly 0.
| Option | What it computes | Notes |
|---|---|---|
| `ksize=1` | The 3x3 kernel above | Cheapest. Sensitive to noise. |
| `ksize=3, 5, ...` | Sum of Sobel second derivatives | Has built-in smoothing. Larger magnitudes, so thresholds differ from `ksize=1`. |
| `cv2.filter2D` with a custom kernel | Any kernel you supply | Use it for the 8-neighbour variant. |
The 8-neighbour variant also counts the diagonal pixels:
import cv2
import numpy as np
kernel8 = np.array([[1, 1, 1],
[1, -8, 1],
[1, 1, 1]], dtype=np.float32)
# lap8n = cv2.filter2D(blur, cv2.CV_32F, kernel8)Computing it with a safe output depth
The depth rule from the Sobel chapter applies here too. The Laplacian is negative on one side of every edge. If you ask for cv2.CV_8U, every negative value is clipped to 0. You lose half the response, and you can no longer detect sign changes.
import cv2
import numpy as np
gray = cv2.imread("input.jpg", cv2.IMREAD_GRAYSCALE)
if gray is None:
raise FileNotFoundError("input.jpg could not be read")
blur = cv2.GaussianBlur(gray, (0, 0), 2) # sigma = 2, size chosen by OpenCV
lap = cv2.Laplacian(blur, cv2.CV_32F, ksize=1) # signed float result
print(lap.dtype, float(lap.min()), float(lap.max()))
# For viewing only: absolute value, saturated to uint8
lap_view = cv2.convertScaleAbs(lap)Keep lap as the float array for any further processing. Use lap_view only for display, because convertScaleAbs discards the sign.
Why you must smooth first
A second derivative amplifies noise more than a first derivative does. Each output pixel combines the center value with four neighbours, and a single noisy pixel produces a strong response with both signs. Smoothing before the Laplacian is not optional.
Smoothing with a Gaussian and then applying the Laplacian is called the Laplacian of Gaussian (LoG). The Gaussian's sigma sets the scale:
- A small sigma keeps fine detail and noise.
- A large sigma keeps only coarse, strong edges and rounds corners.
Passing (0, 0) as the kernel size to GaussianBlur and giving sigmaX lets you set the scale directly, which is the clearest way to tune LoG.
Detecting zero crossings
A zero crossing is a pair of neighbouring pixels whose Laplacian values have opposite signs. In a textured or noisy image, tiny sign flips occur everywhere, even where the response is nearly zero. These produce a speckle of false edges. The fix is to require that the jump across the pair is large enough.
import cv2
import numpy as np
def zero_crossings(lap, min_step):
"""Mark pixels whose Laplacian changes sign against the right or lower
neighbour, when the size of the jump is at least min_step."""
out = np.zeros(lap.shape, np.uint8)
a, b = lap[:, :-1], lap[:, 1:] # horizontal neighbour pairs
horizontal = (a * b < 0) & (np.abs(a - b) >= min_step)
c, d = lap[:-1, :], lap[1:, :] # vertical neighbour pairs
vertical = (c * d < 0) & (np.abs(c - d) >= min_step)
out[:, :-1][horizontal] = 255
out[:-1, :][vertical] = 255
return out
gray = cv2.imread("input.jpg", cv2.IMREAD_GRAYSCALE)
if gray is None:
raise FileNotFoundError("input.jpg could not be read")
blur = cv2.GaussianBlur(gray, (0, 0), 2)
lap = cv2.Laplacian(blur, cv2.CV_32F, ksize=1)
edges = zero_crossings(lap, min_step=8.0)
print("edge pixels:", int(np.count_nonzero(edges)))The function compares each pixel with its right and lower neighbour. This is enough to find every sign change in the image. It marks the left or upper pixel of each pair, so the edge is placed within one pixel of the true crossing.
The min_step threshold plays a role similar to Canny's thresholds. Its useful range depends on sigma, on the contrast of your image, and on ksize. Print np.abs(lap).max() and choose a fraction of it as a starting point, then adjust by looking at the result.
Strengths and limits compared with Sobel and Canny
Zero crossings have a real advantage. Because a sign change between two pixels is a closed condition, the resulting edges form closed curves. There are no gaps where a threshold on gradient magnitude happened to fall short.
They also have costs:
- The detector responds to weak sign changes in smooth gradients. Without
min_step, you get many false edges. - Corners are rounded, and thin lines can be displaced or doubled, especially at large sigma.
- The output has no direction and no magnitude you can use directly.
- There is no non-maximum suppression or hysteresis, so edges are not guaranteed to be one pixel wide or connected to strong edges.
For these reasons, Canny is the usual choice when you need clean, thin edge maps. The Laplacian is useful when you want closed contours, a scale-controlled detector through sigma, or a measure of fine detail.
Another use: measuring sharpness
The Laplacian responds strongly to fine detail, so the variance of its output is a common focus measure. A blurred image has a low variance, and a sharp one has a high variance.
import cv2
gray = cv2.imread("input.jpg", cv2.IMREAD_GRAYSCALE)
if gray is None:
raise FileNotFoundError("input.jpg could not be read")
focus = cv2.Laplacian(gray, cv2.CV_64F).var()
print("variance of Laplacian:", focus)Compare values only between images of the same scene type and size. The absolute number depends on content, so you must pick a cutoff from your own data.
Common mistakes
- Skipping the blur. The Laplacian magnifies noise, so the zero crossings are mostly noise.
- Using
convertScaleAbsoutput for sign tests. The sign is gone after that call. - Using the same
min_stepafter changingksizeorsigma. Both change the size of the response. - Expecting thin, connected edges. Use Canny when you need them.
Exercise
A learner calls cv2.Laplacian(blur, cv2.CV_8U) and passes the result to a zero-crossing detector. The detector finds almost no edges. Explain why, and give the fix.
Show answer
With CV_8U output, OpenCV saturates all negative Laplacian values to 0. A zero crossing needs a positive value next to a negative one, but after clipping there are no negative values, so no pair has opposite signs. The fix is to compute the Laplacian in a signed or float depth such as cv2.CV_32F, keep that array for the sign test, and use cv2.convertScaleAbs only to produce an image for display.
Exercise
For the row [20, 20, 80, 80], compute the second difference f[i-1] - 2*f[i] + f[i+1] at the two interior positions. Between which two pixels is the zero crossing?
Show answer
At index 1 the value is 20 - 40 + 80 = 60. At index 2 it is 20 - 160 + 80 = -60. The sign changes from positive to negative between index 1 and index 2, which is exactly where the step from 20 to 80 occurs.