1

I am working on a multiband image with python.

I imported my image as a masked numpy array of shape (bands, rows, cols) using rasterio. The mask is the same for all bands.

I would like to get the spectra of all non-masked pixels. The result could be an array of shape (bands, rows).

For now I am doing:

output = []
for band in range(array.shape[0]):
 output.append(array[band][array.mask[0]==False])
output = np.asarray(output)

Is there a more direct way to do it?

asked Jul 9, 2019 at 8:17
2
  • By get the spectra of all non-masked pixels do you mean get all the pixel values that do not have a mask? Is the mask the same for all bands? Commented Jul 9, 2019 at 14:01
  • Yes the mask is the same for all bands. And yes I mean all the pixel values that do not have a mask, but I don't want to lose the "bands" dimension. Commented Jul 9, 2019 at 14:17

1 Answer 1

1

You can get all the values of the array that are not masked by indexing the array with the inverse of the mask (hence the ~ operator), with the following line: output = array[~array.mask]

This will result in a 1D array with all the non-masked values. However, you said you wanted to keep the band dimentionality. You can reshape the array so it will maintain the band dimentionality by specifying the the number of bands and -1, which automatically computes the second shape value depending on the number of bands. However, bear in mind that every band has to have the same number of non-masked values for this to work.

output = array[~array.mask].reshape(bands, -1)

This results in the desired shape. Lastly, you can pass this to the np.array() constructor so you get a normal array rather than a masked one.

output = np.array(array[~array.mask].reshape(bands, -1))

answered Jul 9, 2019 at 14:32

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.