Zaoza14
Zaoza14

Reputation: 63

how to find all pixel values ​from a certain range

I have an rgb image with many colours. I know the colours (pixel values) beforehand. I want to find quantity of certain colours on my image. I can do it one color at a time like:

color1 = [63, 51, 30]
count1 = (np.count_nonzero(np.all(MyImage == color1, axis=2)

but how can I find sum of pixels if i want to find many different colors, and don't use something like this:

color2 = [14, 24, 145]
count2 = (np.count_nonzero(np.all(MyImage == color2, axis=2)
color3 = [13, 190, 25]
count3 = (np.count_nonzero(np.all(MyImage == color3, axis=2)
color4 = [156, 31, 19]
count4 = (np.count_nonzero(np.all(MyImage == color4, axis=2)
sumofpixels = count1 + count2...+ countn

Upvotes: 0

Views: 1273

Answers (1)

Julien
Julien

Reputation: 15206

I think this is what you want?

colors = np.array([
    [63, 51, 30],
    [14, 24, 145],
    [13, 190, 25],
    [156, 31, 19],
    ])

image = np.ones((100,100,3)) * colors[3] # create test image with colors[3]
image[0,0] = colors[0] # add 1 pixel with colors[0]
image[1,:] = colors[1] # 1 row with colors[1], i.e. 100 pixels
image[10:20] = colors[2] # 10 rows with colors[2], i.e. 1000 pixels
# 8899 pixels remaining with colors[3]

counts = np.all(image[None] == colors[:,None,None], axis=3).sum(axis=(1,2))
# array([   1,  100, 1000, 8899])

Explanation: the None's create new axes to shapes (1,100,100,3) and (4,1,1,3) so the == will broadcast easily. Then check where all color channels (axis=3) match, then sum over image dimensions (axis=(1,2)), to finally get the total count for each color.

Upvotes: 3

Related Questions