2013-10-05 90 views
1

我一直很难尝试为我正在处理的640x480灰度图像生成直方图。如何在Python中使用OpenCV绘制灰度图像的32位柱状图

我使用Python 2.7.3,2.4.6的OpenCV(Python绑定)和numpy的

下面从相同的图像产生,使用可执行软件工具的图像(在编程C++)

该直方图中的性质是:因此

bins = 50 
hist_width = 250 
normalised_height_max = 50 

BW Histo

图像规格是250×

我咨询这个文档:在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 

我如何才能达到像一个直方图解决这个代码上面指定的规格?

回答

3

我已成功地解决了这个问题:

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) 

这是结果:

New Hist

注意,图像的底部到C++实现稍有不同。我认为这是由于四舍五入代码

相关问题