删除OpenCV中未使用的形状

2024-05-20 00:04:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经用python中的OpenCV进行了形状检测,螺栓和螺母。我拍了一张照片,做了二值化,然后检测边缘。现在,由于灰尘和污垢,白色区域总是颗粒状的。我的检测使用最大的区域作为零件,这非常有效。但我如何才能删除由灰尘造成的数千个对象? 简言之:我想将数组中的形状清除为最大的形状,以便进一步处理


Tags: 对象区域数组opencv照片边缘形状灰尘
1条回答
网友
1楼 · 发布于 2024-05-20 00:04:35

根据我上面使用Python/OpenCV的评论,这里有一种方法可以做到这一点

从你的二值图像得到轮廓。然后选择最大的轮廓。然后在黑色背景图像上绘制一个白色填充轮廓,其大小与您输入的掩码大小相同。然后使用numpy将图像中遮罩中黑色的所有内容变黑

输入:

enter image description here

import cv2
import numpy as np

# load image
img = cv2.imread("coke_bottle2.png")
hh, ww = img.shape[:2]

# convert to gray
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

# threshold using inRange
thresh = cv2.threshold(gray, 50, 255, cv2.THRESH_BINARY)[1]

# apply morphology closing to fill black holes and smooth outline
# could use opening to remove white spots, but we will use contours
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (25,25))
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)

# get the largest contour
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
big_contour = max(contours, key=cv2.contourArea)

# draw largest contour as white filled on black background as mask
mask = np.zeros((hh,ww), dtype=np.uint8)
cv2.drawContours(mask, [big_contour], 0, 255, -1)

# use mask to black all but largest contour
result = img.copy()
result[mask==0] = (0,0,0)

# write result to disk
cv2.imwrite("coke_bottle2_threshold.png", thresh)
cv2.imwrite("coke_bottle2_mask.png", mask)
cv2.imwrite("coke_bottle2_background_removed.jpg", result)

# display it
cv2.imshow("thresh", thresh)
cv2.imshow("mask", mask)
cv2.imshow("result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

阈值图像(包含小的无关白色区域):

enter image description here

遮罩图像(仅最大填充轮廓):

enter image description here

结果:

enter image description here

相关问题 更多 >