如何使用python删除位图图像蒙版中的小岛补丁?

时间:2019-02-01 12:23:05

标签: python opencv image-processing

我是图像处理的新手,正在从事一个项目,在该项目中,我需要将树叶的图像与背景分开,作为项目的一部分。我可以使用OpenCV创建遮罩,但是应该删除一些补丁。

您可以看到下面的图片得到了我的意思有清楚的认识:

enter image description here

2 个答案:

答案 0 :(得分:2)

在该文档的page上,使用opening表示您的小观点,并使用Morphological gradient填充图像的中间部分。

答案 1 :(得分:0)

尝试一下:

import cv2
import numpy as np 

input = cv2.imread('source.png')
gray = cv2.cvtColor(input, cv2.COLOR_BGR2GRAY)

#find all contours
img = cv2.pyrDown(gray)
_, threshed = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY)
contours,_ = cv2.findContours(threshed, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

#find maximum contour and draw   
cmax = max(contours, key = cv2.contourArea) 
epsilon = 0.002 * cv2.arcLength(cmax, True)
approx = cv2.approxPolyDP(cmax, epsilon, True)
cv2.drawContours(input, [approx], -1, (0, 255, 0), 3)

cv2.imshow("Contour", input)

width, height = gray.shape

#fill maximum contour and draw   
img = np.zeros( [width, height, 3],dtype=np.uint8 )
cv2.fillPoly(img, pts =[cmax], color=(255,255,255))

cv2.imshow("Filtered", img)

cv2.waitKey(0)
cv2.destroyAllWindows()

算法

  1. FindContours方法。您可以调整epsilon参数。
  2. 充分利用国家-这就是你的叶子。
  3. 填写此最大数量并绘制。现在,您可以对其进行平滑处理或执行其他任何形态学操作。

结果

enter image description here