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);
}