OpenCV Python – Edge Detection
Edge detection is one of the most important techniques in computer vision. It helps identify the boundaries of objects within an image by detecting sudden changes in intensity.
In OpenCV Python, edge detection is widely used in object detection, image segmentation, and feature extraction.
1. What is Edge Detection?
Edge detection is the process of finding sharp changes in pixel intensity. These changes usually represent:
- Object boundaries
- Shape outlines
- Structural features
It helps convert a complex image into a simplified outline form.
2. Import OpenCV
import cv2
3. Read and Convert Image to Grayscale
Edge detection works best on grayscale images.
img = cv2.imread("image.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow("Gray Image", gray)
cv2.waitKey(0)
cv2.destroyAllWindows()
4. Canny Edge Detection
Canny is the most popular edge detection method.
Syntax:
cv2.Canny(image, threshold1, threshold2)
Example:
edges = cv2.Canny(gray, 100, 200)
cv2.imshow("Canny Edges", edges)
cv2.waitKey(0)
cv2.destroyAllWindows()
5. Sobel Edge Detection
Sobel detects edges in horizontal and vertical directions.
sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=3)
sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=3)
cv2.imshow("Sobel X", sobelx)
cv2.imshow("Sobel Y", sobely)
cv2.waitKey(0)
cv2.destroyAllWindows()
6. Laplacian Edge Detection
Laplacian detects edges in all directions.
laplacian = cv2.Laplacian(gray, cv2.CV_64F)
cv2.imshow("Laplacian", laplacian)
cv2.waitKey(0)
cv2.destroyAllWindows()
7. Combine Canny with Original Image
edges = cv2.Canny(gray, 100, 200)
result = cv2.bitwise_and(img, img, mask=edges)
cv2.imshow("Combined Output", result)
cv2.waitKey(0)
cv2.destroyAllWindows()
8. How Canny Edge Detection Works
Canny algorithm works in 5 steps:
- Noise reduction
- Gradient calculation
- Non-maximum suppression
- Double threshold
- Edge tracking by hysteresis
9. Why Edge Detection is Important
Edge detection is used in:
- Object detection systems
- Face recognition
- Autonomous vehicles
- Medical image analysis
- OCR (text recognition)
10. Common Mistakes
❌ Using color image directly
✔ Solution:
cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
❌ Wrong threshold values
✔ Solution:
- Try values between 50–150 for best results
11. Conclusion
Edge detection in OpenCV Python is a powerful technique for extracting object boundaries and simplifying images. It is a core step in many computer vision and AI applications.
Once you master edge detection, you can move to advanced topics like contours and shape detection.


0 Comments