#include"RgbHist.h"
#define CREATE_IMAGE(DST,SRC,DEPTH,CHANNEL) DST=cvCreateImage(cvGetSize(SRC),DEPTH,CHANNEL)
#define MAX_VALUE_HIST(SRC,MAX) cvGetMinMaxHistValue(SRC,NULL,MAX,NULL,NULL)
using std::cout;
using std::endl;
RGBHist::RGBHist()
{
SetBin(16,16,16);
SetRange();
}
bool RGBHist::LoadImage(char* argv)
{
if(NULL==argv||NULL==(m_image=cvLoadImage(argv,1)))
return 0;
else
return 1;
}
void RGBHist::SetBin(int r_bin,int g_bin,int b_bin)
{
m_rBin=r_bin;
m_gBin=g_bin;
m_bBin=b_bin;
}
void RGBHist::SetRange(float rl,float ra,float gl,float ga,float bl,float ba)
{
m_rRange[0]=rl;
m_rRange[1]=ra;
m_gRange[0]=gl;
m_gRange[1]=ga;
m_bRange[0]=bl;
m_bRange[1]=ba;
}
void RGBHist::CalcHist(int r_bin,int g_bin,int b_bin)
{
CREATE_IMAGE(m_rPlane,m_image,8,1);
CREATE_IMAGE(m_gPlane,m_image,8,1);
CREATE_IMAGE(m_bPlane,m_image,8,1);
IplImage *m_planes[]={m_rPlane,m_gPlane,m_bPlane};
cvSplit(m_image,m_bPlane,m_gPlane,m_rPlane,NULL);
SetBin(r_bin,g_bin,b_bin);
float* ranges[]={m_rRange,m_gRange,m_bRange};
m_rHist=cvCreateHist(1,&m_rBin,CV_HIST_ARRAY,&ranges[0],1);
m_gHist=cvCreateHist(1,&m_gBin,CV_HIST_ARRAY,&ranges[1],1);
m_bHist=cvCreateHist(1,&m_bBin,CV_HIST_ARRAY,&ranges[2],1);
cvCalcHist(&m_bPlane,m_bHist);
cvCalcHist(&m_gPlane,m_gHist);
cvCalcHist(&m_rPlane,m_rHist);
cvNormalizeHist(m_gHist,1); //如果需要显示直方图应屏蔽下述三行
cvNormalizeHist(m_rHist,1);
cvNormalizeHist(m_bHist,1);
}
void RGBHist::ShowHist()
{
IplImage *hist_img=cvCreateImage(cvSize(256,420),8,3);
cvZero(hist_img);
float max[3]={0,0,0};
MAX_VALUE_HIST(m_rHist,&max[0]);
MAX_VALUE_HIST(m_gHist,&max[1]);
MAX_VALUE_HIST(m_bHist,&max[2]);
float rBin_width=float(hist_img->width/m_rBin);
float gBin_width=float(hist_img->width/m_gBin);
float bBin_width=float(hist_img->width/m_bBin);
float rBin_unith=(float)(hist_img->height/max[0]/3);
float gBin_unith=(float)(hist_img->height/max[1]/3);
float bBin_unith=(float)(hist_img->height/max[2]/3);
color(m_rHist,m_rBin,rBin_width,rBin_unith,hist_img,0,cvScalar(255,0,0));
color(m_gHist,m_gBin,gBin_width,gBin_unith,hist_img,140,cvScalar(0,255,0));
color(m_bHist,m_bBin,bBin_width,bBin_unith,hist_img,280,cvScalar(0,0,255));
cvNamedWindow("HIST",1);
cvShowImage("HIST",hist_img);
cvWaitKey(0);
cvDestroyWindow("HIST");
cvReleaseImage(&hist_img);
}
void RGBHist::color(CvHistogram *hist,int bin,float bin_width,float bin_unith,IplImage* hist_image,int level,CvScalar RGB)
{
for(int s=0;s<bin;++s)
{
float bin_val=(float)cvGetReal1D(hist->bins,s);
CvPoint p0=cvPoint(s*bin_width,hist_image->height-level);
CvPoint p1=cvPoint((s+1)*bin_width,
hist_image->height-bin_val*bin_unith-level);
cvRectangle(hist_image,p0,p1,RGB,1,8,0);
}
}