创建图像的HSV空间的H和S二维直方图并比较直方图相似度:
代码:
#include "cv.h" #include "cxcore.h" #include "highgui.h" #include <iostream> CvHistogram* Histogram2D(IplImage* src,int HSize,int SSize) { IplImage* SrcH=cvCreateImage(cvGetSize(src),8,1); IplImage* SrcS=cvCreateImage(cvGetSize(src),8,1); IplImage* SrcV=cvCreateImage(cvGetSize(src),8,1); IplImage* SrcHSV=cvCreateImage(cvGetSize(src),8,3); cvZero(SrcH); cvZero(SrcS); cvZero(SrcV); cvZero(SrcHSV); //转换BGR到HSV cvCvtColor(src,SrcHSV,CV_BGR2HSV); //分割HSV cvSplit(SrcHSV,SrcH,SrcS,SrcV,NULL); //创建histogram CvHistogram* hist; int dims=2; int size[]={HSize,SSize}; float HRange[]={0,180}; float SRange[]={0,255}; float *ranges[]={HRange,SRange}; hist=cvCreateHist(dims,size,CV_HIST_ARRAY,ranges,1); //计算histogram IplImage* image[]={SrcH,SrcS}; cvCalcHist(image,hist); //归一化histogram cvNormalizeHist(hist,1.0); //即直方图所有值加起来为1 return hist; //返回的是归一化的直方图 } int histogram(int argc,char** argv) { int HSize=30; int SSize=32; IplImage* src=cvLoadImage("e:\\picture\\4.jpg"); IplImage* src2=cvLoadImage("e:\\picture\\444.jpg"); CvHistogram* hist=Histogram2D(src,HSize,SSize); CvHistogram* hist2=Histogram2D(src2,HSize,SSize); //创建直方图图像 int scale=10; IplImage* HistImage=cvCreateImage(cvSize(HSize*scale,SSize*scale),8,3); IplImage* HistImage2=cvCreateImage(cvSize(HSize*scale,SSize*scale),8,3); //获取直方图最大值 float MaxHistValue=0; cvGetMinMaxHistValue(hist,NULL,&MaxHistValue); float MaxHistValue2=0; cvGetMinMaxHistValue(hist2,NULL,&MaxHistValue2); //画直方图图像 for(int h=0;h<HSize;h++) { for(int s=0;s<SSize;s++) { float data=cvQueryHistValue_2D(hist,h,s); int result=cvRound(data*255/MaxHistValue); //把最大值扩展到255 cvRectangle(HistImage,cvPoint(h*scale,s*scale),cvPoint((h+1)*scale-1,(s+1)*scale-1),cvScalar(result,result,result),CV_FILLED); } } for(int h=0;h<HSize;h++) { for(int s=0;s<SSize;s++) { float data=cvQueryHistValue_2D(hist2,h,s); int result=cvRound(data*255/MaxHistValue2); //把最大值扩展到255 cvRectangle(HistImage2,cvPoint(h*scale,s*scale),cvPoint((h+1)*scale-1,(s+1)*scale-1),cvScalar(result,result,result),CV_FILLED); } } //比较两个直方图 double CompareResult=cvCompareHist(hist,hist2,CV_COMP_BHATTACHARYYA);//CV_COMP_BHATTACHARYYA方法完全匹配是0,完全不匹配是1 std::cout<<"compare hist result is:"<<CompareResult<<std::endl; cvNamedWindow("src"); cvNamedWindow("src2"); cvNamedWindow("HistImage"); cvNamedWindow("HistImage2"); cvShowImage("src",src); cvShowImage("src2",src2); cvShowImage("HistImage",HistImage); cvShowImage("HistImage2",HistImage2); cvWaitKey(0); return 0; }