Sub topic 8
Gradient magnitude and direction
This chapter assumes you can run OpenCV and NumPy in Python, know how cv2.Sobel is called, and understand dtypes such as uint8 and float32. The previous chapter produced two images, gx and gy. Here you combine them into two more useful quantities: how strong an intensity change is, and which way it points.
From two derivatives to one vector
At every pixel, gx measures how fast intensity changes along x (columns). gy measures the same along y (rows). Together they form the gradient vector (gx, gy), which has two properties:
- Magnitude is the length of the vector. It tells you how sharp the change is. Edges have large magnitude and flat regions have magnitude near zero.
- Direction is the angle of the vector. It points toward increasing brightness, so it is perpendicular to the edge itself.
OpenCV's y axis points down. An angle of 90° therefore points toward the bottom of the image, and the angle grows clockwise on screen.
Computing both with cartToPolar
The least ambiguous way to see the numbers is a synthetic image with one known edge. The left half is black and the right half is white.
import cv2
import numpy as np
img = np.zeros((200, 200), np.uint8)
img[:, 100:] = 255 # vertical step edge between columns 99 and 100
gx = cv2.Sobel(img, cv2.CV_32F, 1, 0, ksize=3)
gy = cv2.Sobel(img, cv2.CV_32F, 0, 1, ksize=3)
mag, angle = cv2.cartToPolar(gx, gy, angleInDegrees=True)
print("gx at the edge:", gx[50, 99], gx[50, 100])
print("mag, angle:", mag[50, 100], round(float(angle[50, 100])))
# Flip the polarity: white on the left, black on the right.
inv = 255 - img
gx2 = cv2.Sobel(inv, cv2.CV_32F, 1, 0, ksize=3)
gy2 = cv2.Sobel(inv, cv2.CV_32F, 0, 1, ksize=3)
mag2, angle2 = cv2.cartToPolar(gx2, gy2, angleInDegrees=True)
print("inverted:", mag2[50, 100], round(float(angle2[50, 100])))The first result is a magnitude of 1020 and an angle of 0°. The inverted image has the same magnitude but an angle of 180°.
The value 1020 comes from the Sobel kernel. Its weights in a column sum to 1 + 2 + 1 = 4, so a 0-to-255 step gives 4 × 255. The gradient points toward the white side. Flipping the polarity reverses the direction but not the strength.
Three details of cartToPolar matter:
gxandgymust have the same size and the same floating-point type (float32orfloat64).- With
angleInDegrees=Truethe angle lies in [0, 360). Without it, the angle is in radians in [0, 2π). - The angle of a zero vector is not meaningful. OpenCV returns 0 there.
Magnitude: L2, L1 and cv2.magnitude
The exact magnitude is the Euclidean (L2) length, sqrt(gx² + gy²). A cheaper approximation is the L1 sum |gx| + |gy|.
| Method | Formula | Notes |
|---|---|---|
| `cv2.magnitude(gx, gy)` | `sqrt(gx² + gy²)` | Same result as the `mag` from `cartToPolar`. Use it when you do not need the angle. |
| L1 | `abs(gx) + abs(gy)` | Faster. It is exact on axis-aligned edges. |
| `cv2.convertScaleAbs(gx)` plus `addWeighted` | Rough L1 blend, saturated to `uint8` | Common in older tutorials. It loses range and precision. |
L1 never underestimates. On a 45° edge it overestimates the true length by a factor of √2. The following snippet measures this on a diagonal edge.
import cv2
import numpy as np
yy, xx = np.mgrid[0:200, 0:200]
diag = np.where(xx > yy, 255, 0).astype(np.uint8) # 45-degree step edge
gx = cv2.Sobel(diag, cv2.CV_32F, 1, 0, ksize=3)
gy = cv2.Sobel(diag, cv2.CV_32F, 0, 1, ksize=3)
l2 = cv2.magnitude(gx, gy)
l1 = np.abs(gx) + np.abs(gy)
mask = l2 > 0
ratio = l1[mask] / l2[mask]
print("max L1/L2 ratio:", float(ratio.max())) # close to 1.414This is why cv2.Canny has an L2gradient flag. The default uses the L1 norm, so its thresholds act slightly differently on diagonal edges than they would with L2.
Turning magnitude into a viewable image
Magnitude values are floats up to about 1442 for a Sobel step edge (1020 × √2 when both derivatives are at their maximum). Casting straight to uint8 wraps or truncates the values. Normalize first.
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, (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)
mag, angle = cv2.cartToPolar(gx, gy, angleInDegrees=True)
mag8 = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)
# Direction as color: hue encodes angle, brightness encodes strength.
hsv = np.zeros((*gray.shape, 3), np.uint8)
hsv[..., 0] = (angle / 2).astype(np.uint8) # OpenCV hue range is 0-179
hsv[..., 1] = 255
hsv[..., 2] = mag8
cv2.imwrite("gradient_direction.png", cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR))
cv2.imwrite("gradient_magnitude.png", mag8)NORM_MINMAX scales relative to the largest value in this particular image. Two images normalized this way are not comparable by brightness. If you need a fixed scale, divide by a constant such as 1442 instead.
Direction details that cause bugs
- Signed versus unsigned direction. A dark-to-light edge and a light-to-dark edge differ by 180°. If you only care about the edge orientation, use
angle % 180. Histogram of oriented gradients (HOG) style features often use this unsigned form. Keep the full 0–360° range when polarity matters, for example to tell a bright object on a dark background from a dark one on a bright background. - Edge direction versus gradient direction. The edge runs along
angle ± 90°. Mixing these up is a common source of off-by-90° errors. - Weak gradients have noisy angles. Where magnitude is near zero, tiny noise values still produce a definite angle. Mask the angle map by a magnitude threshold before you analyze or plot it.
- Output depth. With
cv2.CV_8U, negative derivatives clip to 0, so you lose half of every edge pair and the angle becomes meaningless. Usecv2.CV_32F(orcv2.CV_16S) for the derivatives, as in the code above. - Kernel choice.
ksize=3Sobel is not perfectly rotation-invariant, so angles are slightly off for edges that are not axis-aligned.cv2.Scharr(blur, cv2.CV_32F, 1, 0)and theksize=-1form ofSobelgive a more accurate 3×3 kernel. Scharr also returns larger values (a step of 255 yields 16 × 255 = 4080), so rescale any magnitude thresholds you tuned for Sobel. - Noise. Differentiation amplifies noise. Without the Gaussian blur, magnitude maps of real photos look speckled and the angle map looks random.
Why Canny cares about the angle
Canny uses both outputs of this chapter. It thresholds magnitude, and it uses the direction to thin edges. For each pixel it rounds the angle to one of four directions (0°, 45°, 90°, 135°). It then keeps the pixel only if its magnitude is at least that of the two neighbors along that direction. This step is called non-maximum suppression, and it turns thick magnitude ridges into one-pixel-wide lines. The next chapters build on this.
Exercise
A Sobel (ksize=3) result at one pixel is gx = -300.0 and gy = 400.0 (float32). What are the L2 magnitude and the L1 magnitude? In which of the four quadrants of the 0–360° range does cartToPolar place the angle, and approximately what is it?
Show answer
L2 = sqrt(300² + 400²) = 500. L1 = 300 + 400 = 700. With gx negative and gy positive, the angle is in the 90°–180° range. It equals atan2(400, -300) = 180° - 53.13° ≈ 126.9°. On screen this vector points left and down, because OpenCV's y axis points down.
Exercise
You normalize a magnitude map with cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX) for two different photos and notice that the same faint texture looks bright in one and dark in the other. What causes this, and how do you fix it if you need comparable images?
Show answer
NORM_MINMAX rescales each image so its own smallest and largest values map to 0 and 255. A photo with one very strong edge compresses everything else toward black, while a low-contrast photo stretches its faint texture toward white. For comparable output, divide by a fixed constant instead, such as np.clip(mag / 1442 * 255, 0, 255).astype(np.uint8), so the same magnitude always gives the same brightness.