简体   繁体   中英

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.

在此输入图像描述

What I'm trying to do from this image is to count the number of black pixels (0,0,0) and the consecutive values ie (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)
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
[...]
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
...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM