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

简单轮廓匹配的小例子

先用一个小例子入门:

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

这里写图片描述

先用个小例子入门吧

这里写图片描述

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值