【问题标题】:Delete unused shapes in OpenCV删除 OpenCV 中未使用的形状
【发布时间】:2021-04-29 01:37:46
【问题描述】:

我在 python 中使用 OpenCV 进行形状检测,螺栓和螺母。我拍照,制作二进制并检测边缘。由于灰尘和污垢,现在白色区域总是呈颗粒状。我的检测使用最大的区域作为部分,效果很好。但是如何删除由灰尘引起的数千个对象? 简而言之:我想将形状数组清除为仅最大的形状以便进一步处理。

【问题讨论】:

  • 发布示例图片的链接。从您的二进制图像中获取轮廓。然后选择最大的轮廓。然后在与您的输入相同大小的黑色背景图像上绘制一个白色填充轮廓作为蒙版。然后使用 numpy 将图像中所有蒙版中的黑色部分变黑。

标签: python opencv shapes


【解决方案1】:

根据我上面的评论,这是使用 Python/OpenCV 执行此操作的一种方法。

从您的二值图像中获取轮廓。然后选择最大的轮廓。然后在与您的输入相同大小的黑色背景图像上绘制一个白色填充轮廓作为蒙版。然后使用 numpy 将图像中所有蒙版中的黑色部分变黑。

输入:

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()

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

Mask Image(仅填充最大的轮廓):

结果:

【讨论】:

    猜你喜欢
    • 2022-09-23
    • 1970-01-01
    • 2017-03-08
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多