1.按短边筛选
原始轮廓图:
import cv2
import numpy as np# 读取轮廓图
contour_image = cv2.imread('..\\IMGS\\pp_edge.png', cv2.IMREAD_GRAYSCALE)# 使用cv2.findContours()函数获取所有轮廓
contours, _ = cv2.findContours(contour_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)# 设定的直径阈值
threshold_diameter = 25.0# 遍历每个轮廓
new_image = np.zeros_like(contour_image)
for contour in contours:rect = cv2.minAreaRect(contour) # 获取最小外接矩形diameter = rect[1][0] if rect[1][0] <= rect[1][1] else rect[1][1] # 计算轮廓的最短尺寸,并获取直径# 如果轮廓的直径小于设定的阈值,则忽略该轮廓if diameter >= threshold_diameter:cv2.drawContours(new_image, [contour], -1, (255, 255, 255))print(diameter, end=', ')cv2.imshow('Filtered Contours', new_image) # 绘制保留的轮廓
cv2.waitKey(0)
cv2.destroyAllWindows()
输出结果以及与原图对比:
2.按长边筛选
import cv2
import numpy as np# 读取轮廓图
contour_image = cv2.imread('..\\IMGS\\pp_edge2.png', cv2.IMREAD_GRAYSCALE)# 使用cv2.findContours()函数获取所有轮廓
contours, _ = cv2.findContours(contour_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)# 设定的直径阈值
threshold_diameter = 25.0# 遍历每个轮廓
new_image = np.zeros_like(contour_image)
for contour in contours:diameter = cv2.minEnclosingCircle(contour)[1] * 2 # cv2.minEnclosingCircle():计算一个轮廓的最小包围圆,返回值是圆心坐标和半径# 如果轮廓的直径小于设定的阈值,则忽略该轮廓if diameter >= threshold_diameter:cv2.drawContours(new_image, [contour], -1, (255, 255, 255))print(diameter, end=', ')cv2.imshow('Filtered Contours', new_image) # 绘制保留的轮廓
cv2.waitKey(0)
cv2.destroyAllWindows()
结果图: