使用开源库geos实现计算二维多边形中心点

近日遇到了求取二维多边形中心点(形心)的需求,虽然自己写代码也能实现,但是我认为能用开源库实现的功能就不重复做工,所以还是选择用已有开源库实现,新建一个函数调用geos的接口实现该功能,函数的参数一是多边形顶点坐标(自定义结构体,请忽略此处的结构体定义),二是计算出的中心点坐标,函数代码如下:

bool calDetectResultCentroid(const st_AIDetectorResult &stDetectResult, st_2DPt &st2DPtCenter)
{
    static const geos::geom::GeometryFactory* pGeomFactory = geos::geom::GeometryFactory::getDefaultInstance();

    //构建点序列
    geos::geom::CoordinateArraySequence geoCoordSequence;// = new geos::geom::CoordinateArraySequence();
    geoCoordSequence.add(geos::geom::Coordinate(stDetectResult.fPt1X, stDetectResult.fPt1Y));
    geoCoordSequence.add(geos::geom::Coordinate(stDetectResult.fPt2X, stDetectResult.fPt2Y));
    geoCoordSequence.add(geos::geom::Coordinate(stDetectResult.fPt3X, stDetectResult.fPt3Y));
    geoCoordSequence.add(geos::geom::Coordinate(stDetectResult.fPt4X, stDetectResult.fPt4Y));
    geoCoordSequence.add(geos::geom::Coordinate(stDetectResult.fPt1X, stDetectResult.fPt1Y)); //与第一个点相等

    geos::geom::LinearRing* pGeomLinearRing = pGeomFactory->createLinearRing(geoCoordSequence);
    if (!pGeomLinearRing->isSimple())
    {
        pGeomFactory->destroyGeometry(pGeomLinearRing);
        EASYLOG_PUSHLOG(ERROR_LOG_LEVEL, "LinearRing is not simple ");

        return false;
    }

    std::unique_ptr<geos::geom::Point> pPtCenter = pGeomLinearRing->getCentroid();
    st2DPtCenter.dX = pPtCenter->getX();
    st2DPtCenter.dY = pPtCenter->getY();

    pGeomFactory->destroyGeometry(pGeomLinearRing);

    return true;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值