繁体   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