gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:48:12 27 4
gpt4 key购买 nike

我有一个带有白色多个白色 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com