OpenCV Image Edge Detection

Image edge detection is a fundamental task in computer vision and image processing. It is used to identify regions in an image where brightness changes significantly, and these regions usually correspond to the boundaries of objects.

The following are the commonly used edge detection functions in OpenCV and their descriptions:

FunctionAlgorithmDescriptionApplicable Scenarios
cv2.Canny()Canny Edge DetectionMulti-stage algorithm, good detection performance, strong noise suppression capability.General-purpose edge detection, suitable for most scenarios.
cv2.Sobel()Sobel OperatorEdge detection based on first-order derivatives, can detect horizontal and vertical edges.Detect horizontal and vertical edges.
cv2.Scharr()Scharr OperatorAn improved version of the Sobel operator, with a stronger response to edges.Detect subtle edges.
cv2.Laplacian()Laplacian OperatorEdge detection based on second-order derivatives, sensitive to noise.Detect edges and corners.

1. Canny Edge Detection (cv2.Canny())

Canny edge detection is a multi-stage edge detection algorithm proposed by John F. Canny in 1986.

Canny edge detection is considered the "gold standard" of edge detection because it achieves a good balance between noise suppression and edge localization.

1.1 Steps of Canny Edge Detection

The Canny edge detection algorithm mainly includes the following steps:

  1. Noise suppression: Use a Gaussian filter to smooth the image to reduce the impact of noise.
  2. Gradient calculation: Use the Sobel operator to calculate the gradient magnitude and direction of the image.
  3. Non-maximum suppression: Along the gradient direction, keep the pixels with the maximum local gradient and suppress other pixels.
  4. Double threshold detection: Use two thresholds (low and high) to determine true edges. Pixels above the high threshold are considered strong edges, pixels below the low threshold are suppressed, and pixels between the two are retained if they are connected to strong edges.
  5. Edge connection: Through hysteresis thresholding, weak edges are connected to strong edges to form complete edges.

1.2 Implementing Canny Edge Detection with OpenCV

In OpenCV, you can use thecv2.Canny()function to implement Canny edge detection.

The prototype of this function is as follows:

edges = cv2.Canny(image, threshold1, threshold2, apertureSize=3, L2gradient=False)
  • image: Input image, must be a single-channel grayscale image.
  • threshold1: Low threshold.
  • threshold2: High threshold.
  • apertureSize: Aperture size of the Sobel operator, default is 3.
  • L2gradient: Whether to use the L2 norm to calculate the gradient magnitude, default is False (uses the L1 norm).

Example

import cv2
import numpy as np

# Read the image
image = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)

# Apply Canny edge detection
edges = cv2.Canny(image, 100, 200)

# Display the result
cv2.imshow('Canny Edges', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()

2. Sobel Operator (cv2.Sobel())

The Sobel operator is a gradient-based edge detection operator that detects edges by computing the gradients of the image in the horizontal and vertical directions.

The Sobel operator combines Gaussian smoothing and differentiation, so it has a certain suppression effect on noise.

2.1 Principle of the Sobel Operator

The Sobel operator uses two 3x3 convolution kernels to compute the gradients of the image in the horizontal and vertical directions, respectively:

  • Horizontal convolution kernel:
    [-1, 0, 1]
    [-2, 0, 2]
    [-1, 0, 1]
    
  • Vertical convolution kernel:
    [-1, -2, -1]
    [ 0,  0,  0]
    [ 1,  2,  1]
    

Through these two convolution kernels, the gradients of the image in the horizontal and vertical directions can be obtained, respectivelyGxandGy. The final gradient magnitude can be calculated using the following formula:

G = sqrt(Gx^2 + Gy^2)

2.2 Implementing the Sobel Operator with OpenCV

In OpenCV, you can use thecv2.Sobel()function to compute the gradient of an image. The prototype of this function is as follows:

dst = cv2.Sobel(src, ddepth, dx, dy, ksize=3, scale=1, delta=0, borderType=cv2.BORDER_DEFAULT)
  • src: Input image.
  • ddepth: Depth of the output image, usually usecv2.CV_64F。
  • dx: Order of the derivative in the x direction.
  • dy: Order of the derivative in the y direction.
  • ksize: Size of the Sobel kernel, default is 3.
  • scale: Scale factor, default is 1.
  • delta: Optional delta value, default is 0.
  • borderType: Border extension type, default iscv2.BORDER_DEFAULT。

Example

import cv2
import numpy as np

# Read the image
image = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)

# Compute the gradient in the x direction
sobel_x = cv2.Sobel(image, cv2.CV_64F, 1, 0, ksize=3)

# Compute the gradient in the y direction
sobel_y = cv2.Sobel(image, cv2.CV_64F, 0, 1, ksize=3)

# Compute the gradient magnitude
sobel_combined = np.sqrt(sobel_x**2 + sobel_y**2)

# Display the result
cv2.imshow('Sobel X', sobel_x)
cv2.imshow('Sobel Y', sobel_y)
cv2.imshow('Sobel Combined', sobel_combined)
cv2.waitKey(0)
cv2.destroyAllWindows()

3. Laplacian Operator (cv2.Laplacian())

The Laplacian operator is a second-order differential operator that detects edges by computing the second derivative of the image. The Laplacian operator is relatively sensitive to noise, so the image is usually smoothed with a Gaussian filter before use.

3.1 Principle of the Laplacian Operator

The Laplacian operator uses the following convolution kernel to compute the second derivative of the image:

[ 0,  1,  0]
[ 1, -4,  1]
[ 0,  1,  0]

With this convolution kernel, the Laplacian value of the image can be obtained. Regions with larger Laplacian values usually correspond to edges of the image.

3.2 Implementing the Laplacian Operator with OpenCV

In OpenCV, you can use thecv2.Laplacian()function to compute the Laplacian value of an image.

The prototype of this function is as follows:

dst = cv2.Laplacian(src, ddepth, ksize=1, scale=1, delta=0, borderType=cv2.BORDER_DEFAULT)
  • src: Input image.
  • ddepth: Depth of the output image, usually usecv2.CV_64F。
  • ksize: Size of the Laplacian kernel, default is 1.
  • scale: Scale factor, default is 1.
  • delta: Optional delta value, default is 0.
  • borderType: Border extension type, default iscv2.BORDER_DEFAULT。

Example

import cv2
import numpy as np

# Read the image
image = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)

# Apply the Laplacian operator
laplacian = cv2.Laplacian(image, cv2.CV_64F)

# Display the result
cv2.imshow('Laplacian', laplacian)
cv2.waitKey(0)
cv2.destroyAllWindows()

Comparison of Common Edge Detection Functions

The following is a comparison of common edge detection functions in OpenCV:

FunctionAlgorithmAdvantagesDisadvantagesApplicable Scenarios
cv2.Canny()Canny Edge DetectionStrong noise suppression, good edge detection performance.Parameter tuning is relatively complex.General-purpose edge detection, suitable for most scenarios.
cv2.Sobel()Sobel OperatorSimple computation, suitable for detecting horizontal and vertical edges.Sensitive to noise, average edge detection performance.Detect horizontal and vertical edges.
cv2.Scharr()Scharr OperatorStronger response to edges, suitable for detecting subtle edges.Sensitive to noise.Detect subtle edges.
cv2.Laplacian()Laplacian OperatorCan detect edges and corners.Very sensitive to noise.Detect edges and corners.
Other Extensions