我一直在使用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 = []
使用这种方法,我可以从示例图像生成四个区域,这些区域与左侧接壤而没有错误。尽管上面的伪代码中未显示它,但我也用透明像素填充段以保留其形状。这种额外的考虑使查找右侧子图像更加困难。
答案 0 :(得分:2)
这可以通过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])