OpenCV 自学笔记30. 简单轮廓匹配的小例子

来源:互联网 发布:固定资产管理 源码 编辑:程序博客网 时间:2024/05/21 22:49

简单轮廓匹配的小例子

先用一个小例子入门:

OpenCV中提供了几个与轮廓相关的函数:

  • findContours():从二值图像中寻找轮廓
  • drawContours():绘制轮廓
  • matchShape():使用Hu矩进行轮廓匹配

下面是一个使用这些函数的小例子,测试图片为:

test3_c.jpg如下:

这里写图片描述

test4_c.jpg如下:

这里写图片描述

测试代码main.cpp如下:

#include <opencv2/opencv.hpp>#include <iostream>using namespace cv;using namespace std;int main() {    string path1 = "images/test3_c.jpg";    string path2 = "images/test4_c.jpg";    Mat image1 = imread(path1, IMREAD_GRAYSCALE);    Mat image2 = imread(path2, IMREAD_GRAYSCALE);    image1 = 255 - image1; // 反色    image2 = 255 - image2;    imshow("1", image1); // 显示反色后的图像    imshow("2", image2);    Mat image1_copy = imread(path1);    Mat image2_copy = imread(path2);    // CV_RETR_EXTERNAL 检测外轮廓    vector<vector<Point>> contours1, contours2;    findContours(image1, contours1, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);    findContours(image2, contours2, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);    drawContours(image1_copy, contours1, -1, Scalar(0, 255, 0), 2, 8);    drawContours(image2_copy, contours2, -1, Scalar(0, 255, 0), 2, 8);    imshow("轮廓1", image1_copy);    imshow("轮廓2", image2_copy);    //返回轮廓之间的匹配度, rate越小越相似      double rate = matchShapes(contours1[0], contours2[0], CV_CONTOURS_MATCH_I1, 0);    cout << rate << endl;    waitKey(0);    return 0;}

结果如下,其中上面两张是反色后的图片,下面两张是检测到的外轮廓(绿色线),两个轮廓的匹配度是0.0599843

这里写图片描述

先用个小例子入门吧

这里写图片描述

原创粉丝点击