This code provides a comprehensive guide on contour feature filtering in Python using OpenCV. It demonstrates filtering contours based on area, but you can easily adapt the code for other features like perimeter or shape.

import cv2
import numpy as np

# Load image
img = cv2.imread('contours.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Threshold image
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)

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

# Filter contours based on area
min_area = 100
max_area = 1000
filtered_contours = []
for cnt in contours:
    area = cv2.contourArea(cnt)
    if area > min_area and area < max_area:
        filtered_contours.append(cnt)

# Draw filtered contours
img_contours = np.zeros(img.shape, dtype=np.uint8)
cv2.drawContours(img_contours, filtered_contours, -1, (0, 255, 0), 2)

# Display result
cv2.imshow('Filtered Contours', img_contours)
cv2.waitKey(0)
cv2.destroyAllWindows()

Explanation:

  1. Load and Convert Image: The code starts by loading an image and converting it to grayscale for easier processing.
  2. Thresholding: It then applies a thresholding technique to create a binary image where pixels are either black or white.
  3. Contour Detection: The cv2.findContours function is used to identify contours in the binary image.
  4. Area-Based Filtering: The code filters contours based on their area, keeping only those between a defined minimum and maximum area.
  5. Drawing Filtered Contours: The filtered contours are drawn onto a blank image for visualization.
  6. Display Results: The resulting image with the filtered contours is displayed.

Key Concepts:

  • Contours: Contours represent the boundaries of shapes or regions in an image.
  • Thresholding: Thresholding converts a grayscale image into a binary image by setting a threshold value.
  • Area Calculation: The cv2.contourArea() function calculates the area enclosed by a contour.

Adapting the Code:

You can modify the code to filter contours based on other features by adding additional filtering criteria within the for loop. For example:

  • Perimeter: Use cv2.arcLength(cnt, True) to calculate the perimeter of a contour.
  • Shape: Employ functions like cv2.approxPolyDP() to approximate the shape of a contour and check its number of sides or other properties.

This code provides a strong foundation for advanced image processing tasks involving contour analysis and feature extraction.

Python OpenCV: Contour Feature Filtering for Image Processing

原文地址: https://www.cveoy.top/t/topic/mQdC 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录