文章目录

一、简介

比较常见的判断点与多边形关系的算法有射线法、面积法、点线判断法和弧长法等,算法复杂度都为O(n),不过只有射线法可以正确用于凹多边形,其他3个只可以用于凸多边形。


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


InputArray contour,   输入的轮廓


Point2f

pt,        测试点


bool

measureDist     是否返回距离值,若为false(1在内面,0在边界上,-1在外部),true返回实际距离(double类型)


)


代码演示:

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

头文件 ​​quick_opencv.h​​:声明类与公共函数

#pragma once
#include <opencv2\opencv.hpp>
using namespace cv;

class QuickDemo {
public:
...
void points_polygons_Demo();
};

主函数调用该类的公共成员函数

#include <opencv2\opencv.hpp>
#include <quick_opencv.h>
#include <iostream>
using namespace cv;


int main(int argc, char** argv) {
Mat src = imread("D:\\Desktop\\maomao.png");
if (src.empty()) {
printf("Could not load images...\n");
return -1;
}
namedWindow("input", WINDOW_NORMAL);
imshow("input", src);

QuickDemo qk;
qk.points_polygons_Demo();
waitKey(0);
destroyAllWindows();
return 0;
}

二、效果演示

源文件 ​​quick_demo.cpp​​:实现类与公共函数

void QuickDemo::points_polygons_Demo() {
// 定义六边形
const int r = 100;
Mat src = Mat::zeros(r * 4, r * 4, CV_8UC1);
vector<Point2f> vert(6);
vert[0] = Point(3 * r / 2, static_cast<int>(1.34 * r));
vert[1] = Point(1 * r, 2 * r);
vert[2] = Point(3 * r / 2, static_cast<int>(2.68 * r));
vert[3] = Point(5 * r / 2, static_cast<int>(2.68 * r));
vert[4] = Point(3 * r, 2 * r);
vert[5] = Point(5 * r / 2, static_cast<int>(1.34 * r));

// 绘制六边形
for (int i = 0; i < 6; i++) {
line(src, vert[i], vert[(i + 1) % 6], Scalar(255), 3, 8);
}
imshow("src", src);

// 查找轮廓
vector<vector<Point>> contours;
vector<Vec4i> hieracrhy;
Mat src_copy = src.clone();
findContours(src_copy, contours, hieracrhy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));

// 计算图像所有点到轮廓的距离
float* dst_ptr;
Mat raw_dist = Mat::zeros(src_copy.size(), CV_32FC1);
for (int row = 0; row < src_copy.rows; row++) {
dst_ptr = raw_dist.ptr<float>(row);
for (int col = 0; col < src_copy.cols; col++) {
*dst_ptr++ = saturate_cast<float>(pointPolygonTest(contours[0], Point2f((float)col, (float)row), true));
}
}

// 获取点到轮廓的距离的最大最小值
double minValue, maxValue;
minMaxLoc(raw_dist, &minValue, &maxValue, 0, 0, Mat());
minValue = abs(minValue);
maxValue = abs(maxValue);

// 绘制距离映射图
float* dist_ptr;
Mat drawImg = Mat::zeros(src.size(), CV_8UC3);
for (int row = 0; row < drawImg.rows; row++) {
dist_ptr = raw_dist.ptr<float>(row);
for (int col = 0; col < drawImg.cols; col++) {
float distance_ = *dist_ptr++;
if (distance_ > 0) {
drawImg.at<Vec3b>(row,col)[0] = (uchar)((abs(1.0 - distance_ / maxValue)) * 255);
}
else if (distance_ < 0) {
drawImg.at<Vec3b>(row, col)[2] = (uchar)((abs(1.0 - distance_ / minValue)) * 255);
}
else {
drawImg.at<Vec3b>(row, col)[0] = (uchar)(255);
drawImg.at<Vec3b>(row, col)[1] = (uchar)(255);
drawImg.at<Vec3b>(row, col)[2] = (uchar)(255);
}
}
}
imshow("drawImg", drawImg);
}

OpenCV + CPP 系列(廿九)点与多边形的关系_#include