Reg:根据Blob大小的区域复制Blob

时间:2018-11-23 16:05:44

标签: python opencv opencv-contour image-thresholding

目标:将较大的斑点复制到另一个蒙版图像中

我有一个带有斑点的阈值图像,如下所示:

enter image description here

如何将较大的斑点复制到蒙版图像中,而忽略一个像素的斑点?

enter image description here

我的代码(但是我没有得到想要的结果):

=if(countifs('Login response'!$D:$D,C$1,'Login response'!$B:$B,$A3)>0,TRUE,FALSE)

注意:使用OpenCV 2.4.x

1 个答案:

答案 0 :(得分:1)

这是您可以用来实现目标的方法之一。在代码的注释中提供了解释

import numpy as np
import cv2

ref_img = cv2.imread('threshold.jpg', 0)


img, cnts,_ = cv2.findContours(ref_img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
mask = np.zeros(ref_img.shape, dtype="uint8")
for c in cnts:
   # Get the bounding rect surrounding your blobs
   x,y,w,h = cv2.boundingRect(c) 

   # Calculating the area of the rect is similar to the area of the blob minus the complexity
   area = w*h

   # For box area bigger than one, copy the information from the source image to the mask. 
   # Since the bounding box contains all the relevant information, just copy the entire box to the mask.
   if int(area) > 1 :
    mask[y:y+h,x:x+w] = ref_img[y:y+h,x:x+w]




cv2.imshow('img', mask)
cv2.waitKey(0)