轮廓匹配
基本原理
根据图形的图像几何矩和Hu矩计算图像的轮廓是否匹配
代码演示
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace cv;
using namespace std;
void contour_info(Mat& image, vector<vector<Point>>& contours);
int main() {
Mat src1 = imread("D:/ps/te.png");
Mat src2 = imread("D:/ps/te.png");
if (src1.empty()|| src2.empty())
{
cout << "could not find the image";
return -1;
}
namedWindow("input", WINDOW_FREERATIO);
imshow("input1", src1);
imshow("input2", src2);
vector<vector<Point>>contours1;
vector<vector<Point>>contours2;
contour_info(src1, contours1);
contour_info(src2, contours2);
Moments mm2 = moments(contours2[0]);
Mat hu2;
HuMoments(mm2, hu2);
for (size_t t = 0; t < contours1.size(); t++) {
Moments mm = moments(contours2[t]);
Mat hu;
HuMoments(mm, hu);
double dist = matchShapes(hu, hu2,CONTOURS_MATCH_I1, 0);
if(dist < 1.0){
printf(" matched distance valu: %.2f\n", dist);
drawContours(src1, contours1, t, Scalar(0, 0, 255), 2, 8);
}
}
//drawContours(src, contours, -1, Scalar(0, 0, 255), 2, 8);
imshow("find contours demo", src1);
waitKey(0);
destroyAllWindows();
return 0;
}
void contour_info(Mat& image, vector<vector<Point>>& contours) {
//二值化
Mat dst;
GaussianBlur(image, image, Size(3, 3), 0);
Mat gray, binary;
cvtColor(image, gray, COLOR_BGR2GRAY);
threshold(gray, binary, 0, 255, THRESH_BINARY | THRESH_OTSU);
//轮廓发现
imshow("binary", binary);
//vector<vector<Point>>contours;
vector<Vec4i>hierachy;
findContours(binary, contours, hierachy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point());
}