在OpenCV中从一维浮点数组计算直方图

2 投票
1 回答
2461 浏览
提问于 2025-04-16 16:22

我想用 opencvcv.CalcHist 方法来创建直方图并计算它。但是我的数据是一维数组,而不是 IplImage 对象。为什么下面的代码会产生零直方图呢?

hist =  cv.CreateHist([3, 3], cv.CV_HIST_ARRAY, [[0, 1], [0, 1]])
angles, magnitudes = np.random.rand(100), np.random.rand(100)
cv.CalcHist([cv.GetImage(cv.fromarray(np.array([x]))) for x in [angles, magnitudes]], hist)
np.array(hist.bins)

>>> array([[ 0.,  0.,  0.],
>>>    [ 0.,  0.,  0.],
>>>    [ 0.,  0.,  0.]], dtype=float32)

1 个回答

1

你上面的代码会出现一个异常(opencv 2.3.1版本):

OpenCV Error: Unsupported format or combination of formats () in calcHist, file /usr/ports/graphics/opencv-core/work/OpenCV-2.3.1/modules/imgproc/src/histogram.cpp, line 632
Traceback (most recent call last):
  File "ocv.py", line 8, in <module>
cv.CalcHist([cv.GetImage(cv.fromarray(np.array([x]))) for x in [angles, magnitudes]], hist)
cv2.error

使用np.float32来处理角度和大小可以解决这个问题:

hist =  cv.CreateHist([3, 3], cv.CV_HIST_ARRAY, [[0, 1], [0, 1]])
angles =np.random.rand(100).astype(np.float32)     
magnitude = np.random.rand(100).astype(np.float32)
cv.CalcHist([cv.GetImage(cv.fromarray(np.array([x]))) for x in [angles, magnitudes]], hist)
print np.array(hist.bins)

...

[[ 11.   9.   7.]
 [ 10.  11.  15.]
 [ 11.  14.  12.]]

撰写回答