0
0
Computer-visionHow-ToBeginner ยท 4 min read

How to Use Canny Edge Detection in Computer Vision

Use cv2.Canny() from OpenCV to detect edges by specifying the input image and two threshold values. It finds strong and weak edges and connects them to highlight object boundaries clearly.
๐Ÿ“

Syntax

The cv2.Canny() function detects edges in an image using two threshold values. The syntax is:

  • image: The input grayscale image.
  • threshold1: Lower boundary for edge detection.
  • threshold2: Upper boundary for edge detection.
  • apertureSize (optional): Size of the Sobel kernel (default is 3).
  • L2gradient (optional): Boolean to use a more accurate gradient calculation.
python
edges = cv2.Canny(image, threshold1, threshold2, apertureSize=3, L2gradient=False)
๐Ÿ’ป

Example

This example loads a grayscale image, applies Canny edge detection, and displays the original and edge images side by side.

python
import cv2
import numpy as np

# Load image in grayscale
image = cv2.imread('input.jpg', cv2.IMREAD_GRAYSCALE)

# Check if image loaded
if image is None:
    raise FileNotFoundError('Image file not found.')

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

# Stack images horizontally for comparison
combined = np.hstack((image, edges))

# Show the images
cv2.imshow('Original and Edges', combined)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output
A window opens showing the original grayscale image on the left and the detected edges on the right.
โš ๏ธ

Common Pitfalls

  • Wrong image format: Canny requires a grayscale image, not color.
  • Threshold values: Setting thresholds too low or too high can miss edges or detect noise.
  • Ignoring noise: Applying Canny on noisy images without smoothing can cause false edges.

Always convert to grayscale and consider applying Gaussian blur before Canny.

python
import cv2

# Wrong way: Using color image
image_color = cv2.imread('input.jpg')
edges_wrong = cv2.Canny(image_color, 100, 200)  # May give incorrect results

# Right way: Convert to grayscale and blur
image_gray = cv2.cvtColor(image_color, cv2.COLOR_BGR2GRAY)
image_blur = cv2.GaussianBlur(image_gray, (5, 5), 1.4)
edges_right = cv2.Canny(image_blur, 100, 200)
๐Ÿ“Š

Quick Reference

ParameterDescriptionTypical Values
imageInput grayscale imageGrayscale image array
threshold1Lower threshold for edge detection50-150
threshold2Upper threshold for edge detection100-300
apertureSizeSobel kernel size for gradient3 (default), 5, or 7
L2gradientUse precise gradient calculationFalse (default) or True
โœ…

Key Takeaways

Always convert your image to grayscale before applying Canny edge detection.
Choose threshold values carefully to balance edge detection and noise suppression.
Apply Gaussian blur to reduce noise and improve edge detection quality.
Use cv2.Canny() with proper parameters to detect clear edges.
Visualize results side by side to verify edge detection effectiveness.