轮廓距离

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

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

pointPolygonTest()函数原型:

double pointPolygonTest(InputArray contour,
                        Point2f pt,
                        bool measureDist
                        )
  • contour:输入的轮廓
  • pt:需要计算与轮廓距离的像素点
  • measureDist:计算的距离是否具有方向性的标志,当参数为true时,点在轮廓内部时,距离为正,点在轮廓外部时,距离为负

当参数为false时,只检测是否在轮廓内

该函数能够计算指定像素点距离轮廓的最小距离并以double类型的数据返回

第一个参数是表示轮廓,数据类型是vector< Point >或者Mat

第二个参数是需要计算与轮廓距离的像素点坐标

第三个参数是计算的距离是否具有方向性的标志,当参数为true时,点在轮廓内部时,距离为正,点在轮廓外部时,距离为负

当参数为false时,只检测是否在轮廓内

示例:

#include <iostream>
#include <opencv2/opencv.hpp>
#include <vector>
using namespace std;
using namespace cv;
int main()
{
    Mat img = imread("E:\\CLion\\opencv_xin\\SG\\SG_Rect.png");
    if (img.empty())
    {
        cout << "error" << endl;
        return -1;
    }
    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 = Point(250,200);
    circle(img,point,2,Scalar(0,255,0),2,8,0);
    //多边形
    for (int i = 0; i < contours.size(); ++i)
    {
        //用最小外接矩形求取轮廓中心
        RotatedRect rrect = minAreaRect(contours[i]);
        Point2f center = rrect.center;          //最小外接矩形的中心
        circle(img,center,2,Scalar(255,0,0),2,8,0);     //创建圆心点
        //轮廓外部点距离轮廓的距离
        double dis = pointPolygonTest(contours[i],point, true);
        //轮廓内部点距离轮廓的距离
        double dis2 = pointPolygonTest(contours[i],center, true);
        //输出结果
        cout << "外部点距离轮廓距离" << dis << endl;
        cout << "内部点距离轮廓距离" << dis2 << endl;
    }
    return 0;
}

\

results matching ""

    No results matching ""