程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了删除 OpenCV 中未使用的形状大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决删除 OpenCV 中未使用的形状?

开发过程中遇到删除 OpenCV 中未使用的形状的问题如何解决?下面主要结合日常开发的经验,给出你关于删除 OpenCV 中未使用的形状的解决方法建议,希望对你解决删除 OpenCV 中未使用的形状有所启发或帮助;

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

解决方法

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

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

输入:

删除 OpenCV 中未使用的形状

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],-1)

# use mask to black all but largest contour
result = img.copy()
result[R_689_11845@ask==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()

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

删除 OpenCV 中未使用的形状

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

删除 OpenCV 中未使用的形状

结果:

删除 OpenCV 中未使用的形状

大佬总结

以上是大佬教程为你收集整理的删除 OpenCV 中未使用的形状全部内容,希望文章能够帮你解决删除 OpenCV 中未使用的形状所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。