Image processing 是否有一种方法可以使用OpenCV python删除图像中除bean之外的其他组件?
我一直在尝试从图像中删除除bean之外的所有其他组件。我试过使用边缘和轮廓,但都做不好。 如果“bean”是黑暗区域,那么在Python OpenCV中有一种方法Image processing 是否有一种方法可以使用OpenCV python删除图像中除bean之外的其他组件?,image-processing,opencv-python,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
- 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
输入:
阈值图像: 形态学清理图像: 遮罩图像: 结果图像:
欢迎来到堆栈溢出。请阅读帮助中心()中的信息指南,特别是“如何提出一个好问题”和“如何创建一个最小的、可复制的示例”()。图像的哪一部分是“bean”?是圆还是圆内的暗区?
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()