【问题标题】:How do I plot a 32-Bin Histogram for a Grayscale Image in Python using OpenCV如何使用 OpenCV 在 Python 中为灰度图像绘制 32-Bin 直方图
【发布时间】:2013-10-12 18:14:47
【问题描述】:

我在尝试为我正在使用的 640x480 灰度图像生成直方图时遇到了困难。

我正在使用 Python 2.7.3、OpenCV 2.4.6(Python 绑定)和 Numpy

下面的图像是使用可执行软件工具(用 C++ 编程)从同一个图像生成的

这个直方图的属性是:

bins = 50
hist_width = 250
normalised_height_max = 50

因此图像规格为 250x50

我已查阅此文档:

OpenCV 中的直方图计算 http://docs.opencv.org/doc/tutorials/imgproc/histograms/histogram_calculation/histogram_calculation.html

Hist.py - OpenCV Python 示例 https://github.com/Itseez/opencv/blob/master/samples/python2/hist.py

第二个参考中的代码编译得很好,但我尝试编辑它以获得这些块样式列而不是细线,但我似乎无法正确。

import cv2
import numpy as np

cv2.namedWindow('colorhist', cv2.CV_WINDOW_AUTOSIZE)

img = cv2.imread('sample_image.jpg')
h = np.zeros((50,256))

bins = np.arange(32).reshape(32,1)
hist_item = cv2.calcHist([img],0,None,[32],[0,256])
cv2.normalize(hist_item,hist_item,64,cv2.NORM_MINMAX)
hist=np.int32(np.around(hist_item))
pts = np.column_stack((bins,hist))
cv2.polylines(h,[pts],False,(255,255,255))

h=np.flipud(h)

cv2.imshow('colorhist',h)
cv2.waitKey(0)

我的目标是使用以下规格制作直方图:

bins = 32
hist_width = 256
normalised_height_max = 64

我如何修复此代码以实现与上述指定规格类似的直方图?

【问题讨论】:

    标签: python opencv histogram grayscale


    【解决方案1】:

    我已经设法解决了这个问题:

    import cv2
    import numpy as np
    
    #Create window to display image
    cv2.namedWindow('colorhist', cv2.CV_WINDOW_AUTOSIZE)
    
    #Set hist parameters
    
    hist_height = 64
    hist_width = 256
    nbins = 32
    bin_width = hist_width/nbins
    
    #Read image in grayscale mode
    img = cv2.imread('sample_image.jpg',0)
    
    #Create an empty image for the histogram
    h = np.zeros((hist_height,hist_width))
    
    #Create array for the bins
    bins = np.arange(nbins,dtype=np.int32).reshape(nbins,1)
    
     #Calculate and normalise the histogram
    hist_item = cv2.calcHist([img],[0],None,[nbins],[0,256])
    cv2.normalize(hist_item,hist_item,hist_height,cv2.NORM_MINMAX)
    hist=np.int32(np.around(hist_item))
    pts = np.column_stack((bins,hist))
    
    #Loop through each bin and plot the rectangle in white
    for x,y in enumerate(hist):
        cv2.rectangle(h,(x*bin_width,y),(x*bin_width + bin_width-1,hist_height),(255),-1)
    
    #Flip upside down
    h=np.flipud(h)
    
    #Show the histogram
    cv2.imshow('colorhist',h)
    cv2.waitKey(0)
    

    结果如下:

    请注意,图像的底部与 C++ 实现略有不同。我认为这是由于代码中某处的舍入所致

    【讨论】:

      猜你喜欢
      • 2019-06-01
      • 1970-01-01
      • 2013-03-24
      • 2012-03-12
      • 1970-01-01
      • 2018-06-02
      • 2023-01-27
      • 2020-04-16
      • 1970-01-01
      相关资源
      最近更新 更多