opencv::点多边形测试
阅读原文时间:2023年07月10日阅读:3

点多边形测试
测试一个点是否在给定的多边形内部,边缘或者外部

double pointPolygonTest(
InputArray contour, // 输入的轮廓
Point2f pt, // 测试点
bool measureDist // 是否返回距离值,如果是false,1表示在内面,0表示在边界上,-1表示在外部,true返回实际距离
)

步骤
构建一张400x400大小的图片, Mat::Zero(, , CV_8UC1)
画上一个六边形的闭合区域line
发现轮廓
对图像中所有像素点做点 多边形测试,得到距离,归一化后显示。

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

vector<Point2f> vert();  
vert\[\] = Point( \* r / , static\_cast<int>(1.34\*r));  
vert\[\] = Point( \* r,  \* r);  
vert\[\] = Point( \* r / , static\_cast<int>(2.866\*r));  
vert\[\] = Point( \* r / , static\_cast<int>(2.866\*r));  
vert\[\] = Point( \* r,  \* r);  
vert\[\] = Point( \* r / , static\_cast<int>(1.34\*r));

for (int i = ; i < ; i++) {  
    line(src, vert\[i\], vert\[(i + ) % \], Scalar(), , , );  
}  
// 画一个六边型  
imshow("input\_win", src);

vector<vector<Point>> contours;  
vector<Vec4i> hierachy;  
Mat csrc;  
src.copyTo(csrc);  
//边界发现  
findContours(csrc, contours, hierachy, RETR\_TREE, CHAIN\_APPROX\_SIMPLE, Point(, ));  
Mat raw\_dist = Mat::zeros(csrc.size(), CV\_32FC1);  
for (int row = ; row < raw\_dist.rows; row++) {  
    for (int col = ; col < raw\_dist.cols; col++) {  
        double dist = pointPolygonTest(contours\[\], Point2f(static\_cast<float>(col), static\_cast<float>(row)), true);  
        raw\_dist.at<float>(row, col) = static\_cast<float>(dist);  
    }  
}

double minValue, maxValue;  
minMaxLoc(raw\_dist, &minValue, &maxValue, , , Mat());  
Mat drawImg = Mat::zeros(src.size(), CV\_8UC3);  
for (int row = ; row < drawImg.rows; row++) {  
    for (int col = ; col < drawImg.cols; col++) {  
        float dist = raw\_dist.at<float>(row, col);  
        if (dist > ) {  
            //内部  
            drawImg.at<Vec3b>(row, col)\[\] = (uchar)(abs(1.0 - (dist / maxValue)) \* );  
        }  
        else if (dist < ) {  
            //外部  
            drawImg.at<Vec3b>(row, col)\[\] = (uchar)(abs(1.0 - (dist / minValue)) \* );  
        }  
        else {  
            //边缘  
            drawImg.at<Vec3b>(row, col)\[\] = (uchar)(abs( - dist));  
            drawImg.at<Vec3b>(row, col)\[\] = (uchar)(abs( - dist));  
            drawImg.at<Vec3b>(row, col)\[\] = (uchar)(abs( - dist));  
        }  
    }  
}

imshow("output\_win", drawImg);

waitKey();  
return ;  

}

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章