python-3.x - 如何计算二值图像中 Blob 的实例(白色 Blob 和黑色作为背景色)

标签 python-3.x machine-learning deep-learning computer-vision computer-science

我有一个带有白色多个白色 Blob 且背景为黑色的二值图像。我想在 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:
    • 如果它们已经具有相同的标签,我们会为其赋予相同的标签
    • 我们给它赋予与其中一个标签相同的标签,并将带有第二个标签的所有像素转换为第一个标签,因此这些组件现在是一个(因为它们通过该像素连接)

您还可以使用预定义的方法,例如 this example .

关于python-3.x - 如何计算二值图像中 Blob 的实例(白色 Blob 和黑色作为背景色),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56532750/

相关文章:

debugging - 如何可视化 TensorFlow Estimator 权重?

python - 如何教卷积神经网络对未知图像说 "no"?

python - 导入错误: You need to first `import keras` in order to use `keras_applications`

Keras自定义损失与多个输出的关系

python-3.x - Pandas:检查一列是否存在于另一列中

python - 在 pandas 中使用 lstrip 时删除多余的字符

python - 在 Python 中从头开始计算雅可比矩阵

tensorflow - 如何使用Tensorflow2.0 alpha堆叠卷积层和LSTM?

Python 模块导入 3.7

python - 在嵌套列表中查找唯一元素