簡體   English   中英

數不了。 使用OpenCV的圖像中的黑色到白色像素

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

我是python的新手,非常感謝任何幫助。

在此輸入圖像描述

我想從這張圖片做的是計算黑色像素數(0,0,0)和連續值,即(1,1,1),(2,2,2),(3,3) ,3)全部達到(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)
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]))

打印:

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

使用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是圖像中存在的每個像素的數量

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM