Python Forum

Full Version: Using boolean mask in Numpy for 3D
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I can generate a 8 x 8 x 4 matrix as follows using Numpy:

px = np.random.randint(1,254, (8,8,4),dtype=np.uint8)

This gives me 64 groups where each group has 4 values. This would be a very small CMYK image.
I will go much larger, hence the need for Numpy.
I want to use Boolean Masking to manipulate each group. Now focusing on the forth group, I would expect
my masking to look something like the following:

px[px[:, :, 3] >160] = 3 #(Here)

I saw something like this in 2D and I have tried to expand it to 3D. The above I would like it to do the following:
For every row and column in the 8 x 8 array, if the fourth element has a value greater than 160, assign a value of 3 to that element. Now, if I try this...

print([px[:, :, 3] >160])

It will give me a 8 x 8 True/False array that corresponds to the fourth element conditions as I would expect.

How does one write the line labeled (Here) so it will modify only the fourth element as I described?