从 Python 中的阈值图像中去除小轮廓和噪声
Removing small contours and noises from a thresholded image in Python
在 Python 中,是否有任何方法或函数可以通过 OpenCV 去除已给定阈值图像的小轮廓?我的目标是只让矩形并很快将这些重叠的矩形分开:
如果您尝试删除的斑点与要保留的斑点相比较小,一种方法是在斑点周围绘制边界框并使用边界框的面积丢弃不需要的斑点。
cnts = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
rect_areas = []
for c in cnts:
(x, y, w, h) = cv2.boundingRect(c)
rect_areas.append(w * h)
avg_area = mean(rect_areas)
for c in cnts:
(x, y, w, h) = cv2.boundingRect(c)
cnt_area = w * h
if cnt_area < 0.5 * avg_area:
img[y:y + h, x:x + w] = 0
这里我要删除面积小于平均面积一半的斑点。您可以通过实验将此值设置为您想要的值。
我今天早上采用的另一种方法是针对相同问题补充你的方法并做出贡献,通过矩形轮廓区域的条件进行评估:
_,contours, hierarchy = cv2.findContours(closing, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
image_copy = image.copy()
for c in contours:
#Defining a condition to draw the contours, a number larger than/smaller than or between ranges
x = 5000.0
if cv2.contourArea(c) > x:
x, y, w, h = cv2.boundingRect(c)
cv2.drawContours(image_copy, [c], 0, (0,255,0), 17)
我相信必须有其他的并且比我所做的更好,以避免打印我正在寻找的确定的轮廓,以及我试图解决的一些短的轮廓
在 Python 中,是否有任何方法或函数可以通过 OpenCV 去除已给定阈值图像的小轮廓?我的目标是只让矩形并很快将这些重叠的矩形分开:
如果您尝试删除的斑点与要保留的斑点相比较小,一种方法是在斑点周围绘制边界框并使用边界框的面积丢弃不需要的斑点。
cnts = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
rect_areas = []
for c in cnts:
(x, y, w, h) = cv2.boundingRect(c)
rect_areas.append(w * h)
avg_area = mean(rect_areas)
for c in cnts:
(x, y, w, h) = cv2.boundingRect(c)
cnt_area = w * h
if cnt_area < 0.5 * avg_area:
img[y:y + h, x:x + w] = 0
这里我要删除面积小于平均面积一半的斑点。您可以通过实验将此值设置为您想要的值。
我今天早上采用的另一种方法是针对相同问题补充你的方法并做出贡献,通过矩形轮廓区域的条件进行评估:
_,contours, hierarchy = cv2.findContours(closing, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
image_copy = image.copy()
for c in contours:
#Defining a condition to draw the contours, a number larger than/smaller than or between ranges
x = 5000.0
if cv2.contourArea(c) > x:
x, y, w, h = cv2.boundingRect(c)
cv2.drawContours(image_copy, [c], 0, (0,255,0), 17)
我相信必须有其他的并且比我所做的更好,以避免打印我正在寻找的确定的轮廓,以及我试图解决的一些短的轮廓