Opencv(C++)笔记--cv::pointPolygonTest()判断点的位置

1--cv::pointPolygonTest()用途

        判断当前位置的点在多边形轮廓的相对位置,即内部、边缘和外部;

2--OpenCV API

Opencv(C++)笔记--cv::pointPolygonTest()判断点的位置_第1张图片

double cv::pointPolygonTest(cv::InputArray contour, cv::Point2f pt, bool measureDist)

        measureDist = flase时,内部返回+1,边缘返回0,外部返回-1;

        measureDist = true时,返回的是有符号的距离;

3--代码实例

# include 
# include 
# include 
# include 

int main(int argc, char** argv){
    const int r = 100;
    cv::Mat src = cv::Mat::zeros(r * 4, r * 4, CV_8UC1);

    // 定义六边形的六个点
    std::vector vert(6);
    vert[0] = cv::Point(3 * r / 2, static_cast(1.34 * r));
    vert[1] = cv::Point(1 * r, 2 * r);
    vert[2] = cv::Point(3 * r / 2, static_cast(2.866 * r));
    vert[3] = cv::Point(5 * r / 2, static_cast(2.866 * r));
    vert[4] = cv::Point(3 * r, 2 * r);
    vert[5] = cv::Point(5 * r / 2, static_cast(1.34 * r));
    // 绘制六边形
    for(int i = 0; i < 6; i++){
        cv::line(src, vert[i], vert[(i + 1) % 6], cv::Scalar(255, 255, 255), 3, 8, 0);
    }

    std::vector> contours;
    std::vector hierachy;
    cv::Mat csrc;
    src.copyTo(csrc);
    cv::findContours(csrc, contours, hierachy, cv::RETR_TREE, cv::CHAIN_APPROX_SIMPLE, cv::Point(0, 0)); // 检测轮廓
    cv::Mat raw_dist = cv::Mat::zeros(csrc.size(), CV_32FC1);
    for (int row = 0; row < raw_dist.rows; row++){
        for (int col = 0; col < raw_dist.cols; col++){
            // measureDist = flase时,内部返回+1,边缘返回0,外部返回-1
            // measureDist = true时,返回的是有符号的距离
            double dist = cv::pointPolygonTest(contours[0], cv::Point2f(static_cast(col), static_cast(row)), true);
            raw_dist.at(row, col) = static_cast(dist);
        }
    }

    double minValue, maxValue;
    cv::minMaxLoc(raw_dist, &minValue, &maxValue, 0, 0, cv::Mat());
    cv::Mat drawImg = cv::Mat::zeros(src.size(), CV_8UC3);
    for (int row = 0; row < drawImg.rows; row++){
        for (int col = 0; col < drawImg.cols; col++){
            float dist = raw_dist.at(row, col);
            if (dist > 0){ // 当前坐标在内部
                drawImg.at(row, col)[0] = (uchar)(abs((dist / maxValue)) * 255);
            }
            else if (dist < 0){ // 当前坐标在外部
                drawImg.at(row, col)[2] = (uchar)(abs(dist / minValue) * 255);
            }
            else {
                drawImg.at(row, col)[0] = (uchar)(abs(255 - dist));
                drawImg.at(row, col)[1] = (uchar)(abs(255 - dist));
                drawImg.at(row, col)[2] = (uchar)(abs(255 - dist));
            }
        }
    }
    cv::imshow("src", src);
    cv::imshow("test", drawImg);

    cv::waitKey(0);
    return 0;
}

Opencv(C++)笔记--cv::pointPolygonTest()判断点的位置_第2张图片

 

你可能感兴趣的:(Opencv(C++)学习笔记,c++,opencv,开发语言)