Skip to content
OpenCV

Contours

Find, draw, and measure contours.

By EZ4Code Team
contoursshape

Code

import cv2

img = cv2.imread("shapes.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

# Find external contours
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL,
                                       cv2.CHAIN_APPROX_SIMPLE)

output = img.copy()
for c in contours:
    area = cv2.contourArea(c)
    if area < 100:
        continue
    x, y, w, h = cv2.boundingRect(c)
    cv2.rectangle(output, (x, y), (x + w, y + h), (0, 255, 0), 2)
    perimeter = cv2.arcLength(c, True)
    approx = cv2.approxPolyDP(c, 0.04 * perimeter, True)
    cv2.drawContours(output, [c], -1, (0, 0, 255), 2)

cv2.imwrite("contours.jpg", output)
print(len(contours))

Explanation

findContours extracts boundary points from a binary image, with RETR_EXTERNAL keeping only outer contours. contourArea, arcLength, and boundingRect compute geometric measurements, while approxPolyDP simplifies a contour to its corner vertices. drawContours renders the points back onto an image.

More OpenCV Snippets