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 functions, which can be used for object recognition, shape analysis, target tracking, and other applications. Below is a detailed explanation 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 nested relationship between contours, such as whether one contour contains another.
* **Contour Features:** The area, perimeter, bounding rectangle, minimum enclosing rectangle, minimum enclosing circle, etc. of a contour.
### Commonly Used Contour Detection Functions
| Function Name | 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()` | Approximate a contour with a polygon |
## Function Detailed Description
### 1. `cv2.findContours()`
**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`: Input binary image (usually an image after thresholding or edge detection).
* `mode`: Contour retrieval mode, commonly used ones include:
* `cv2.RETR_EXTERNAL`: Retrieve only the outermost contours.
* `cv2.RETR_LIST`: Retrieve all contours without establishing hierarchy.
* `cv2.RETR_TREE`: Retrieve all contours and establish a complete hierarchy.
* `method`: Contour approximation method, commonly used ones include:
* `cv2.CHAIN_APPROX_NONE`: Store all contour points.
* `cv2.CHAIN_APPROX_SIMPLE`: Compress horizontal, vertical, and diagonal segments, keeping only the endpoints.
* `contours`: Output list of contours, each contour is a point set.
* `hierarchy`: Output hierarchy information.
* `offset`: Optional parameter, offset of contour points.
**Return Value**:
* `contours`: List of detected contours.
* `hierarchy`: Hierarchy information of contours.
## Example
import cv2
import numpy as np
# Read Image and Convert to Grayscale
image = cv2.imread('image.png',0)
# Binarization
_, 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()`
**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`: Image on which to draw contours.
* `contours`: List of contours.
* `contourIdx`: Index of contour to draw, if negative, draw all contours.
* `color`: Color of the contour.
* `thickness`: Thickness of the contour line, if negative, fill the interior of the contour.
* `lineType`: Line type.
* `hierarchy`: Hierarchy information of contours.
* `maxLevel`: Maximum hierarchy depth to draw.
* `offset`: Offset of contour points.
**Return Value**:
No return value, draws contours 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 calculate the area of a contour.
**Function Definition**:
area = cv2.contourArea(contour[, oriented])
**Parameter Description**:
* `contour`: Input contour point set.
* `oriented`: Optional parameter, if True, returns 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()`
**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`: Input contour point set.
* `closed`: 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()`
**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`: Input contour point set.
**Return Value**:
The top-left corner coordinates `(x, y)` of the bounding rectangle and width `w`, 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 calculate the minimum enclosing rectangle (rotated rectangle) of a contour.
**Function Definition**:
rect = cv2.minAreaRect(points)
**Parameter Description**:
* `points`: Input contour point set.
**Return Value**:
Returns a rotated rectangle containing 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,,0,(0,0,255),2)
cv2.imshow('Min Area Rectangles', image)
cv2.waitKey(0)
### 7. `cv2.minEnclosingCircle()`
**Description**:
This function is used to calculate the minimum enclosing circle of a contour.
**Function Definition**:
(center, radius) = cv2.minEnclosingCircle(points)
**Parameter Description**:
* `points`: Input contour point set.
**Return Value**:
Returns the center `(x, y)` and 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 approximate a contour with a polygon.
**Function Definition**:
approx = cv2.approxPolyDP(curve, epsilon, closed)
**Parameter Description**:
* `curve`: Input contour point set.
* `epsilon`: Approximation accuracy, smaller value means more accurate approximation.
* `closed`: 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(cont
YouTip