Sub topic 8
Gradient Magnitude and Direction
Assume you know basic Python, NumPy array shapes and dtypes, grayscale images, and Sobel derivatives in OpenCV. This chapter starts with two derivative images, gx and gy, and combines them into a description of each pixel's local intensity change.
The gradient as a vector
For a grayscale image, the horizontal derivative gx measures intensity change from left to right. The vertical derivative gy measures change from top to bottom. Together they form a gradient vector:
- Gradient magnitude:
sqrt(gx² + gy²) - Gradient direction:
atan2(gy, gx)
A large magnitude means a strong local change, which often indicates an edge. A small magnitude means that nearby pixels have similar intensity.
The direction points toward increasing intensity. In an image, the horizontal axis points right and the vertical axis points down. Therefore, a direction of 0 degrees points right, and 90 degrees points down. The direction of the edge itself is perpendicular to the gradient direction.
Compute the two components safely
Derivative values can be negative. Use a signed or floating-point output type instead of uint8, because an unsigned image cannot represent negative values.
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)
magnitude, direction = cv2.cartToPolar(
gx, gy, angleInDegrees=True
)
magnitude_view = cv2.normalize(
magnitude, None, 0, 255, cv2.NORM_MINMAX
).astype(np.uint8)
print("magnitude:", magnitude.shape, magnitude.dtype)
print("direction:", direction.shape, direction.dtype)cv2.cartToPolar applies the magnitude and angle formulas element by element. The result keeps floating-point precision. The normalized magnitude_view is only for display. Normalization changes the numerical scale, so do not use that image as the original gradient strength without recording the scale.
| Quantity | Meaning | Typical use |
|---|---|---|
| `gx` | Horizontal intensity change | Find vertical boundaries |
| `gy` | Vertical intensity change | Find horizontal boundaries |
| `magnitude` | Overall change strength | Rank likely edges |
| `direction` | Direction of increasing intensity | Analyze edge orientation |
Interpret weak and strong gradients
Noise can create large derivatives, especially when neighboring pixels vary rapidly. Blurring before differentiation usually makes the gradient more stable, but too much blur removes small features. A flat region has low magnitude and an unreliable direction. When the magnitude is near zero, avoid drawing conclusions from its angle.
The gradient direction describes intensity change, not necessarily the visible edge orientation. For example, a vertical boundary has a horizontal gradient, so its gradient angle is near 0 or 180 degrees.
Exercise
A pixel has gx = 3 and gy = 4. What are its gradient magnitude and approximate direction in image coordinates?
Show answer
The magnitude is 5. The direction is atan2(4, 3), approximately 53.1 degrees, pointing down and right.