【opencv学习之三十六】轮廓特征应用:计算点与轮廓距离

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/abcvincent/article/details/79275615

opencv实现了Contours与point的距离关系的计算使用起来很方便,不用自己再进行坐标转换计算了;示例代码如下:

void imgContoursPoint()//26轮廓与点的距离计算
{
    //1.查找轮廓前的预处理
    Mat srcImg = imread("D:/ImageTest/11.png");
    Mat copyImg = srcImg.clone();
    cvtColor(srcImg,srcImg,CV_BGR2GRAY);
    threshold(srcImg,srcImg,100,255,CV_THRESH_BINARY_INV );//
    imshow("thresh",srcImg);
    //2.查找轮廓
    vector<vector<Point>> contours;
    findContours(srcImg,contours,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_NONE);//最外层轮廓
    drawContours(copyImg, contours, -1, Scalar(0, 255, 0), 2, 8);
    //3.计算点到轮廓的距离与位置关系
    Point2f point1(230, 200);
    circle(copyImg,point1,3,Scalar(255,0,0),-1,8);
    double a0 = pointPolygonTest(contours[0], point1, true);//true表示点到轮廓的距离
    double b0 = pointPolygonTest(contours[0], point1, false);//false表示计算点与轮廓的位置关系-1表示外部,0在轮廓上,1在轮廓内
    cout << "a0=" << a0 << endl;
    cout << "b0=" << b0 << endl;

    Point2f point2(150, 200);
    circle(copyImg,point2,3,Scalar(0,0,255),-1,8);
    double a1 = pointPolygonTest(contours[0], point2, true);//true表示点到轮廓的距离
    double b1 = pointPolygonTest(contours[0], point2, false);//false表示计算点与轮廓的位置关系-1表示外部,0在轮廓上,1在轮廓内
    cout << "a1=" << a1 << endl;
    cout << "b1=" << b1 << endl;

    //    //添加文字
    QString strg1=QString::number(a0,10,3);
    QString str1=QString("a0=%1").arg(strg1);
    QByteArray cStr1 = str1.toLocal8Bit(); // 注意,这个QByteArray 对象一定要建立
    char *p1 = cStr1.data();
    putText(copyImg,p1, Point(30, 30),CV_FONT_HERSHEY_COMPLEX, 0.8, Scalar(255, 0, 0), 1, 8);

    QString strg2=QString::number(b0,10,3);
    QString str2=QString("b0=%1").arg(strg2);
    QByteArray cStr2 = str2.toLocal8Bit(); // 注意,这个QByteArray 对象一定要建立
    char *p2 = cStr2.data();
    putText(copyImg,p2, Point(30, 30*2),CV_FONT_HERSHEY_COMPLEX,0.8, Scalar(255, 0, 0), 1, 8);

    QString strg3=QString::number(a1,10,3);
    QString str3=QString("a1=%1").arg(strg3);
    QByteArray cStr3 = str3.toLocal8Bit(); // 注意,这个QByteArray 对象一定要建立
    char *p3 = cStr3.data();
    putText(copyImg,p3, Point(30, 30*3),CV_FONT_HERSHEY_COMPLEX, 0.8, Scalar(0, 0, 255), 1, 8);

    QString strg4=QString::number(b1,10,3);
    QString str4=QString("b1=%1").arg(strg4);
    QByteArray cStr4 = str4.toLocal8Bit(); // 注意,这个QByteArray 对象一定要建立
    char *p4 = cStr4.data();
    putText(copyImg,p4, Point(30, 30*4),CV_FONT_HERSHEY_COMPLEX, 0.8, Scalar(0, 0, 255), 1, 8);

    imshow("contours",copyImg);
    waitKey(0);
}
效果如下:



猜你喜欢

转载自blog.csdn.net/abcvincent/article/details/79275615