python - 注册 : Copy blob based on the area of the blob size

标签 python opencv opencv-contour image-thresholding

目标:在另一个蒙版图像中复制较大的 Blob

我有一个带有 Blob 的阈值图像,如图所示:

enter image description here

我怎样才能将较大的 Blob 复制到蒙版图像中并省略一个像素的 Blob ?

enter image description here

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

import numpy as np
import cv2

ref_img = cv2.imread('threshold.jpg', 0)
thresh = np.copy(ref_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:
   (x,y),radius = cv2.minEnclosingCircle(c)
   area = cv2.contourArea(c)
   if int(area) < 1:
      cv2.circle(mask, (int(x), int(y)), int(radius), (255, 255, 255), -1)

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

注:使用 OpenCV 2.4.x

最佳答案

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

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)

关于python - 注册 : Copy blob based on the area of the blob size,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53449821/

相关文章:

python - 如何检测字符串后缀并从列表中删除这些后缀元素? - Python

python - 在 Python 中获取 Oauth 访问 token

c++ - 如何访问 cv::canny 阈值的梯度幅值图像

c++ - 调试 Opencv Android 应用程序

python - 出现错误 “FindContours support only 8uC1 and 32sC1 images in function cvStartFindContours”

python - 获取嵌套列表中特定字符串的索引信息?在Python 3中

python - 如何在 python (Windows) 上的 openCV dnn 模块上使用 GPU 加速?

python - 使用 OpenCV Python 使用模糊水平集进行视网膜流体分割

python - 使用openCV-python将两个轮廓分割成两个相同大小的不同图像

python - 使用 cifar 100 的图像分类器,训练精度没有增加