c++ - 如何使用 Boost Within 检测点是否位于多边形内

标签 c++ boost

我正在尝试检测我的多边形可能的每个坐标。 (不是每次都是三角形,而是为了这个)。但是当我尝试检查每个可能的 x 和 y 时,我的程序根本无法工作。

我正在使用 https://www.boost.org/doc/libs/1_62_0/libs/geometry/doc/html/geometry/reference/algorithms/within/within_2.html

这是我的程序

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)

我不明白为什么。当我使用绘图来检查多边形是否正常工作时, 我有我的三角形 enter image description here

最佳答案

多边形的几何形状无效。

Model polygon reference

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/

相关文章:

c++ - 为什么在尝试使i = i * i时出现错误 “using uninitialized memory ' i'”和 “uninitialized local variable '我已使用”

c++ - 我可以将编译时字符串比较与 MPL 模板混合使用吗?

c++ - boost::property_tree XML pretty-print

c++ - 带有 boost.Asio 的多线程服务器

c++ - 列出我的计算机上安装的物理驱动器

c++ - 如何使用 boost.Qi 解析此类 XML 并调用名为标签的函数?

c++ - 如何在循环遍历 vector 时分配变量?

c++ - 我的 delete[] 有什么问题?

c++ - 我想根据任意掩码打包这些位

android - 在 Visual Studio 中创建新的 native 应用程序 (Android) 时出错