|
分類:[C/C++]
void QuickDemo::contour_get(Mat& image, vector<vector<Point>>& contours)
{
//高斯模糊
Mat dst;
GaussianBlur(image, dst, Size(3, 3), 0);
Mat gray;
cvtColor(dst, gray, COLOR_BGR2GRAY);
Mat binary;
threshold(gray, binary, 0, 255, THRESH_BINARY_INV | THRESH_OTSU);
/*namedWindow("THRESH_OTSU", WINDOW_FREERATIO);
imshow("THRESH_OTSU", binary);*/
//查找轮廓
vector<Vec4i> hierachy;
findContours(binary, contours, hierachy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE, Point());
cout << contours.size() << endl;
}
18. void QuickDemo::contour_match(Mat& image1, Mat&image2)
19. {
20. vector<vector<Point>> contours1;
21. vector<vector<Point>> contours2;
22. contour_get(image1, contours1);
23. contour_get(image2, contours2);
24.
25. /*
26. * 步骤:
27. * 1、任选图像2中的一个轮廓,计算其Hu矩
28. * 2、对图像1所有轮廓计算Hu矩,将图像2的Hu矩与图像1的所有Hu进行比较
29. * 3、相似度阈值操作。
30. */
31. //Hu矩计算
32. Moments mm2 = moments(contours2[0]);//先计算几何矩
33. Mat hu2;
34. HuMoments(mm2, hu2);
35. for (size_t t = 0; t < contours1.size(); ++t) {
36. Moments mm = moments(contours1[t]);//先计算几何矩
37. Mat hu;
38. HuMoments(mm, hu);
39. double sim_value = matchShapes(hu, hu2, CONTOURS_MATCH_I1, 0);
40. //在原图绘制相似轮廓
41. if (sim_value < 1) {
42. cout << "第" << t << "个轮廓的相似度值为:" << (float)(1 - sim_value) << endl;
43. drawContours(image1, contours1, t, Scalar(0, 255, 0), 2, 8);
44. drawContours(image2, contours2, 0, Scalar(0, 255, 0), 2, 8);
45. }
46.
47. //获取图像1轮廓的中心位置
48. double cx = mm.m10 / mm.m00;
49. double cy = mm.m01 / mm.m00;
50. circle(image1, Point(cx, cy), 2, Scalar(255, 0, 0), 2, 8);//在中心位置画圆
51. }
52. namedWindow("contours1", WINDOW_FREERATIO);
53. imshow("contours1", image1);
54. namedWindow("image2", WINDOW_FREERATIO);
55. imshow("image2", image2);
56. }
|