How to Use Contour Detection in OpenCV for Computer Vision
Use
cv2.findContours() in OpenCV to detect contours by passing a binary image. Contours represent boundaries of objects and can be processed for shape analysis or object detection.Syntax
The main function for contour detection in OpenCV is cv2.findContours(). It takes a binary image and returns contours and hierarchy information.
image: The input binary image (usually after thresholding or edge detection).mode: Contour retrieval mode (e.g.,cv2.RETR_EXTERNALfor outer contours).method: Contour approximation method (e.g.,cv2.CHAIN_APPROX_SIMPLEto compress horizontal, vertical, and diagonal segments).
python
contours, hierarchy = cv2.findContours(image, mode, method)
Example
This example loads an image, converts it to grayscale, applies thresholding to get a binary image, detects contours, and draws them on the original image.
python
import cv2 # Load image image = cv2.imread('shapes.png') # Convert to grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Apply binary threshold _, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) # Find contours contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Draw contours on the original image cv2.drawContours(image, contours, -1, (0, 255, 0), 3) # Save the result cv2.imwrite('contours_output.png', image) # Print number of contours found print(f'Number of contours found: {len(contours)}')
Output
Number of contours found: 3
Common Pitfalls
- Passing a non-binary image to
cv2.findContours()will not detect contours correctly. Always threshold or edge-detect first. - Using the wrong retrieval mode can miss inner contours or hierarchy details.
- Not handling the return values correctly: in OpenCV 4.x,
findContoursreturnscontours, hierarchy, but in older versions it returnsimage, contours, hierarchy.
python
import cv2 # Wrong: passing color image directly image = cv2.imread('shapes.png') contours, hierarchy = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # This will fail # Right: convert to grayscale and threshold first gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) _, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
Quick Reference
Contour Retrieval Modes:
cv2.RETR_EXTERNAL: Retrieves only the extreme outer contours.cv2.RETR_LIST: Retrieves all contours without establishing any hierarchical relationships.cv2.RETR_TREE: Retrieves all contours and reconstructs a full hierarchy of nested contours.
Contour Approximation Methods:
cv2.CHAIN_APPROX_NONE: Stores all contour points.cv2.CHAIN_APPROX_SIMPLE: Compresses horizontal, vertical, and diagonal segments and leaves only their end points.
Key Takeaways
Always convert images to binary format before using cv2.findContours for accurate detection.
Use cv2.RETR_EXTERNAL to get outer contours or cv2.RETR_TREE for full hierarchy of contours.
cv2.CHAIN_APPROX_SIMPLE reduces memory by compressing contour points without losing shape.
Contours can be drawn with cv2.drawContours to visualize detected shapes.
Check OpenCV version to handle findContours return values correctly.