如果你想要移除的斑点相比你想保留的斑点较小,一种方法是在斑点周围绘制边界框,并使用边界框的面积丢弃不需要的斑点。
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)