image-processing - 除了使用 OpenCV python 的 bean 之外,有没有办法可以删除图像中的其他组件?
问题描述
我一直在尝试从图像中删除除 bean 之外的所有其他组件。我尝试过使用边缘和轮廓,但我无法做到正确。 在此处输入图像描述
解决方案
如果“豆子”是黑暗区域,那么这是 Python OpenCV 中的一种方法。
- Read the input
- Threshold on the blue color
- Apply morphology close to clean it up a little
- Invert
- Find the largest contour
- Draw a white filled contour on a black background as a mask
- Use the mask to make everything in the input black except the "beans"
- Save the results
输入:
import cv2
import numpy as np
# load image
img = cv2.imread("beans.jpg")
lower =(80,70,30)
upper = (220,220,180)
# create the mask and use it to change the colors
thresh = cv2.inRange(img, lower, upper)
# apply morphology
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))
morph = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
# invert
morph = 255 - morph
# find largest contour
contours = cv2.findContours(morph, 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 white filled contour on black background as mask
mask = np.zeros_like(thresh)
cv2.drawContours(mask, [big_contour], 0, 255, -1)
# apply mask to img
result = img.copy()
result[mask==0] = (0,0,0)
# write result to disk
cv2.imwrite("beans_thresh2.png", thresh)
cv2.imwrite("beans_morph2.png", morph)
cv2.imwrite("beans_mask2.png", mask)
cv2.imwrite("beans_result2.png", result)
# display it
cv2.imshow("thresh", thresh)
cv2.imshow("morph", morph)
cv2.imshow("mask", mask)
cv2.imshow("result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()
阈值图像:
形态清洁图像:
蒙版图片:
结果图像:
推荐阅读
- scala - 如何使用代码模板的 Scala 宏/准引用?
- android - 任务“:react-native-gesture-handler:generateDebugRFile”执行失败
- artifactory - salt stack中是否有文件上传功能可以将jar上传到JFrog Artifactory?
- c++ - 如何在 Qt Creator 中禁用/删除所有断点
- nativescript - 试图用 nativescript 加速
- java - 如何从 url 下载 https 文件
- mongodb - 如何在mongodb中用java编写$substr($substr(a,1,8),1,6)
- python - Python TypeError:UMat()缺少必需的参数“范围”(位置2)
- r - 格式化考试结果以在 R 中执行 t 检验
- postgresql - 如何检查 postgresql 会话计数?