Python 3.x 如何计算二进制图像中水滴的实例(白色水滴和黑色作为背景色)

Python 3.x 如何计算二进制图像中水滴的实例(白色水滴和黑色作为背景色),python-3.x,machine-learning,deep-learning,computer-vision,computer-science,Python 3.x,Machine Learning,Deep Learning,Computer Vision,Computer Science,我有一个带有白色多个白色斑点的二值图像,背景是黑色。我想用python计算这个图像中的blob数 我从cv和skimage.measure.find_contours()中尝试了python函数cv.findContours,但没有给出所需的结果 img = cv2.imread('test.png', 0) con = measure.find_contours(img, 0.8) fig, ax = plt.subplots() ax.imshow(img, interpolation='

我有一个带有白色多个白色斑点的二值图像,背景是黑色。我想用python计算这个图像中的blob数

我从cv和skimage.measure.find_contours()中尝试了python函数cv.findContours,但没有给出所需的结果

img = cv2.imread('test.png', 0)
con = measure.find_contours(img, 0.8)

fig, ax = plt.subplots()
ax.imshow(img, interpolation='nearest', cmap=plt.cm.gray)

for n, contour in enumerate(con):
    ax.plot(contour[:, 1], contour[:, 0], linewidth=2)

ax.axis('image')
ax.set_xticks([])
ax.set_yticks([])
plt.show()

# Trying to save image with contours but failed.

cv2.imwrite('contour.png', con)

# No idea how to count instances of a blob in a binary image

您可以使用一个计算连接组件数量的函数。有实现的选项,您可以轻松编写自己的选项。下面是一个示例代码:

def connected_components(image):
    # list of tags we have used 
    tags = []
    # current  tag (remember 1 and 0 are already in image so start from 2)
    tag = 2
    # counter
    cntr = 0
    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            if image[i, j] != 0:
                if i != 0 and j != 0 and image[i, j-1] != 0 and image[i-1, j] != 0 and image[i-1, j] != image[i, j-1]:
                    image[i, j] = image[i, j - 1]
                    tags.remove(image[i - 1, j])
                    cntr -= 1
                    image[image == image[i - 1, j]] = image[i, j]
                elif i != 0 and image[i-1, j] != 0:
                    image[i, j] = image[i-1, j]
                elif j != 0 and image[i, j-1] != 0:
                    image[i, j] = image[i, j-1]
                else:
                    image[i, j] = tag
                    tags.append(tag)
                    tag += 1
                    cntr += 1
    return image, tags, cntr
这段代码的作用:我们在每个像素上移动,如果它是一个具有1个值的新像素:

  • 如果其左侧或右侧没有像素也为1,我们将给它一个新标记
  • 如果其左侧或上方的像素也为1,则我们将为其提供与中相同的标记
  • 如果其左侧和上方的像素也为1:
    • 如果他们已经有相同的标签,我们会给他们相同的标签
    • 我们给它与其中一个相同的标记,并将所有带有第二个标记的像素转换为第一个标记,因此这些组件现在是一个(因为它们由该像素连接)

您也可以使用预定义的方法,如。

谢谢您的回答,但请再说一遍,我如何计算“新”实例?很抱歉误解了您的问题。我更新了我的答案。希望这个有帮助。