2

I have performed mean-shift segmentation on an image and got the labels array, where each point value corresponds to the segment it belongs to.

labels = [[0,0,0,0,1],
          [2,2,1,1,1],
          [0,0,2,2,1]]

On the other hand, I have the corresponding grayScale image, and want to perform operations on each regions independently.

img = [[100,110,105,100,84],
       [ 40, 42, 81, 78,83],
       [105,103, 45, 52,88]]

Let's say, I want the sum of the grayscale values for each region, and if it's <200, I want to set those points to 0 (in this case, all the points in region 2), How would I do that with numpy? I'm sure there's a better way than the implementation I have started, which includes many, many for loops and temporary variables...

2 Answers 2

2

Look into numpy.bincount and numpy.where, that should get you started. For example:

import numpy as np
labels = np.array([[0,0,0,0,1],
                   [2,2,1,1,1],
                   [0,0,2,2,1]])
img = np.array([[100,110,105,100,84],
                [ 40, 42, 81, 78,83],
                [105,103, 45, 52,88]])

# Sum the regions by label:
sums = np.bincount(labels.ravel(), img.ravel())

# Create new image by applying threhold
final = np.where(sums[labels] < 200, -1, img)
print final
# [[100 110 105 100  84]
#  [ -1  -1  81  78  83]
#  [105 103  -1  -1  88]]
Sign up to request clarification or add additional context in comments.

Comments

1

You're looking for the numpy function where. Here's how you get started:

import numpy as np

labels = [[0,0,0,0,1], 
                 [2,2,1,1,1], 
                 [0,0,2,2,1]]

img = [[100,110,105,100,84], 
             [ 40, 42, 81, 78,83], 
             [105,103, 45, 52,88]]

# to sum pixels with a label 0:
px_sum = np.sum(img[np.where(labels == 0)])

1 Comment

wow, I love numpy :D that's exactly what I was looking for, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.