首页 > 代码库 > 图像检索:二维直方图+EMD距离
图像检索:二维直方图+EMD距离
#include<iostream> #include<fstream> #include<map> #include<string> using namespace std; #include<opencv2\core\core.hpp> #include<opencv2\highgui\highgui.hpp> #include<opencv2\imgproc\imgproc.hpp> using namespace cv; Mat signature(const Mat & src); int main(int argc,char* argv[]) { //定义文件流,只能读取 ifstream inPutFile(argv[1],ios::in); if(! inPutFile) { cerr <<"File Open Erro !"<<endl; return -1; } //读取文件流中的每一行,并赋值给fileName,形成查询数据库 string fileName; Mat image,imageSignature,sourceSignature; vector<Mat> signatures; map<int,string> index;//图像的索引 index.clear(); int number = 0; signatures.clear(); while(getline(inPutFile,fileName)) { index.insert(pair<int,string>(number,fileName)); number++; image = imread(fileName,1); imageSignature = signature(image); signatures.push_back(imageSignature); } //待搜索的图像 number = 0; Mat imageSource = imread(argv[2],1); sourceSignature = signature(imageSource); vector<Mat>::iterator iter; map<float,int> distance; for(iter = signatures.begin();iter != signatures.end();iter ++) { distance.insert(pair<float,int>(EMD(sourceSignature,*iter,CV_DIST_L2,number),number)); number ++; } //显示距离最小的前五名的检索图像 number = 0; map<float,int>::iterator mapiter; for(mapiter = distance.begin();mapiter != distance.end() && number <1;mapiter++,number++) { string simage = index.find((*mapiter).second)->second; image = imread(simage,1); namedWindow(simage,1); imshow(simage,image); } waitKey(0); return 0; } Mat signature(const Mat & src) { Mat hsv,hist,normalHist,histCol; //颜色空间转换 cvtColor(src,hsv,CV_BGR2HSV); //二维直方图 int hbins = 30; int sbins = 16; int histSize[] = {hbins,sbins}; float hranges[] = {0.0,180.0}; float sranges[] = {0.0,256.0}; const float* ranges[] = {hranges,sranges}; int channels[] ={0,1}; calcHist(&hsv,1,channels,Mat(),hist,2,histSize,ranges,true,false); //把直方图特征按一列来存储 int rows = hbins*sbins; histCol = hist.reshape(1,rows); //把直方图归一化 normalize(histCol,normalHist,1000,0,CV_L1,CV_32F); Mat signature(hbins*sbins,3,CV_32FC1); normalHist.copyTo(signature.col(0)); //我们把bin的索引放在signature的第二列和第三列 for(int h =0 ;h<hbins;h++) { Mat roi(signature,Rect(1,h*sbins,2,sbins)); for(int s= 0;s<sbins;s++) { roi.at<float>(s,0) = float(h); roi.at<float>(s,1) =float(s); } } return signature; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。