← Back to Documentation

Algorithm Reference: Canny Edge Detection

Type: Feature Detection / Gradient Analysis
Library: OpenCV (cv2.Canny)
Application: Structural Analysis & Sketch Generation

Canny Edge Detection is widely considered the "gold standard" for edge detection algorithms. Unlike simple Sobel filters, Canny uses a multi-stage process involving noise reduction, gradient calculation, non-maximum suppression, and hysteresis thresholding to produce clean, thin lines.

1. Mathematical Formulation

The algorithm detects edges by looking for local maxima in the gradient of the image. For a smoothed image I, the gradient intensity (strength of the edge) at any pixel is calculated using the derivative in x and y directions:

G = √( Gx2 + Gy2 )

The direction of the edge θ is determined by the angle of the gradient:

θ = arctan( Gy / Gx )

Pixels are only kept as edges if their gradient magnitude is a local maximum in the direction of the gradient. This step, called "Non-Maximum Suppression," ensures that thick blurry edges are thinned down to a single pixel width.

2. Python Backend Logic (Snippet)

While browsers can perform simple convolution, the Canny multi-stage process is computationally intensive for high-resolution images. We run this pipeline on our Python server to ensure consistent performance across mobile and desktop devices.

Below is the conceptual logic used to generate the "Sketch" effect. Note the importance of pre-processing (Grayscale + Blur) before applying the edge detector.


def process_canny_edges(image, low_thresh, high_thresh):
    # 1. Convert to Grayscale
    # Edges are defined by intensity, not color
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # 2. Noise Reduction (Gaussian Blur)
    # Essential to prevent false edge detection from noise
    blurred = cv2.GaussianBlur(gray, (5, 5), 1.4)

    # 3. Apply Canny Algorithm
    # Uses Hysteresis Thresholding to connect weak edges
    edges = cv2.Canny(
        blurred,
        threshold1=low_thresh,
        threshold2=high_thresh
    )

    return edges

3. Hysteresis Thresholding

The unique power of Canny lies in its use of two thresholds:

This allows the algorithm to trace faint lines (like a jawline) as long as they connect to strong lines (like a shirt collar), creating a continuous sketch.

Try the Edge Tool:

Launch Live Tool