Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the number of pixels in a numpy array equal to a given color

Tags:

python

numpy

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?

like image 914
Tim Avatar asked Nov 30 '25 02:11

Tim


1 Answers

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
like image 50
furas Avatar answered Dec 02 '25 16:12

furas