matchShapes轮廓特征属性及应用(七)—位置关系及轮廓匹配 1.计算点与轮廓的距离及位置关系——pointPolygonTest()
2.矩的计算——moments()
3.形状匹配(比较两个形状或轮廓间的相似度)——matchShapes()
先上ppt:
代码:1.计算点到轮廓的距离与位置关系
#include "opencv2/opencv.hpp" Mat srcImg = imread("00.png",CV_LOAD_IMAGE_COLOR); Mat copyImg = srcImg.clone(); cvtColor(srcImg,srcImg,CV_BGR2GRAY); threshold(srcImg,srcImg,100,255,CV_THRESH_BINARY);//确保黑中找白 vector<vector<Point>> contours; findContours(srcImg,contours,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_NONE);//最外层轮廓 drawContours(copyImg, contours, -1, Scalar(0, 255, 0), 2, 8); circle(copyImg,p1,3,Scalar(0,0,255),-1,8); double a0 = pointPolygonTest(contours[0], p1, true);//true表示点到轮廓的距离 double b0 = pointPolygonTest(contours[0], p1, false);//false表示计算点与轮廓的位置关系 cout << "a0=" << a0 << endl; cout << "b0=" << b0 << endl; imshow("contours",copyImg);
运行结果:
代码:2.轮廓矩的计算
#include "opencv2/opencv.hpp" Mat srcImg = imread("00.png", CV_LOAD_IMAGE_COLOR); Mat copyImg = srcImg.clone(); cvtColor(srcImg, srcImg, CV_BGR2GRAY); threshold(srcImg, srcImg, 100, 255, CV_THRESH_BINARY);//确保黑中找白 imshow("thresh", srcImg); vector<vector<Point>> contours; findContours(srcImg, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);//最外层轮廓 drawContours(copyImg, contours, -1, Scalar(0, 255, 0), 2, 8); Moments moments0 = moments(contours[0],false);//计算轮廓矩 cout << moments0.m00<< endl;//输出空间矩之一的m00 imshow("contours", copyImg);
运行结果:
代码:3.形状匹配---比较两个形状或轮廓间的相似度
#include "opencv2/opencv.hpp" Mat templateImg = imread("1.jpg", CV_LOAD_IMAGE_COLOR); Mat copyImg1 = templateImg.clone(); cvtColor(templateImg, templateImg, CV_BGR2GRAY); threshold(templateImg, templateImg, 100, 255, CV_THRESH_BINARY);//确保黑中找白 imshow("thresh1", templateImg); vector<vector<Point>> contours1; findContours(templateImg, contours1, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);//最外层轮廓 drawContours(copyImg1, contours1, -1, Scalar(0, 255, 0), 2, 8); Mat testImg = imread("2.jpg", CV_LOAD_IMAGE_COLOR); Mat copyImg2 = testImg.clone(); cvtColor(testImg, testImg, CV_BGR2GRAY); threshold(testImg, testImg, 100, 255, CV_THRESH_BINARY);//确保黑中找白 imshow("thresh2", testImg); vector<vector<Point>> contours2; findContours(testImg, contours2, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);//最外层轮廓 //3.形状匹配---比较两个形状或轮廓间的相似度 for (int i = 0; i < contours2.size();i++)//遍历待测试图像的轮廓 //返回此轮廓与模版轮廓之间的相似度,a0越小越相似 double a0 = matchShapes(contours1[0],contours2[i],CV_CONTOURS_MATCH_I1,0); cout << "模版轮廓与待测试图像轮廓" << i << "的相似度:" << a0 << endl;//输出两个轮廓间的相似度 if (a0<0.1)//如果此轮廓与模版轮廓的相似度小于0.1 drawContours(copyImg2, contours2, i, Scalar(0, 255, 0), 2, 8);//则在待测试图像上画出此轮廓 imshow("copyImg2", copyImg2); if (waitKey(0) == 27)//等待按键进行下一个轮廓,ESC则退出
运行结果:
|