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?

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.
    – tvoirand
    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))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.