Skip to content
OpenCV

Edge Detection

Detect edges with Canny, Sobel, and Laplacian.

By EZ4Code Team
edgecannysobel

Code

import cv2
import numpy as np

img = cv2.imread("input.jpg", cv2.IMREAD_GRAYSCALE)

# Canny edge detector
edges = cv2.Canny(img, threshold1=100, threshold2=200,
                  apertureSize=3, L2gradient=True)

# Sobel gradients
gx = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=3)
gy = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=3)
magnitude = cv2.magnitude(gx, gy)
sobel = np.uint8(np.clip(magnitude, 0, 255))

# Laplacian
lap = cv2.Laplacian(img, cv2.CV_64F, ksize=3)
lap_abs = cv2.convertScaleAbs(lap)

# Auto Canny via median
sigma = 0.33
v = np.median(img)
lower = int(max(0, (1 - sigma) * v))
upper = int(min(255, (1 + sigma) * v))
auto = cv2.Canny(img, lower, upper)

Explanation

Canny is the standard edge detector, with two thresholds controlling hysteresis and apertureSize setting the Sobel kernel it uses internally. Sobel returns directional gradients whose magnitude gives edge strength, while Laplacian highlights rapid intensity changes. Auto-Canny derives thresholds from the image median.

More OpenCV Snippets