生成&绘制梯度幅度和直径的直方图。取向

时间:2017-05-19 05:47:08

标签: python opencv matplotlib

使用matplotlib如何生成&显示图像梯度幅度和方向的直方图?

我不知道的一件事是x轴限制;对于幅度应该是0到1?即边缘的强度在0到1之间?对于方向,我假设x轴限制为0到360(度)或者我应该做弧度吗?

下面是我如何生成渐变,幅度和方向。我现在如何将每个显示为直方图?

def get_gradient(src):

    sobelx = cv2.Sobel(src,cv2.CV_64F,1,0,ksize=5)
    sobely = cv2.Sobel(src,cv2.CV_64F,0,1,ksize=5)

    grad = sobelx + sobely
    mag = cv2.magnitude(sobelx, sobely)  # so my Mat element values could be anything between 0 and 1???
    ori = cv2.phase(sobelx, sobely, True) # so my Mat element values could be anything between 0 and 360 degrees???
    return [grad, mag, ori]

grad_res = get_gradient(src)

# number of bins is 100 from 0 to 1. Ie, 0.001, 0.002, ... 1.000 
# am I correct?
mag_hist = cv2.calcHist([grad_res[1]],[0],None,[100],[0,1]) 

ori_hist = cv2.calcHist([grad_res[2]],[0],None,[360],[0,360]) 

plt.plot(mag_hist)
plt.xlim([0,1])

plt.plot(ori_hist)
plt.xlim([0,360])

plt.show()

编辑:上述代码中的当前错误:

  

mag_hist = cv2.calcHist([gradient [1]],[0],None,[10],[0,100])   错误:C:\ projects \ opencv-python \ opencv \ modules \ imgproc \ src \ histogram.cpp:1422:错误:(-210)函数cv :: calcHist

1 个答案:

答案 0 :(得分:2)

您将返回calcHist不支持的64位浮点数。您需要将它们转换为32位浮点数。将cv2.Sobel()来电中的类型更改为cv2.CV_32F或使用[grad_res[1].astype('float32')]作为cv2.calcHist()中的参数。

来自OpenCV docs
图片 - 源数组。它们都应具有相同的深度,CV_8UCV_32F,并且大小相同。它们中的每一个都可以有任意数量的通道。