Can you help me write a code for contour feature filtering in python
Sure, here's an example code for contour feature filtering in Python using OpenCV:
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()
In this code, we first load an image and convert it to grayscale. We then threshold the image to create a binary image. Next, we find contours in the binary image using OpenCV's findContours function.
We then filter the contours based on their area. In this example, we only keep contours with an area between 100 and 1000 pixels. We store the filtered contours in a list.
Finally, we draw the filtered contours on a blank image and display the result.
You can modify the code to filter contours based on other features, such as perimeter or shape.
原文地址: https://www.cveoy.top/t/topic/bnBY 著作权归作者所有。请勿转载和采集!