Edge Detection & Gradient Filters

These filters find boundaries between regions by detecting rapid changes in pixel brightness. Edge detection is foundational to object detection, segmentation, and feature extraction.

Classification of Edge Detection Filters

graph TD
    A[Edge Detection & Gradient Filters] --> B[First-Order Derivative]
    A --> C[Second-Order Derivative]
    A --> D[Multi-Stage Pipeline]

    B --> B1[Sobel Filter]
    B --> B2[Prewitt Filter]
    B --> B3[Roberts Cross Filter]
    B --> B4[Scharr Filter]

    C --> C1[Laplacian of Gaussian - LoG]

    D --> D1[Canny Edge Detector]

    style A fill:#4A90D9,color:#fff
    style B fill:#7BB661,color:#fff
    style C fill:#E8A04C,color:#fff
    style D fill:#C586C0,color:#fff

1. Sobel Filter

Spatial
The Sobel filter is a classic, widely used and edge detection filter used in image processing to highlight boundaries and sharp intensity changes. It operates in the spatial domain to calculate an approximation of the image gradient—meaning it finds the areas where the pixel intensity changes the most rapidly.

How it works?

Unlike the Laplacian filter (which uses a single kernel to find the second derivative), the Sobel filter uses a first-order derivative approach. It works by calculating the gradient of image intensity in two specific directions, horizontally and vertically.

To do this, it convolves (slides) two separate 3×3 kernels across the original image:

Gx=10+120+210+1The X-Direction KernelAGy=121000+1+2+1The Y-Direction KernelA
Key Keatures
Built-in Noise Smoothing

Referring to the concept in linear algebra called matrix separability, A 2D Sobel filter is separable if it can be written as the product of a "column" and a "row".

[101202101]=[121][101]

The Row Vector [101]: This is the actual derivative part. As it moves horizontally, it calculates the difference between the left pixel and the right pixel.
The Column Vector [121]: This acts vertically (perpendicular to the derivative). This is a 1D Gaussian smoothing filter. It averages the pixels from the row above, the current row, and the row below.
By using the weights 1, 2, 1, the Sobel filter is applying a weighted average. It Looks at the pixels above and below me to help smooth out any random specks of noise, but give double priority (the 2) to the exact row I am currently calculating.

When to use
When to avoid
Caution

Sobel detects edges per direction. If you only compute Gx, you will miss horizontal edges entirely. Always compute the full magnitude unless you intentionally want directional edges.

2. Prewitt Filter

Spatial
Identical in concept to Sobel, the Prewitt Filter is another classic, first-order derivative edge-detection operator in image processing. The main and only difference between both is Prewitt Filter uses a simpler, uniform kernel without the center-weighted smoothin

How it works
Like the Sobel filter, the Prewitt operator works in the spatial domain to calculate the image gradient. It slides two 3×3 convolution kernels across the original image to detect the rate of brightness change in two distinct directions:

Gx=10+110+110+1The X-Direction KernelAGy=111000+1+1+1The Y-Direction KernelA

Gradient Magnitude (Edge Strength):

G=Gx2+Gy2

Gradient Direction (Edge Orientation):

θ=arctan(GyGx)
Key Features
Uniform Averaging (Box Blur):

Prewitt filter can be decomposed into a 1D derivative [101] and a 1D smoothing vector [111]. This means it applies a uniform, equal-weight average perpendicular to the edge direction. 👎 It treats the row above, the current row, and the row below with exact equal importance. If you are trying to find the precise location of a horizontal pixel change, blurring everything equally across three rows can "smear" the edge vertically.

When to use
When to avoid

3. Roberts Cross Filter

How it works
Uses two tiny 2×2 diagonal kernels to compute gradients at 45° and 135°.

Gx=+1001Gy=0+110

When to use

When to avoid

Caution

Roberts Cross is rarely used in modern pipelines. It is included for historical completeness and for very constrained environments. In almost every other case, Sobel or Canny will produce better results.

4. Canny Edge Detector

Canny is best described as an "Optimal Edge Detection Algorithm" that integrates both smoothing and sharpening filters into a complete pipeline.

How it works?

A multi-stage algorithm, not a simple convolution:

  1. Gaussian Smoothing — reduces noise before edge detection.
  2. Sobel Gradient — computes edge magnitude and direction at every pixel.
  3. Non-Maximum Suppression — thins edges to 1-pixel-wide lines by keeping only local maxima in the gradient direction.
  4. Double Thresholding — classifies pixels into
    • Strong edges (above high threshold)
    • Weak edges (between low and high)
    • Non-edges (using both threshold)
  5. Hysteresis — promotes weak edge pixels that are connected to strong edge pixels; discards isolated weak ones.
graph LR
	A[Input Image] --> B[1\.
Gaussian
Smoothing] B --> C[2\.
Gradient
Calculation
Sobel] C --> D[3\.
Non-Maximum
Suppression] D --> E[4\.
Double
Thresholding] E --> F[5\.
Edge
Tracking by
Hysteresis] F --> G[Final Edge Map]
When to use
Parameters to tune
When to avoid
Caution

