简体   繁体   中英

How to mask an image gray scale using numpy array slicing

I need to replace 8 bits values (0 to 255) indexed set of an image (final image), following a "map values" from another image (second image) gray scale which related map indexes was chosen from a primary image.

In fact this is similar thing that MATLAB does with

 indexS =  find(image1 == integer ('could be a integer from 1 to 255')) 
 imagfinal(indexS) = imagsecondary(indexS).

I tried following examples for python/matlab find() on stack, for ex.: MATLAB-style find() function in Python . And the related ones...

I tried n.nonzero , np.argwhere and np.where, but I am really confuse.

I have three source images, let's say A, B, C, same shape, eg. (100x100) with diverse 0 to 255 values, I mean they are completely gray scales different each other.

So, 1st step - I need to get all indexes with values = 1 (but could be , 10, 196 , up to 255) from A, so I did:

Aboolean = np.equal(A,1)

result is

       [False, False, False, ..., False, False, False],
       [False, False, False, ..., False, False, False],...

then I tried use those boolean index array results for getting the values from B:

Bnew = B[Aboolean]

But it did not work for furthers steps, because the result is a map of values and the indexes are lost...

The values from Bnew are supposed to substitute the respective values 8-bits on C image,I mean those 8-bits values into the same position (or same indexes), remembering that B and C (also A) have the same shape/size array (100x100).

So I tried again:


D = np.where(Aboolean,B,C)

when plotting the image, the final result is just the same image C !! No modifications, at all.


fig, ax = plt.subplots(nrows=1, figsize=(16,20))
ax.imshow(D, cmap='gray',interpolation='nearest')

results same image 'C'

My goal is a kind of replacing a set of values from B upon C (ruled by same index positions) , that was sliced following a map of indexes of conditions upon A.

You can do this by using the boolean indexing from A to directly copy the values from C into B (if you don't want to modify the original B, first create a copy using B.copy() ).

>>> import numpy as np
>>> A = np.array([0,0,1,0,0])
>>> B = np.array([1,2,3,4,5])
>>> C = np.array([10,9,8,7,6])
>>> B[A==1] = C[A==1]

>>> B
array([1, 2, 8, 4, 5])

EDIT:

C[A==1] = B[A==1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM