Calculate mean of certain part of numpy array (image)

Viewed 236

I want to calculate the mean of a certain part of an image (a numpy array). The image contains a dog, and I have a mask that can black out all pixels except for the dog using bitwise_and. I can then calculate the mean intensity of the dog without the surrounding as

masked_dog_image = cv2.bitwise_and(dog_image,dog_mask)
dog_image_no_zeros = masked_dog_image[masked_dog_image > 0].
np.mean(dog_images_no_zeros)

HOWEVER, in think it is unnecessary to create masked_dog_image and then dog_image_no_zeros just to find this mean value. Is there a more efficient way to do it?

1 Answers

You can simply use the dog_mask to index into the image and calculate the mean of the resulting pixels:

np.mean(dog_image[dog_mask > 0])

I've made the dog_mask of type bool on purpose to ensure that we are properly indexing with a Boolean mask. I am making no assumptions as to the data type of your mask.

Related