Sub topic 7
Finding intensity changes with Sobel and Scharr
This chapter covers how OpenCV measures intensity change with first-derivative kernels. It assumes you can read an image with cv2.imread, that you know the difference between uint8 and float32 arrays, and that you know what convolution with a small kernel does. Later chapters build gradient magnitude, direction and Canny on top of this one.
What a gradient measures
An edge is a place where pixel intensity changes quickly. The image gradient at a pixel is a pair of numbers: how fast intensity changes in the x direction (left to right) and in the y direction (top to bottom). A flat region gives values near zero. A sharp boundary gives large values.
On a discrete image the derivative is approximated by a difference between neighbouring pixels. The simplest version, I(x+1) - I(x-1), is very sensitive to noise, because one noisy pixel changes the answer directly. Sobel and Scharr reduce this by combining the difference with smoothing in the perpendicular direction.
The Sobel kernel
The 3x3 Sobel kernel for the x derivative is:
import numpy as np
sobel_x = np.array([[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1]], dtype=np.float32)
sobel_y = sobel_x.TIt is the outer product of two 1D kernels: a difference [-1, 0, 1] along x and a smoothing kernel [1, 2, 1] along y. Each row is weighted, so the middle row counts twice as much as its neighbours. The result responds to vertical edges (intensity changing along x) and averages over three rows, which suppresses noise.
Two sign conventions matter:
gxis positive where intensity increases from left to right (dark to bright).gyis positive where intensity increases from top to bottom, because image rows count downward.
Because dark-to-bright gives a positive value and bright-to-dark gives a negative one, the output must be able to store negative numbers.
Computing Sobel with cv2.Sobel
import cv2
import numpy as np
img = cv2.imread("input.jpg")
if img is None:
raise FileNotFoundError("input.jpg could not be read")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
gx = cv2.Sobel(blur, cv2.CV_32F, 1, 0, ksize=3)
gy = cv2.Sobel(blur, cv2.CV_32F, 0, 1, ksize=3)
print(gx.dtype, gx.min(), gx.max())The signature is cv2.Sobel(src, ddepth, dx, dy, ksize=3). The arguments are:
| Argument | Meaning |
|---|---|
| `ddepth` | Depth of the output array, such as `cv2.CV_32F` or `cv2.CV_16S` |
| `dx` | Order of the derivative in x (0 or 1 for a first derivative) |
| `dy` | Order of the derivative in y |
| `ksize` | Kernel size: 1, 3, 5 or 7 (odd), or `cv2.FILTER_SCHARR` |
dx=1, dy=0 gives the x derivative, and dx=0, dy=1 gives the y derivative. Passing dx=1, dy=1 computes a mixed second-order term, which is not the gradient magnitude. Compute the two derivatives separately and combine them afterwards.
Why the output depth matters
This is the most common mistake with Sobel. If you leave the output depth at cv2.CV_8U, which is the depth of a uint8 input, OpenCV saturates results to the range 0 to 255. Every negative value becomes 0.
bad = cv2.Sobel(blur, cv2.CV_8U, 1, 0, ksize=3) # loses dark-to-bright...
good = cv2.Sobel(blur, cv2.CV_32F, 1, 0, ksize=3)In bad, only one polarity of edge survives. A white object on a black background shows its left edge but loses its right edge, because the right edge has a negative derivative. Use a signed or floating-point depth so that both polarities are kept: cv2.CV_32F and cv2.CV_64F are the usual choices, and cv2.CV_16S is a compact signed integer option.
If you want a viewable 8-bit picture afterwards, convert deliberately:
abs_gx = cv2.convertScaleAbs(gx) # abs() then saturate to uint8convertScaleAbs takes the absolute value first, so both polarities appear as bright pixels. Note that it clips anything above 255, so it is fine for display but discards range.
Kernel size and scale
A larger ksize (5 or 7) averages over more pixels. This lowers noise sensitivity and responds to broader edges, but it blurs fine detail and localizes edges less precisely. Larger kernels also give larger raw values, since the weights sum to bigger numbers. Do not compare raw magnitudes across different ksize values without rescaling. The optional scale argument multiplies the result, and delta adds an offset.
Applying a Gaussian blur first, as above, is the usual way to control noise. Choose between a larger blur followed by ksize=3, or a larger ksize, based on how much noise you have. The blur then Sobel route is easier to tune because the blur strength is a separate parameter.
Scharr: a more accurate 3x3 kernel
The Sobel 3x3 kernel is a rough approximation of a derivative, and its response varies with edge direction. Scharr uses different weights that are more rotationally consistent:
scharr_x = np.array([[ -3, 0, 3],
[-10, 0, 10],
[ -3, 0, 3]], dtype=np.float32)In OpenCV you can call it in two ways, and they give the same result:
gx_scharr = cv2.Scharr(blur, cv2.CV_32F, 1, 0)
gx_scharr2 = cv2.Sobel(blur, cv2.CV_32F, 1, 0, ksize=cv2.FILTER_SCHARR)cv2.Scharr has no ksize argument because it is always 3x3. It supports only a single derivative at a time, so one of dx and dy must be 1 and the other 0.
Scharr responses are about 3 to 4 times larger than Sobel's on the same image, so thresholds tuned for one do not transfer to the other.
| Property | Sobel 3x3 | Scharr 3x3 |
|---|---|---|
| Weights | 1, 2, 1 smoothing | 3, 10, 3 smoothing |
| Direction accuracy | Moderate | Better |
| Available sizes | 1, 3, 5, 7 | 3 only |
| Output scale | Smaller | Larger |
Choose Scharr when you need accurate gradient direction at 3x3, for example when you compute orientation. Choose Sobel when you need larger kernels or higher-order derivatives.
How a gradient responds to an edge
A worked check
Build a tiny image with a known step edge and verify the sign and size of the response.
import cv2
import numpy as np
step = np.zeros((5, 6), np.uint8)
step[:, 3:] = 100 # dark on the left, bright on the right
gx = cv2.Sobel(step, cv2.CV_32F, 1, 0, ksize=3)
gy = cv2.Sobel(step, cv2.CV_32F, 0, 1, ksize=3)
gx_8u = cv2.Sobel(step, cv2.CV_8U, 1, 0, ksize=3)
print(gx[2]) # [0. 0. 400. 400. 0. 0.]
print(gy[2]) # all zeros in the interior
print(gx_8u[2]) # [0 0 255 255 0 0] (saturated)The step has height 100. The Sobel x kernel has a positive column sum weighting of 1+2+1 = 4 on each side, so the interior response is 4 x 100 = 400 at the two pixels next to the edge. The vertical derivative is zero because nothing changes from top to bottom. The 8-bit version clips 400 to 255. Flip the step so that the left side is bright and the CV_8U result becomes all zeros, while the float result becomes -400.
Common gotchas
- Negative values vanish. Using
CV_8Uoutput discards one edge polarity. - Noise is amplified. A derivative boosts high frequencies, so unfiltered noisy images give a messy gradient. Blur first.
- Color images. Applying Sobel to a 3-channel image filters each channel independently. Convert to grayscale first unless you need per-channel gradients.
- Overflow in manual code. If you compute differences with NumPy on
uint8arrays, values wrap around (3 - 5 becomes 254). Convert tofloat32first. - Borders. The outermost pixels use the border mode, which is
BORDER_REFLECT_101by default, so the border row or column of the gradient is computed from reflected data rather than real neighbours.
Exercise
You run cv2.Sobel(gray, cv2.CV_8U, 1, 0) on a photo of a white square on a black background. The square's left edge appears but its right edge is missing. Why, and what is the fix?
Show answer
The right edge goes from white to black, so its x derivative is negative. With a CV_8U output, negative values saturate to 0 and disappear. Use a signed or float depth such as cv2.CV_32F (or cv2.CV_16S), then take the absolute value or the magnitude when you need a displayable image, for example with cv2.convertScaleAbs.
Exercise
You switch from cv2.Sobel(blur, cv2.CV_32F, 1, 0, ksize=3) to cv2.Scharr(blur, cv2.CV_32F, 1, 0) and your fixed gradient threshold now marks far too many pixels as edges. What is the likely cause?
Show answer
Scharr's weights are larger, so its responses are roughly 3 to 4 times bigger than Sobel's on the same image. A threshold tuned for Sobel is too low for Scharr. Raise the threshold by about that factor, or normalize both outputs to a common scale before comparing.