Edge detection is a fundamental technique in computer vision used to identify object boundaries. OpenCV provides powerful operators like Canny, Sobel, and Laplacian to detect edges effectively.
The Canny algorithm is a multi-stage process that detects strong and weak edges using gradients and thresholds.
import cv2
img = cv2.imread("sample.jpg", cv2.IMREAD_GRAYSCALE)
# Apply Canny Edge Detection
edges = cv2.Canny(img, 100, 200)
cv2.imshow("Canny Edges", edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
The Sobel operator calculates the gradient of image intensity. It highlights edges in the X and Y directions.
sobelx = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=5) # Horizontal edges
sobely = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=5) # Vertical edges
cv2.imshow("Sobel X", sobelx)
cv2.imshow("Sobel Y", sobely)
cv2.waitKey(0)
cv2.destroyAllWindows()
The Laplacian operator detects edges by calculating the second derivative of intensity. It highlights regions of rapid intensity change.
laplacian = cv2.Laplacian(img, cv2.CV_64F)
cv2.imshow("Laplacian Edges", laplacian)
cv2.waitKey(0)
cv2.destroyAllWindows()
✅ In this lesson, you learned how to use Canny, Sobel, and Laplacian operators for edge detection.
These techniques are widely used in object recognition, shape analysis, and feature extraction.
👉 Next, we will explore morphological operations (erosion, dilation, opening, closing).
