1. 程式人生 > >opencv計算兩個輪廓之間hu矩相似程度,MatchShapes

opencv計算兩個輪廓之間hu矩相似程度,MatchShapes

OPENCV提供了輸入影象直接進行hu矩匹配的函式,返回的是兩個影象或輪廓之間hu矩的相似度:

double cvMatchShapes(const void*object1,const void*object2,int method,doubleparameter=0);

計算兩個輪廓之間hu矩相似程度:

#include <iostream>
#include "cv.h"
#include "cxcore.h"
#include "highgui.h"
using namespace std;

CvSeq *getImageContours(CvArr *src)
{
	cvThreshold(src, src, 100, 255, CV_THRESH_BINARY);
	CvMemStorage * storage = cvCreateMemStorage(0);
	CvSeq * contours;
	cvFindContours(src, storage, &contours);
	return contours;
}
int main()
{
	IplImage *src1 = cvLoadImage("", 0);
	CvSeq *contours1 = getImageContours(src1);  // 得到src1的輪廓
	IplImage *src2 = cvLoadImage("", 0);
	CvSeq *contours2 = getImageContours(src2);
	double result = cvMatchShapes(contours1, contours2, 1);   // 根據輸入的影象或輪廓來計算它們的hu矩的相似度
	cout << result << endl;
	cvReleaseMemStorage(&contours1->storage);
	cvReleaseMemStorage(&contours1->storage);
	cvReleaseImage(&src1);
	cvReleaseImage(&src2);
	return 0;
}

給出了10副圖片2.jpg  3.jpg.....11.jpg

其中2.jpg和11.jpg非常相似,我們程式碼是要實現的在3~11.jgp找到與2.jpg最相似的圖片。

程式碼:

#include <iostream>
#include <string>
#include <sstream>
#include "cv.h"
#include "cxcore.h"
#include "highgui.h"
using namespace std;

int main()
{
	IplImage *srcColor = cvLoadImage("E:\\study_opencv_video\\lesson15_3\\2.jpg", 1);
	IplImage *src = cvCreateImage(cvGetSize(srcColor), 8, 1);
	cvCvtColor(srcColor, src, CV_BGR2GRAY);
	if(!src)
	{
		cout << "No Image Load" << endl;
	}
	int i;
	stringstream ss;
	string path;
	string str;
	IplImage *dst = NULL, *dstColor;
	char c[256];
	double result, maxResult= 1000 * 256 *256;
	IplImage *resultMap = NULL;
	for (i = 3; i < 12; i ++)
	{
		path = "E:\\study_opencv_video\\lesson15_3\\";
		ss.clear();
		ss << i;
		ss >> str;
		str += ".jpg";
		path += str;
		ss.clear();
		ss << path;
		ss >> c;
		dstColor = cvLoadImage(c,1);       //讀取圖片
		dst = cvCreateImage(cvGetSize(dstColor), 8, 1);
		cvCvtColor(dstColor, dst, CV_BGR2GRAY);
		result = cvMatchShapes(src, dst, 1);
		if(maxResult > result)         //求最大相似
		{
			resultMap = cvCreateImage(cvGetSize(dstColor), 8, 3);
			maxResult = result;
			cvCopy(dstColor, resultMap);
		}
	}
	cvNamedWindow("srcColor", 0);
	cvNamedWindow("resultMap",0);
	cvShowImage("resultMap", resultMap);
	cvShowImage("srcColor", srcColor);
	cvWaitKey(0);
	cvReleaseImage(&src);
	cvReleaseImage(&srcColor);
	cvReleaseImage(&dst);
	cvReleaseImage(&dstColor);
	cvReleaseImage(&resultMap);
	cvDestroyWindow("srcColor");
	cvDestroyWindow("resultMap");
	return 0;
}