簡體   English   中英

如何使用合並的 bin 計算直方圖?

[英]How can I calculate histograms with merged bins?

我想問你關於使用 OpenCV 在 Python 中計算直方圖的問題。 我使用了這個代碼:

hist = cv2.calcHist(im, [0, 1, 2], None, [8, 8, 8], [0, 256, 0, 256, 0, 256])

結果給了我 8 個 bin 的每個顏色通道的直方圖,但我想得到的是:

  • 第一個 bin ( R=0-32,G=0-32,B=0-32 ),
  • 第二個bin( R=33-64,G=0-32,B=0-32 ),
  • 等等,

所以我總共會有 512 個垃圾箱。

從我的角度來看,您的cv2.calcHist調用不正確:

hist = cv2.calcHist(im, [0, 1, 2], None, [8, 8, 8], [0, 256, 0, 256, 0, 256])

第一個參數應該是圖像列表:

hist = cv2.calcHist([im], [0, 1, 2], None, [8, 8, 8], [0, 256, 0, 256, 0, 256])

讓我們看看這個小例子:

import cv2
import numpy as np

# Red blue square of size [4, 4], i.e. eight pixels (255, 0, 0) and eight pixels (0, 0, 255); Attention: BGR ordering!
image = np.zeros((4, 4, 3), dtype=np.uint8)
image[:, 0:2, 2] = 255
image[:, 2:4, 0] = 255

# Calculate histogram with two bins [0 - 127] and [128 - 255] per channel:
# Result should be hist["bin 0", "bin 0", "bin 1"] = 8 (red) and hist["bin 1", "bin 0", "bin 0"] = 8 (blue)

# Original cv2.calcHist call with two  bins [0 - 127] and [128 - 255]
hist = cv2.calcHist(image, [0, 1, 2], None, [2, 2, 2], [0, 256, 0, 256, 0, 256])
print(hist, '\n')       # Not correct

# Correct cv2.calcHist call
hist = cv2.calcHist([image], [0, 1, 2], None, [2, 2, 2], [0, 256, 0, 256, 0, 256])
print(hist, '\n')       # Correct
[[[8. 0.]
  [0. 0.]]

 [[0. 0.]
  [0. 4.]]] 

[[[0. 8.]
  [0. 0.]]

 [[8. 0.]
  [0. 0.]]] 

可以,您的版本總共只有 12 個值,而圖像中有 16 個像素! 此外,目前還不清楚代表什么“垃圾箱”(如果有的話)。

因此,擁有正確的cv2.calcHist調用,您的總體思路/方法是正確的! 也許,您只需要一點提示,“如何閱讀”結果hist

import cv2
import numpy as np

# Colored rectangle of size [32, 16] with one "color" per bin for eight bins per channel,
# i.e. 512 pixels, such that each of the resulting 512 bins has value 1
x = np.linspace(16, 240, 8, dtype=np.uint8)
image = np.reshape(np.moveaxis(np.array(np.meshgrid(x, x, x)), [0, 1, 2, 3], [3, 0, 1, 2]), (32, 16, 3))

# Correct cv2.calcHist call
hist = cv2.calcHist([image], [0, 1, 2], None, [8, 8, 8], [0, 256, 0, 256, 0, 256])

# Lengthy output of each histogram bin
for B in np.arange(hist.shape[0]):
    for G in np.arange(hist.shape[1]):
        for R in np.arange(hist.shape[2]):
            r = 'R=' + str(R*32).zfill(3) + '-' + str((R+1)*32-1).zfill(3)
            g = 'G=' + str(G*32).zfill(3) + '-' + str((G+1)*32-1).zfill(3)
            b = 'B=' + str(B*32).zfill(3) + '-' + str((B+1)*32-1).zfill(3)
            print('(' + r +  ', ' + g + ', ' + b + '): ', int(hist[B, G, R]))
(R=000-031, G=000-031, B=000-031):  1
(R=032-063, G=000-031, B=000-031):  1
(R=064-095, G=000-031, B=000-031):  1
[... 506 more lines ...]
(R=160-191, G=224-255, B=224-255):  1
(R=192-223, G=224-255, B=224-255):  1
(R=224-255, G=224-255, B=224-255):  1

希望有幫助!

暫無
暫無

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

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