首页 > 解决方案 > 除了使用 OpenCV python 的 bean 之外,有没有办法可以删除图像中的其他组件?

问题描述

我一直在尝试从图像中删除除 bean 之外的所有其他组件。我尝试过使用边缘和轮廓,但我无法做到正确。 在此处输入图像描述

标签: image-processingopencv-python

解决方案


如果“豆子”是黑暗区域,那么这是 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()

阈值图像:

在此处输入图像描述

形态清洁图像:

在此处输入图像描述

蒙版图片:

在此处输入图像描述

结果图像:

在此处输入图像描述


推荐阅读