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
-
Contour: The boundary of an object in an image, consisting of a series of points.
-
Contour hierarchy: The nesting relationship between contours, such as whether one contour contains another.
-
Contour features: The area, perimeter, bounding rectangle, minimum enclosing rectangle, minimum enclosing circle, and so on of a contour.
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:
image: The input binary image (usually an image after thresholding or edge detection).mode: The contour retrieval mode, commonly used ones include: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.
method: The contour approximation method, commonly used ones include:cv2.CHAIN_APPROX_NONE: Store all the contour points.cv2.CHAIN_APPROX_SIMPLE: Compress horizontal, vertical, and diagonal line segments, keeping only the endpoints.
contours: The output list of contours, where each contour is a set of points.hierarchy: The output hierarchy information.offset: An optional parameter, the offset of the 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
_
,
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:
image: The image on which to draw the contours.contours: The list of contours.contourIdx: The index of the contour to draw; if negative, all contours are drawn.color: The color of the contours.thickness: The thickness of the contour lines; if negative, the interior of the contours is filled.lineType: The line type.hierarchy: The hierarchy information of the contours.maxLevel: The maximum hierarchy depth to draw.offset: The offset of the 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()
Description:
This function is used to compute the area of a contour.
Function definition:
area = cv2.contourArea(contour[, oriented])
Parameter Description:
contour: The input set of contour points.oriented: An optional parameter; if True, returns a signed area.
Return Value:
The area of the contour.
Example
for
contour
in
contours:
area
=
cv2.
contourArea
(
contour
)
(
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:
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
)
(
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:
points: The input set of contour points.
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:
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()
Description:
This function is used to compute 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 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:
curve: The input set of contour points.epsilon: The 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 set of polygon points.
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 identify objects in an image, such as detecting circles, rectangles, and so on.
- Shape analysis: By computing contour features (such as area, perimeter, bounding rectangle, etc.), the shape of an object 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 from an image.
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
(
)