用Python从图像中提取连通对象

17

我有一张灰度PNG图像,想从中提取所有连通组件。
有些组件具有相同的强度,但我想为每个对象分配一个唯一的标签。
这是我的图像:

enter image description here

我尝试了这段代码:

img = imread(images + 'soccer_cif' + str(i).zfill(6) + '_GT_index.png')
labeled, nr_objects = label(img)
print "Number of objects is %d " % nr_objects

但是使用此方法,我只获得了三个对象。请告诉我如何获取每个对象。


label 函数是从哪儿来的? - Janne Karila
可能的解决方案:https://dev59.com/tm435IYBdhLWcg3wohtT#5304140 - unutbu
实际上我正在使用类似的东西。标签函数来源于scipy.ndimage 但是获得了我发布的结果。 - Khushboo
2个回答

25

J.F. Sebastian展示了一种识别图像中对象的方法。 但是,这需要手动选择高斯模糊半径和阈值:

from PIL import Image
import numpy as np
from scipy import ndimage
import matplotlib.pyplot as plt

fname='index.png'
blur_radius = 1.0
threshold = 50

img = Image.open(fname).convert('L')
img = np.asarray(img)
print(img.shape)
# (160, 240)

# smooth the image (to remove small objects)
imgf = ndimage.gaussian_filter(img, blur_radius)
threshold = 50

# find connected components
labeled, nr_objects = ndimage.label(imgf > threshold) 
print("Number of objects is {}".format(nr_objects))
# Number of objects is 4 

plt.imsave('/tmp/out.png', labeled)
plt.imshow(labeled)

plt.show()

使用blur_radius = 1.0,可以找到4个对象。 使用blur_radius = 0.5,可以找到5个对象:

enter image description here


嗯,我之前没有尝试过高斯模糊。 这种方法效果更好。谢谢 :) - Khushboo

4

如果对象的边界非常清晰,并且您有一个二进制图像img,您可以避免使用高斯滤波器,只需执行以下操作:

labeled, nr_objects = ndimage.label(img)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接