Abid Abdul Gafoor
Abid Abdul Gafoor

Reputation: 461

Counting the no. of black to white pixels in the image using OpenCV

I'm new to python and any help would be greatly appreciated.

enter image description here

What I'm trying to do from this image is to count the number of black pixels (0,0,0) and the consecutive values i.e (1,1,1), (2,2,2), (3,3,3) all up to (255,255,255). So the code would print out answers such as:

(0,0,0) = 10 pixels
(1,1,1) = 5 pixels
(2,2,2) = 8 pixels
etc.

This is a code I found online to find the blue pixels but I don't want to set a upper and lower boundary. I'm completely confused on how to do this please help!

import cv2
import numpy as np

img = cv2.imread("multi.png")
BLUE_MIN = np.array([0, 0, 200], np.uint8)
BLUE_MAX = np.array([50, 50, 255], np.uint8)

dst = cv2.inRange(img, BLUE_MIN, BLUE_MAX)
no_blue = cv2.countNonZero(dst)
print('The number of blue pixels is: ' + str(no_blue))
cv2.namedWindow("opencv")
cv2.imshow("opencv",img)
cv2.waitKey(0)

Upvotes: 3

Views: 2963

Answers (3)

filippo
filippo

Reputation: 5294

colors, counts = np.unique(img.reshape(-1, 3), axis=0, return_counts=True)

for color, count in zip(colors, counts):
    print("{} = {} pixels".format(color, count))

[1 1 0] = 6977 pixels
[3 3 3] = 7477 pixels
[6 6 6] = 5343 pixels
[8 8 8] = 4790 pixels
[11 11 11] = 4290 pixels
[13 13 13] = 3681 pixels
[16 16 16] = 3605 pixels
[19 19 19] = 2742 pixels
[21 21 21] = 2984 pixels
[...]

Upvotes: 2

Daniel F
Daniel F

Reputation: 14399

Using void views and np.unique

def vview(a):  #based on @jaime's answer: https://stackoverflow.com/a/16973510/4427777
    return np.ascontiguousarray(a).view(np.dtype((np.void, a.dtype.itemsize * a.shape[1])))

pixels = = img.reshape(-1,3)
_, idx, count = np.unique(vview(pixels), return_index = True, return_counts = True)

print np.c_[pixels[idx], count[:, None]]

Basically pixels[idx] is an array of all the unique pixels and count is how many of each pixel exist in the image

Upvotes: 0

jedwards
jedwards

Reputation: 30210

import cv2
import numpy as np
from collections import defaultdict

img = cv2.imread("C:\\temp\\multi.png")
pixels = img.reshape(-1,3)

counts = defaultdict(int)
for pixel in pixels:
    if pixel[0] == pixel[1] == pixel[2]:
        counts[pixel[0]] += 1

for pv in sorted(counts.keys()):
    print("(%d,%d,%d): %d pixels" % (pv, pv, pv, counts[pv]))

Prints:

(3,3,3): 7477 pixels
(6,6,6): 5343 pixels
(8,8,8): 4790 pixels
(11,11,11): 4290 pixels
(13,13,13): 3681 pixels
(16,16,16): 3605 pixels
(19,19,19): 2742 pixels
(21,21,21): 2984 pixels
(26,26,26): 2366 pixels
(29,29,29): 2149 pixels
(32,32,32): 2460 pixels
...

Upvotes: 1

Related Questions