2

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?

2
  • Do you mean np.mean(masked_dog_image[masked_dog_image > 0])? I have a feeling I’ve missed a detail. If so, please update the question to clarify the requirement(s). Commented Nov 19, 2020 at 18:49
  • Thanks for you reply. I fixed the question now. Commented Nov 19, 2020 at 21:42

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.