【问题标题】:Save individual segments from image segmentation从图像分割中保存单个片段
【发布时间】:2019-05-18 06:40:59
【问题描述】:

我一直在使用 skimage.segmentation 模块来查找图像中的连续片段。 例如,

细分得很好

我希望能够单独查看原始图像的不同区域(这样上面的图像会产生 6 个大致矩形的子图像)。我在这方面取得了一定程度的成功,但这很困难。我可以使用任何预先存在的模块来完成此操作吗?

如果没有,我们将不胜感激高级算法建议。

到目前为止的方法:

image_slic = seg.slic(image, n_segments=6)
borders = seg.find_boundaries(image_slic)
sub_images = []
new_seg = []
for every row of borders:
     new_seg.append([])
    for every pixel in every row:
         if (pixel is not a border and is not already processed):
              new_seg[-1].append(pixel)
              Mark pixel as processed
         elif (pixel is a border and is not already processed):
              break
    if (on the first pixel of a row OR the first unprocessed pixel):
         sub_images.append(new_seg)
         new_seg = []

使用这种方法,我可以从示例图像中生成与左侧接壤的四个区域,而不会出错。虽然上面的伪代码中没有显示它,但我还在用透明像素填充片段以保持它们的形状。这种额外的考虑使得查找右侧子图像变得更加困难。

【问题讨论】:

    标签: python image-segmentation scikit-image python-imageio


    【解决方案1】:

    这可以通过 NumPy 的boolean indexing 轻松完成:

    import numpy as np
    from skimage import io, segmentation
    import matplotlib.pyplot as plt
    
    n_segments = 6
    fig_width = 2.5*n_segments
    
    img = io.imread('https://i.imgur.com/G44JEG7.png')
    segments = segmentation.slic(img, n_segments=n_segments)
    
    fig, ax = plt.subplots(1, n_segments)
    fig.set_figwidth(fig_width)
    
    for index in np.unique(segments):
        segment = img.copy()
        segment[segments!=index] = 0
        ax[index].imshow(segment)
        ax[index].set(title=f'Segment {index}')
        ax[index].set_axis_off()
    
    plt.show(fig)
    

    您可以像这样使用 NumPy 的 where 函数获得相同的结果:

    for index in np.unique(segments):
        segment = np.where(np.expand_dims(segments, axis=-1)==index, img, [0, 0, 0])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-16
      • 1970-01-01
      • 2020-03-09
      相关资源
      最近更新 更多