数不了。使用OpenCV

时间:2018-06-12 12:37:47

标签: python numpy opencv image-processing

我是python的新手,非常感谢任何帮助。

enter image description here

我想从这张图片中做的是计算黑色像素数(0,0,0)和连续值,即(1,1,1),(2,2,2),(全部达到(255,255,255)。所以代码会打印出答案,例如:

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

这是我在网上找到的用于查找蓝色像素的代码,但我不想设置上下边界。我完全很困惑如何做到这一点,请帮忙!

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)

3 个答案:

答案 0 :(得分:2)

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
[...]

答案 1 :(得分:0)

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]))

打印:

(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
...

答案 2 :(得分:0)

使用void次观看和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]]

基本上pixels[idx]是所有唯一像素的数组,而count是图像中存在的每个像素的数量