OpenCV Image Contour Detection

Contour detection is an important task in image processing, used to extract the boundaries of objects in an image.

OpenCV provides powerful contour detection capabilities, which can be used for applications such as object recognition, shape analysis, and target tracking. The following is a detailed description of OpenCV image contour detection.

Basic Concepts of Contour Detection

  • Contour:The boundary of an object in an image, composed of a series of points.

  • Contour hierarchy:The nesting relationship between contours, for example, whether one contour contains another.

  • Contour features:The area, perimeter, bounding rectangle, minimum enclosing rectangle, minimum enclosing circle, etc., of a contour.

Common Functions for Contour Detection

Function Name Function Description
cv2.findContours() Find contours in an image.
cv2.drawContours() Draw contours on an image.
cv2.contourArea() Calculate the area of a contour.
cv2.arcLength() Calculate the perimeter or arc length of a contour.
cv2.boundingRect() Calculate the bounding rectangle of a contour.
cv2.minAreaRect() Calculate the minimum enclosing rectangle of a contour.
cv2.minEnclosingCircle() Calculate the minimum enclosing circle of a contour.
cv2.approxPolyDP() Perform polygon approximation on a contour.

Detailed Function Descriptions

1. cv2.findContours()

Function Description:
This function is used to find contours in a binary image. A contour is a curve of continuous points with the same color or intensity in an image.

Function Definition:

contours, hierarchy = cv2.findContours(image, mode, method[, contours[, hierarchy[, offset]]])

Parameter Description:

  • image: The input binary image (usually an image after thresholding or edge detection).
  • mode: Contour retrieval mode, commonly used ones are:
    • cv2.RETR_EXTERNAL: Only detect the outermost contours.
    • cv2.RETR_LIST: Detect all contours, but do not establish hierarchy.
    • cv2.RETR_TREE: Detect all contours and establish a complete hierarchy.
  • method: Contour approximation method, commonly used ones are:
    • cv2.CHAIN_APPROX_NONE: Store all contour points.
    • cv2.CHAIN_APPROX_SIMPLE: Compress horizontal, vertical, and diagonal segments, retaining only endpoints.
  • contours: The output contour list, where each contour is a set of points.
  • hierarchy: The output hierarchy information.
  • offset: Optional parameter, the offset of contour points.

Return Value:

  • contours: The list of detected contours.
  • hierarchy: The hierarchy information of the contours.

Example

import cv2
import numpy as np

# Read the image and convert it to grayscale
image = cv2.imread('image.png', 0)
# Binarization processing
_, binary = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)
# Find contours
contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

2. cv2.drawContours()

Function Description:
This function is used to draw detected contours on an image.

Function Definition:

cv2.drawContours(image, contours, contourIdx, color[, thickness[, lineType[, hierarchy[, maxLevel[, offset]]]]])

Parameter Description:

  • image: The image on which to draw contours.
  • contours: The list of contours.
  • contourIdx: The index of the contour to draw; if negative, draw all contours.
  • color: The color of the contours.
  • thickness: The thickness of the contour lines; if negative, fill the interior of the contours.
  • lineType: Line type.
  • hierarchy: The hierarchy information of the contours.
  • maxLevel: The maximum hierarchy depth to draw.
  • offset: The offset of contour points.

Return Value:
No return value; contours are drawn directly on the input image.

Example

# Create a blank image
output = np.zeros_like(image)
# Draw all contours
cv2.drawContours(output, contours, -1, (255, 0, 0), 2)
cv2.imshow('Contours', output)
cv2.waitKey(0)

3. cv2.contourArea()

Function Description:
This function is used to calculate the area of a contour.

Function Definition:

area = cv2.contourArea(contour[, oriented])

Parameter Description:

  • contour: The input set of contour points.
  • oriented: Optional parameter; if True, returns a signed area.

Return Value:
The area of the contour.

Example

for contour in contours:
    area = cv2.contourArea(contour)
    print(f"Contour area: {area}")

4. cv2.arcLength()

Function Description:
This function is used to calculate the perimeter or arc length of a contour.

Function Definition:

length = cv2.arcLength(curve, closed)

Parameter Description:

  • curve: The input set of contour points.
  • closed: A boolean value indicating whether the contour is closed.

Return Value:
The perimeter or arc length of the contour.

Example

for contour in contours:
    perimeter = cv2.arcLength(contour, True)
    print(f"Contour perimeter: {perimeter}")

