xShirase
xShirase

Reputation: 12389

operations on a NumPy array based on info in another Array

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...

Upvotes: 2

Views: 79

Answers (2)

rjonnal
rjonnal

Reputation: 1207

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)])

Upvotes: 1

Bi Rico
Bi Rico

Reputation: 25833

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

Upvotes: 2

Related Questions