3

I've got an image as numpy array and a mask for image.

from scipy.misc import face

img = face(gray=True)
mask = img > 250

How can I apply function to all masked elements?

def foo(x):
    return int(x*0.5) 
1
  • Actually function should return random value in range (0, 255) for every cell under mask. Commented Apr 5, 2016 at 10:27

1 Answer 1

4

For that specific function, few approaches could be listed.

Approach #1 : You can use boolean indexing for in-place setting -

img[mask] = (img[mask]*0.5).astype(int)

Approach #2 : You can also use np.where for a possibly more intuitive solution -

img_out = np.where(mask,(img*0.5).astype(int),img)

With that np.where that has a syntax of np.where(mask,A,B), we are choosing between two equal shaped arrays A and B to produce a new array of the same shape as A and B. The selection is made based upon the elements in mask, which is again of the same shape as A and B. Thus for every True element in mask, we select A, otherwise B. Translating this to our case, A would be (img*0.5).astype(int) and B is img.

Approach #3 : There's a built-in np.putmask that seems to be the closest for this exact task and could be used to do in-place setting, like so -

np.putmask(img, mask, (img*0.5).astype('uint8'))
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the solutions! But how do I applied them to other function? Suppose, I need to generate random pixels instead of all masked cells. If I use these methods it will assign one value to all mask
Ok, I got it. At first I generate noisy image the same size as img and then I merge them by mask ans = np.where(mask, noisy_template, img)
@KatrinaMalakhova Ah I got your question now! :) So yes, you can generate noisy_template with noisy_template = np.random.randint(0,255,img.shape).astype('uint8').

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.