0

I am trying to apply component-labeling via contour tracing of a simple array as an example.

arr = np.array([
                [1,0,1,0,0,0,0],
                [1,1,1,0,0,0,0],
                [0,1,1,0,0,0,1],
                [0,1,1,0,0,1,1],
                [0,0,0,0,1,1,1],
                [0,0,0,1,1,1,1],
                [0,0,0,1,1,1,1],
                ])

This represents a binary image, with 0 being empty space and 1 representing the shape.

The result I am trying to get is separately labeling these two polygons and showing in a graph via matplotlib each polygon in a different color (as proof that each point in the polygon has been labeled to a respective region.

I thought that the combination of skimage.measure.regionprops, skimage.measure.label, and skimage.measure.find_contours would do the trick, but I haven't been able to find any examples that I am looking for to work off of.

I have spent hours trying to understand the documentation and searching for previous posts and am at a dead end now. This post hereseems like something similar to my problem, although I would want to be able to label each pixel inside shape rather then just the perimeters.

Any help or explanation of what I SHOULD be doing instead muchly appreciated. Thank you

Evan Kim
  • 769
  • 2
  • 8
  • 26

1 Answers1

3

You just need to use skimage.measure.label:

import numpy as np
from skimage.measure import label
from skimage import io

arr = np.array([[1,0,1,0,0,0,0],
                [1,1,1,0,0,0,0],
                [0,1,1,0,0,0,1],
                [0,1,1,0,0,1,1],
                [0,0,0,0,1,1,1],
                [0,0,0,1,1,1,1],
                [0,0,0,1,1,1,1]])

img = label(arr)
io.imshow(img)

labeled

In [12]: img
Out[12]: 
array([[1, 0, 1, 0, 0, 0, 0],
       [1, 1, 1, 0, 0, 0, 0],
       [0, 1, 1, 0, 0, 0, 2],
       [0, 1, 1, 0, 0, 2, 2],
       [0, 0, 0, 0, 2, 2, 2],
       [0, 0, 0, 2, 2, 2, 2],
       [0, 0, 0, 2, 2, 2, 2]], dtype=int64)
Tonechas
  • 13,398
  • 16
  • 46
  • 80
  • Let's say I wanted to reference the entire yellow shape and get a ndarray of all the points in the yellow shape. Would I use regionprops for that? – Evan Kim Apr 15 '19 at 13:24
  • 1
    Noy sure I'm understanding correctly, but I think you could simply do this: `yellow = img == 2` – Tonechas Apr 15 '19 at 13:26
  • Let me try to rephrase. Let's say this is a big array (over 100x100) and there can be anywhere from 5 to 10 different shapes that get labeled. How can I find the largest shape from all of the labeled shapes? Would I also be able to query if a point `(x,y)` belongs to the largest label? – Evan Kim Apr 15 '19 at 13:36
  • 1
    `skimage.measure.regionprops` is your friend. I think you are more likely to get help on how to use `regionprops` to solve your problem if you post a new question. – Tonechas Apr 15 '19 at 13:41