可以使用 OpenCV 库来实现轮廓特征筛选和填充操作。以下是一个示例代码,其中假设有一个名为 'img' 的灰度图像,已经通过阈值化得到二值图像。代码中对轮廓进行了面积和周长筛选,并对第一个轮廓进行了灰色填充。

import cv2

# 读取二值图像
img = cv2.imread('binary_image.png', 0)

# 轮廓检测
contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# 面积和周长筛选
filtered_contours = []
for contour in contours:
    area = cv2.contourArea(contour)
    perimeter = cv2.arcLength(contour, True)
    if area > 100 and perimeter > 50:
        filtered_contours.append(contour)

# 对第一个轮廓进行填充
if len(filtered_contours) > 0:
    cv2.drawContours(img, [filtered_contours[0]], 0, 127, -1)

# 显示结果
cv2.imshow('Result', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

需要注意的是,OpenCV 中的轮廓检测函数会返回轮廓的列表和层级关系,因此需要使用索引来获取指定的轮廓。此外,填充操作可以通过 cv2.drawContours 函数实现,其中的 thickness 参数为负数表示对轮廓内部进行填充。

Python OpenCV 轮廓特征筛选和填充示例

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

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