我正在尝试检测我的多边形可能的每个坐标。 (不是每次都是三角形,而是为了这个)。但是当我尝试检查每个可能的 x 和 y 时,我的程序根本无法工作。
这是我的程序
int main()
{
int x = 0;
int y = 0;
typedef boost::geometry::model::d2::point_xy<double> point_type;
boost::geometry::model::polygon<point_type> poly2;
boost::geometry::read_wkt("POLYGON((375 200,700 900,1100 190))", poly2);
for (x = 0; x < 1200; x++)
{
if (x > 1150)
{
x = 0;
y++;
}
else if (y > 1000)
exit(0);
else
{
point_type p(x, y);
bool check_covered = boost::geometry::within(p, poly2);
if (check_covered)
{
std::cout << "in" << std::endl;
}
}
}
return 0;
}
但是我没有输出。基本上,他们永远不会进入我的“if (check_covered)
”
最佳答案
多边形的几何形状无效。
Template parameter(s)
bool Closed
Default true
您可以通过 boost::geometry::is_valid
检查几何图形是否有效,对于您的多边形,它返回 false。
您可以添加最后一点:
"POLYGON((375 200,700 900,1100 190,375 200))"
或在within
检查之前调用boost::geometry::Correct(poly2)
(它将添加一个缺失点)。
这是一个现场演示,也使点迭代更加有效:
<强> Live On Coliru
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <iostream>
namespace bg = boost::geometry;
namespace bgm = bg::model;
using Point = bgm::d2::point_xy<double>;
int main()
{
bgm::polygon<Point> poly;
bgm::box<Point> box;
bg::read_wkt("POLYGON((375 200,700 900,1100 190,375 200))", poly);
bg::envelope(poly, box);
for (int x = box.min_corner().x(); x < box.max_corner().x(); ++x)
for (int y = box.min_corner().y(); y < box.max_corner().y(); ++y)
if (Point p(x,y); bg::within(p, poly)) {
std::cout << "in: " << bg::wkt(p) << std::endl;
}
}
打印
in: POINT(376 200)
in: POINT(376 201)
in: POINT(376 202)
in: POINT(377 200)
in: POINT(377 201)
in: POINT(377 202)
in: POINT(377 203)
in: POINT(377 204)
...
等等
关于c++ - 如何使用 Boost Within 检测点是否位于多边形内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67749999/