pointPolygonTest多边形检测

根据官网提供的程序

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include 
#include 
#include 

using namespace cv;
using namespace std;

/** @function main */
int main(int argc, char** argv)
{
    /// 创建一个图形 
    const int r = 100;
    Mat src = Mat::zeros(Size(4 * r, 4 * r), CV_8UC1);

    /// 绘制一系列点创建一个轮廓:
    vector vert(6);

    vert[0] = Point(1.5*r, 1.34*r);
    vert[1] = Point(1 * r, 2 * r);
    vert[2] = Point(1.5*r, 2.866*r);
    vert[3] = Point(2.5*r, 2.866*r);
    vert[4] = Point(3 * r, 2 * r);
    vert[5] = Point(2.5*r, 1.34*r);

    for (int i = 0; i <= 5; i++)
    {

        cout << "vert[i]" << vert[i]</// 在src内部绘制
    for (int j = 0; j < 6; j++)
    {
        line(src, vert[j], vert[(j + 1) % 6], Scalar(255), 3, 8);//画线不取余时,报错,显示vector out of range
    }

    /// 得到轮廓
    vector<vector > contours; 
    vector hierarchy;
    Mat src_copy = src.clone();

    findContours(src_copy, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE);

    /// 计算到轮廓的距离
    Mat raw_dist(src.size(), CV_32FC1);

    for (int j = 0; j < src.rows; j++)
    {
        for (int i = 0; i < src.cols; i++)
        {
            raw_dist.at<float>(j, i) = pointPolygonTest(contours[0], Point2f(i, j), true);

        }
    }

    double minVal; double maxVal;
    minMaxLoc(raw_dist, &minVal, &maxVal, 0, 0, Mat());
    minVal = abs(minVal); maxVal = abs(maxVal);

    cout << minVal << endl;
    cout << maxVal << endl;


    /// 图形化的显示距离
    Mat drawing = Mat::zeros(src.size(), CV_8UC3);

    for (int j = 0; j < src.rows; j++)
    {
        for (int i = 0; i < src.cols; i++)
        {
            if (raw_dist.at<float>(j, i) < 0)//表示在轮廓线外部,因为pointPolygonTest里的measureDist为true
            {
                drawing.at(j, i)[0] = 255 - (int)abs(raw_dist.at<float>(j, i)) * 255 / minVal;


            }
            else if (raw_dist.at<float>(j, i) > 0)
            {
                drawing.at(j, i)[1] = 255 - (int)abs(raw_dist.at<float>(j, i) )* 255 / maxVal;
            }
            else
            {
                drawing.at(j, i)[0] = 255; drawing.at(j, i)[1] = 255; drawing.at(j, i)[2] = 255;
            }
        }
    }

    /// 创建窗口显示结果
    char* source_window = "Source";
    namedWindow(source_window, WINDOW_AUTOSIZE);
    imshow(source_window, src);
    namedWindow("Distance", WINDOW_AUTOSIZE);
    imshow("Distance", drawing);

    waitKey(0);
    return(0);
}

pointPolygonTest多边形检测_第1张图片
根据图中所示,在轮廓线内的为绿色,因为是通道1,外面是蓝色,通道为0

不知道为什么,画线不取余时,即vert[(j + 1) % 6改成vert[(j + 1) 报错,显示vector out of range 。希望过路大神能告知。
/// 在src内部绘制
for (int j = 0; j < 6; j++)
{
line(src, vert[j], vert[(j + 1) % 6], Scalar(255), 3, 8);
}

你可能感兴趣的:(opencv-3-0)