【问题标题】:Extracting connected objects from an image in Python在 Python 中从图像中提取连接的对象
【发布时间】:2013-05-31 23:45:14
【问题描述】:

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

我试过这段代码:

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函数从何而来?
  • 可能的解决方案:stackoverflow.com/a/5304140/190597
  • 我实际上正在使用类似的东西。标签函数来自 scipy.ndimage 但是得到了我发布的结果

标签: python image scipy


【解决方案1】:

J.F. Sebastian shows a way 识别图像中的对象。它需要手动选择高斯模糊半径和阈值,但是:

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个对象:

【讨论】:

  • 嗯,我之前没有尝试过高斯模糊。这种方法效果更好。谢谢:)
【解决方案2】:

如果物体的边界是完全清晰的并且你在img中有一个二值图像,你可以避免高斯滤波,只做这行:

labeled, nr_objects = ndimage.label(img)

【讨论】:

    猜你喜欢
    • 2013-04-13
    • 2019-02-02
    • 2019-02-17
    • 2019-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多