The two thresholds in Canny need to be tuned per-image or per-dataset. A fixed threshold that works well on one lighting condition may fail completely on another. Consider using automatic threshold selection (e.g., based on the median pixel intensity of the image).


5. Scharr Filter

Spatial
The Scharr filter is a direct refinement of Sobel. Sobel's 1-2-1 weighted smoothing kernel is a reasonable approximation of a Gaussian, but it introduces a subtle directional bias — the gradient magnitude it reports can vary slightly depending on the angle of the edge. The Scharr filter corrects this by replacing those weights with 3-10-3, which is the mathematically optimal weighting for near-perfect rotational symmetry. In practice, this means Scharr reports the same edge strength regardless of whether the edge is vertical, horizontal, or diagonal.

How it works?

Exactly like Sobel: two kernels slide across the image — one for horizontal change (Gx), one for vertical (Gy). The only difference is the kernel weights.

Gx=30+3100+1030+3The X-Direction KernelAGy=3103000+3+10+3The Y-Direction KernelA

Gradient magnitude and direction are computed the same way as Sobel:

G=Gx2+Gy2θ=arctan(GyGx)
Step-by-Step Example

A 3×3 patch with a sharp left-to-right transition (dark left, bright right — a vertical edge):

Image Patch=[505020050502005050200]

Applying Gx (Scharr):

Gx=(3)(50)+(0)(50)+(3)(200)+(10)(50)+(0)(50)+(10)(200)+(3)(50)+(0)(50)+(3)(200)=150+600500+2000150+600=2400

Applying Gx (Sobel) on the same patch — for comparison:

GxSobel=(1)(50)+(0)(50)+(1)(200)+(2)(50)+(0)(50)+(2)(200)+(1)(50)+(0)(50)+(1)(200)=50+200100+40050+200=600

Both correctly detect the vertical edge, and Gy=0 for both (the patch has no top-to-bottom variation). The Scharr value is 4× larger because its weights are heavier — this is expected and not the point. The real advantage is directional accuracy: on a diagonal (45°) edge, Sobel's magnitude drifts by ~5% depending on the exact angle; Scharr stays consistent.

Sobel vs Scharr at a glance
Sobel Scharr
Smoothing weights 1 - 2 - 1 3 - 10 - 3
Rotational accuracy ~95% isotropic ~99.8% isotropic
Noise sensitivity Moderate Slightly higher (larger weights)
Kernel sizes available 3×3, 5×5, 7×7, … Fixed 3×3 only
Best use case General-purpose edge detection Gradient direction accuracy
When to use
When to avoid
Tip

In OpenCV, use cv2.Scharr(img, cv2.CV_64F, 1, 0) for the X gradient and cv2.Scharr(img, cv2.CV_64F, 0, 1) for Y. It is equivalent to cv2.Sobel() with ksize=-1.


6. Laplacian of Gaussian (LoG) — Edge Detection Mode

Spatial Second-Order Derivative

Cross-reference

The LoG filter is covered in detail in II — Sharpening Filters → LoG from an image sharpening and enhancement perspective. This section focuses on how the same filter is used as a precision edge detector through zero-crossing detection.

The key difference: Sharpening vs Edge Detection

The filter output is identical in both cases — what changes is entirely what you do with the result.

Mode What you do with the LoG output
Sharpening Add or subtract the LoG response to the original image to enhance edges
Edge Detection Find zero-crossings — locations where the output flips sign — to locate boundaries
How Zero-Crossings Work

The Laplacian of an image is positive on one side of an edge and negative on the other. Exactly at the edge, it passes through zero. Finding where the LoG output flips sign gives a precise, thin edge map.

graph LR
    A[Input Image] --> B["Gaussian Blur (Reduce Noise)"]
    B --> C["Apply Laplacian (Second Derivative)"]
    C --> D["Find Zero-Crossings (Sign flips)"]
    D --> E[Edge Map]
Step-by-Step (1D illustration)

A simplified 1D intensity profile crossing from dark to bright:

Original intensities:10,10,10,80,80,80

After Gaussian smoothing (the sharp jump softens into a ramp):

Smoothed:10,15,35,55,75,80

First derivative (gradient) — peaks at the transition:

1st derivative:5,20,20,20,5

Second derivative (Laplacian) — crosses zero at the edge:

2nd derivative:+15,0,0,15

The zero-crossing sits exactly at the midpoint of the intensity transition — this is the detected edge. No magnitude thresholding needed to localize it precisely.

Why use LoG instead of Sobel?
Sobel / Scharr LoG (Zero-Crossing)
Derivative order First (gradient) Second (Laplacian)
Edge localization Peak of gradient magnitude Zero-crossing — more precise
Directionality Separate X and Y kernels Isotropic — equal response in all directions
Scale control Kernel size σ of the Gaussian
Noise sensitivity Moderate Higher — Gaussian pre-smoothing is mandatory
Edge connectivity Not guaranteed Naturally produces closed, connected contours
Parameters to tune
When to use
When to avoid
Caution

Do not threshold the raw LoG output looking for large positive values — that is the sharpening use case. For edge detection, you must detect sign changes (zero-crossings) in the output. Naively thresholding the magnitude will not produce clean edges and is the most common misuse of LoG as an edge detector.