2

I've been using skimage.segmentation modules to find contiguous segments within an image. For example,

this image

segments quite nicely to

segmented

I want to be able to view the distinct regions of the original image in isolation (such that the above image would result in 6 roughly rectangular sub-images). I have obtained some degree of success in doing this, but it's been difficult. Is there any pre-existing module I can use to accomplish this?

If not, high-level algorthim advice would be appreciated.

Approach thus far:

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 = []

With this approach, I can generate the four regions from the example image that border the left side without error. While it's not shown in the above pseudo-code, I'm also padding segments with transparent pixels to preserve their shape. This additional consideration makes finding right-side sub-images more difficult.

Tonechas
  • 13,398
  • 16
  • 46
  • 80
user6118986
  • 341
  • 2
  • 15

1 Answers1

3

This can be readily accomplished through NumPy's 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)

segments

You could obtain the same result using NumPy's where function like this:

for index in np.unique(segments):
    segment = np.where(np.expand_dims(segments, axis=-1)==index, img, [0, 0, 0])
Tonechas
  • 13,398
  • 16
  • 46
  • 80