21 May Contour Detection with OpenCV
Contour detection is a fundamental technique in computer vision used to identify and extract the boundaries of objects in an image. OpenCV provides powerful functions to detect, analyze, and manipulate contours.
Contour Retrieval Modes
OpenCV provides different ways to retrieve contours:
- cv2.RETR_EXTERNAL: This mode only detects outer contours (ignores nested objects).
- cv2.RETR_LIST: This mode detects all contours without hierarchy.
- cv2.RETR_TREE: This mode Detects all contours and reconstructs hierarchy (for nested objects).
Contour Approximation Methods
- cv2.CHAIN_APPROX_NONE: It stores all contour points (no compression).
- cv2.CHAIN_APPROX_SIMPLE: It compresses horizontal, vertical, and diagonal segments.
Common Applications of Contour Detection
- Object Detection & Recognition
- Shape Analysis(e.g., detecting squares, circles)
- Medical Imaging(tumor boundary detection)
- Industrial Automation(defect detection in products)
- Augmented Reality (AR) & Robotics
Let us see an example of basic contour detection:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# Contour Detection import cv2 # Load image and convert to binary image = cv2.imread(r'C:\Users\hp\Downloads\Astronaut.png') gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) _, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) # Find contours contours, _ = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # Draw contours on original image cv2.drawContours(image, contours, -1, (0, 255, 0), 2) # Green contours, thickness=2 # Display result cv2.imshow("Contours", image) cv2.waitKey(0) cv2.destroyAllWindows() |
Output
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.
For Videos, Join Our YouTube Channel: Join Now
Read More:
- Apply Sepia Tone filter with OpenCV
- Generative AI Tutorial
- Machine Learning Tutorial
- Deep Learning Tutorial
- Ollama Tutorial
- Retrieval Augmented Generation (RAG) Tutorial
- Copilot Tutorial
- Gemini Tutorial
- ChatGPT Tutorial
No Comments