Reputation: 375
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?
Upvotes: 3
Views: 4411
Reputation: 142859
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
Upvotes: 5