首页 > 代码库 > 二维直方图及其比较

二维直方图及其比较

创建图像的HSV空间的H和S二维直方图并比较直方图相似度:

wKioL1PsIq7jBhULAALN9XfV2yQ160.jpg

wKiom1PsIZiT8OkfAALN9XfV2yQ292.jpg

wKioL1PsIrbCT5o2AALd0NFOUEs360.jpg

代码:

#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=http://www.mamicode.com/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=http://www.mamicode.com/0;"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;
}


本文出自 “flyclc” 博客,请务必保留此出处http://flyclc.blog.51cto.com/1385758/1539794