点到轮廓的距离

点到轮廓的距离

简介

  • 点到轮廓的距离,对于计算轮廓在图像中的位置、两个轮廓之间的距离以及确定图像上某一点是否在轮廓内部具有重要的作用。

实现

OpenCV 4 提供了计算像素点距离轮廓最小距离的pointPolygonTest()函数

double cv::pointPolygonTest(InputArray contour, Point2f pt, bool measureDist)
  • contour:输入的轮廓,类型为 vector<Point>Mat
  • pt:需要计算与轮廓距离的像素点
  • measureDist:计算的距离是否具有方向性的标志。false 表示输出结果不具有方向性,只判断像素点与轮廓之间的位置关系,如果像素点在轮廓的内部,返回值为 -1,如果像素点在轮廓的边缘上,返回值为0,如果像素点在轮廓的外部,返回值为 -1;true 表示输出结果具有方向性,如果像素点在轮廓内部,返回值为正数,如果像素点在轮廓外部,返回值为负数

示例代码:

#include <opencv2/opencv.hpp>
#include <vector>
using namespace cv;
using namespace std;

int main()
{
    Mat img = imread("/home/kslas/OpenCV/regular.jpg");

    // 边缘检测
    Mat canny;
    Canny(img, canny, 80, 160, 3, false);
    // 膨胀运算
    Mat kernel = getStructuringElement(0, Size(3, 3));
    dilate(canny, canny, kernel);
    // 轮廓发现
    vector<vector<Point>> contours;
    vector<Vec4i> hierarchy;
    findContours(canny, contours, hierarchy, 0, 2);

    // 创建图像中的一个像素点并绘制图形
    Point point = Point(50, 300);
    circle(img, point, 2, Scalar(0, 0, 255), 2);

    // 多边形
    for (int i = 0; i < contours.size(); i++)
    {
        // 用最小外接矩形求取轮廓中心
        RotatedRect rrect = minAreaRect(contours[i]);
        Point2f center = rrect.center;
        circle(img, center, 2, Scalar(0, 255, 0), 2);  // 绘制圆心点

        // 轮廓外部点距离轮廓的距离
        double dis = pointPolygonTest(contours[i], point, true);
        // 轮廓内部点距离轮廓的距离
        double dis2 = pointPolygonTest(contours[i], center, true);
        // 输出点结果
        cout << "外部点距离轮廓距离: " << dis << endl;
        cout << "内部点距离轮廓距离: " << dis2 << endl;
    }
    imshow("img", img);
    waitKey(0);
    destroyAllWindows();
    return 0;
}

运行结果:

posted @ 2022-02-07 19:49  TNTksals  阅读(621)  评论(0编辑  收藏  举报