5. cv2.boundingRect()

Function Description:
This function is used to calculate the bounding rectangle of a contour.

Function Definition:

x, y, w, h = cv2.boundingRect(points)

Parameter Description:

  • points: The input set of contour points.

Return Value:
The top-left coordinates of the bounding rectangle(x, y)and widthw, heighth。

Example

for contour in contours:
    x, y, w, h = cv2.boundingRect(contour)
    cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow('Bounding Rectangles', image)
cv2.waitKey(0)

6. cv2.minAreaRect()

Function Description:
This function is used to calculate the minimum enclosing rectangle (rotated rectangle) of a contour.

Function Definition:

rect = cv2.minAreaRect(points)

Parameter Description:

  • points: The input set of contour points.

Return Value:
Returns a rotated rectangle containing the center point(x, y), width, height, and rotation angle.

Example

for contour in contours:
    rect = cv2.minAreaRect(contour)
    box = cv2.boxPoints(rect)
    box = np.int0(box)
    cv2.drawContours(image, [box], 0, (0, 0, 255), 2)
cv2.imshow('Min Area Rectangles', image)
cv2.waitKey(0)

7. cv2.minEnclosingCircle()

Function Description:
This function is used to calculate the minimum enclosing circle of a contour.

Function Definition:

(center, radius) = cv2.minEnclosingCircle(points)

Parameter Description:

  • points: The input set of contour points.

Return Value:
Returns the center of the circle(x, y)and radiusradius。

Example

for contour in contours:
    (x, y), radius = cv2.minEnclosingCircle(contour)
    center = (int(x), int(y))
    radius = int(radius)
    cv2.circle(image, center, radius, (255, 0, 0), 2)
cv2.imshow('Min Enclosing Circles', image)
cv2.waitKey(0)

8. cv2.approxPolyDP()

Function Description:
This function is used to perform polygon approximation on a contour.

Function Definition:

approx = cv2.approxPolyDP(curve, epsilon, closed)

Parameter Description:

  • curve: The input set of contour points.
  • epsilon: Approximation accuracy; the smaller the value, the more precise the approximation.
  • closed: A boolean value indicating whether the contour is closed.

Return Value:
Returns the approximated polygon point set.

Example

for contour in contours:
    epsilon = 0.01 * cv2.arcLength(contour, True)
    approx = cv2.approxPolyDP(contour, epsilon, True)
    cv2.drawContours(image, [approx], 0, (0, 255, 0), 2)
cv2.imshow('Approx Polygons', image)
cv2.waitKey(0)

Applications of Contour Detection

  • Object recognition: Contour detection can be used to recognize objects in an image, such as detecting circles, rectangles, etc.
  • Shape analysis: By calculating the features of contours (such as area, perimeter, bounding rectangle, etc.), the shape of objects can be analyzed.
  • Target tracking: In videos, contour detection can be used to track moving targets.
  • Image segmentation: Contour detection can be used to segment objects in an image.

OpenCV provides powerful contour detection capabilities, which can be used to extract the boundaries of objects in an image and calculate contour features.

The following are the main steps and functions of contour detection:

StepFunctionDescription
Image preprocessingcv2.cvtColor()Convert the image to grayscale.
Binarization processingcv2.threshold()Convert the grayscale image to a binary image.
Find contourscv2.findContours()Find contours in the image.
Draw contourscv2.drawContours()Draw the detected contours.
Calculate contour areacv2.contourArea()Calculate the area of the contour.
Calculate contour perimetercv2.arcLength()Calculate the perimeter of the contour.
Calculate bounding rectanglecv2.boundingRect()Calculate the bounding rectangle of the contour.
Calculate minimum enclosing rectanglecv2.minAreaRect()Calculate the minimum enclosing rectangle of the contour.
Calculate minimum enclosing circlecv2.minEnclosingCircle()Calculate the minimum enclosing circle of the contour.
Polygon approximationcv2.approxPolyDP()Perform polygon approximation on the contour.

The following is a complete example code for contour detection:

Example

import cv2

# Read the image
image = cv2.imread("path/to/image")

# Convert to grayscale image
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Binarization processing
ret, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

# Find contours
contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

# Draw contours
cv2.drawContours(image, contours, -1, (0, 255, 0), 2)

# Display the result
cv2.imshow("Contours", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Other Extensions