How to Draw Contours in OpenCV for Computer Vision
To draw contours in OpenCV, use the
cv2.drawContours() function which takes the image, contours, contour index, color, and thickness as inputs. First, find contours using cv2.findContours(), then draw them on the image to visualize shapes or boundaries.Syntax
The main function to draw contours is cv2.drawContours(). It requires:
- image: The image where contours will be drawn.
- contours: List of contours found by
cv2.findContours(). - contourIdx: Index of contour to draw or
-1to draw all. - color: Color of the contour lines (BGR format).
- thickness: Thickness of contour lines.
python
cv2.drawContours(image, contours, contourIdx, color, thickness)
Example
This example loads an image, converts it to grayscale, finds contours, and draws them in green with thickness 3.
python
import cv2 # Load image image = cv2.imread('shapes.png') # Convert to grayscale gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Threshold the image to get a binary image _, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) # Find contours contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Draw all contours in green cv2.drawContours(image, contours, -1, (0, 255, 0), 3) # Save or display the result cv2.imwrite('contours_drawn.png', image)
Output
Creates 'contours_drawn.png' with green contours drawn around detected shapes.
Common Pitfalls
- Not converting the image to grayscale before finding contours can cause errors.
- Using the wrong contour index: use
-1to draw all contours. - Passing the original image to
cv2.findContours()instead of a binary image (like thresholded or edge-detected) will fail to find contours. - Confusing color format: OpenCV uses BGR, not RGB.
python
import cv2 # Wrong: Using color image directly for findContours image = cv2.imread('shapes.png') contours, _ = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Wrong # Right: Convert to grayscale and threshold gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) _, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Correct # Draw contours cv2.drawContours(image, contours, -1, (255, 0, 0), 2) # Blue contours
Quick Reference
Tips for drawing contours in OpenCV:
- Always preprocess image to binary (threshold or edges) before finding contours.
- Use
-1as contourIdx to draw all contours. - Choose color in BGR format, e.g., (0,255,0) for green.
- Adjust thickness to control line visibility.
Key Takeaways
Use cv2.findContours on a binary image to get contours before drawing.
Draw contours with cv2.drawContours by specifying image, contours, index, color, and thickness.
Convert images to grayscale and threshold before contour detection for best results.
Use contourIdx = -1 to draw all contours at once.
Remember OpenCV uses BGR color format, not RGB.