Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

OpenCV Image Contour Detection

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 functionality that can be used for object recognition, shape analysis, target tracking, and other applications. The following is a detailed description of OpenCV image contour detection.

Basic Concepts of Contour Detection

Common Functions for Contour Detection

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

Detailed Function Description

1. cv2.findContours()

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

Function definition:



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

Parameter Description:

- `cv2.RETR_EXTERNAL`: Detect only the outermost contours. - `cv2.RETR_LIST`: Detect all contours, but do not establish a hierarchical relationship. - `cv2.RETR_TREE`: Detect all contours and establish a complete hierarchical structure. - `cv2.CHAIN_APPROX_NONE`: Store all the contour points. - `cv2.CHAIN_APPROX_SIMPLE`: Compress horizontal, vertical, and diagonal line segments, keeping only the endpoints.

Return Value:

Example

import

cv2

import

numpy

as

np

Read the image and convert it to grayscale

image

=

cv2.

imread

(

'image.png'

,

0

)

Binarization

_

,

binary

=

cv2.

threshold

(

image

,

127

,

255

,

cv2.

THRESH_BINARY

)

Finding contours

contours

,

hierarchy

=

cv2.

findContours

(

binary

,

cv2.

RETR_TREE

,

cv2.

CHAIN_APPROX_SIMPLE

)

2. cv2.drawContours()

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:

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()

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

Function definition:



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

Parameter Description:

Return Value:
The area of the contour.

Example

for

contour

in

contours:

    area

=

cv2.

contourArea

(

contour

)

   

print

(

f

"Contour area: {area}"

)

4. cv2.arcLength()

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

Function definition:



length = cv2.arcLength(curve, closed)

Parameter Description:

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()

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

Function definition:



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

Parameter Description:

Return Value:
The top-left coordinate of the bounding rectangle (x, y) and width wand height h。

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()

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

Function definition:



rect = cv2.minAreaRect(points)

Parameter Description:

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()

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

Function definition:



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

Parameter Description:

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

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()

Description:
This function is used to perform polygonal approximation of a contour.

Function definition:



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

Parameter Description:

Return Value:
Returns the approximated set of polygon points.

Example

for

contour

in

contours:

    epsilon

=

0.01

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

OpenCV provides powerful contour detection functionality that can be used to extract the boundaries of objects in an image and compute contour features.

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

Step function Description
Image preprocessing cv2.cvtColor() Convert the image to grayscale.
Binarization cv2.threshold() Convert the grayscale image to a binary image.
Finding contours cv2.findContours() Find the contours in the image.
Draw the outline cv2.drawContours() Draw the detected contours.
Compute the contour area cv2.contourArea() Compute the area of the contour.
Compute the contour perimeter cv2.arcLength() Compute the perimeter of the contour.
Compute the bounding rectangle cv2.boundingRect() Compute the bounding rectangle of the contour.
Compute the minimum enclosing rectangle cv2.minAreaRect() Compute the minimum enclosing rectangle of the contour.
Compute the minimum enclosing circle cv2.minEnclosingCircle() Compute the minimum enclosing circle of the contour.
Polygonal approximation cv2.approxPolyDP() Perform polygonal approximation of the contour.

The following is a complete contour detection example code:

Example

import

cv2

Read an image

image

=

cv2.

imread

(

"path/to/image"

)

Convert to grayscale

gray

=

cv2.

cvtColor

(

image

,

cv2.

COLOR_BGR2GRAY

)

Binarization

ret

,

binary

=

cv2.

threshold

(

gray

,

127

,

255

,

cv2.

THRESH_BINARY

)

Finding contours

contours

,

hierarchy

=

cv2.

findContours

(

binary

,

cv2.

RETR_TREE

,

cv2.

CHAIN_APPROX_SIMPLE

)

Draw the outline

cv2.

drawContours

(

image

,

contours

,

1

,

(

0

,

255

,

0

)

,

2

)

Display Results

cv2.

imshow

(

"Contours"

,

image

)

cv2.

waitKey

(

0

)

cv2.

destroyAllWindows

(

)