3

I have been scouring around and can't seem to find an answer to this question. Say I have a given RGB value, i.e. (255,0,25) or something like that.

I have a ndarray called 'img' of shape (height, width, 3). Now, I want to find the number of pixels in this array that equal my color. I thought doing

(img==(255,0,25)).sum() would work, but even if my image is a comprised only of the color (255,0,25), I will overcount and it seems that this is summing up when r=255, 0, or 25, and when g=255,0, or 25, and when b=255,0, or 25.

I have been searching the numpy documentation, but I can't find a way to compare pixel-wise, and not element-wise. Any ideas?

4
  • 1
    (img == (255,0,25)).all(axis=1).sum() Commented May 19, 2020 at 17:54
  • 2
    @furas Do you mean axis=-1? Commented May 19, 2020 at 17:56
  • @QuangHoang I tested on 1D list of pixels but for 2D array of pixels it has to be axis=2 and it gives the same as axis=-1 Commented May 19, 2020 at 17:58
  • 2
    Exactly my point. In general, it'd better be axis=-1. That said, an image is more likely a 3-D array. Commented May 19, 2020 at 17:59

1 Answer 1

5

it compares every value in RGB separatelly so every pixel gives tuple (True, True, True) and you have to convert (True, True, True) to True using .all(axis=...)

For 3D array (y,x,RGB) you have to use .all(axis=2) or more universal .all(axis=-1) as noticed @QuangHoang in comment.

print( (img == (255,0,25)).all(axis=-1).sum() )

import numpy as np

img = np.array([[(255,0,25) for x in range(3)] for x in range(3)])
#print(img)

print( (img == (255,0,25)).all(axis=-1).sum() )  # 9

img[1][1] = (0,0,0)
img[1][2] = (0,0,0)
#print(img)

print( (img == (255,0,25)).all(axis=-1).sum() )  # 7
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.