地理信息系统中常用最小外接矩形(MBR)表示一个地理要素的大致位置,地理系统中的许多操作,例如空间查询,空间检索,都需要用最小外接矩形建立RTree,以提升运算速度。
gdal中使用OGREnvelope定义最小外接矩阵,该类通过MinX,MaxX,MinY,MaxY四个成员变量表示矩阵的最小X坐标,最大X坐标,最小Y坐标,最大Y坐标,其形成的外接矩形为{(MinX, MinY), (MinX, MaxY), (MaxX, MaxY), (MaxX, MinY)}。
gdal获取最小外接矩形的接口为void OGRGeometry::getEnvelope( OGREnvelope * psEnvelope )。在gdal中,几何图形都从OGRGeometry派生,所有几何图形都支持getEnvelope接口。
下图是polyon,multipolygon的最小外接示意图(红色边框为最小外接矩阵):
实现代码如下:
#include <gdal.h>
#include <ogrsf_frmts.h>
#include <ogr_geometry.h>
#include <cstdio>
#include <vector>
int main(int argc, char **argv)
{
OGRPoint A(-5.76,4.35);
OGRPoint B(-7.36,1.65);
OGRPoint C(-3.6,-0.47);
OGRPoint D(1.68,1.65);
OGRPoint E(-3.06,0.71);
OGRPoint F(-2.74,4.31);
std::vector<OGRPoint> points1{A, B, C, D, E, F, A};
OGRLinearRing ring1;
for (auto &point : points1) {
ring1.addPoint(&point);
}
OGRPolygon poly1;
poly1.addRing(&ring1);
OGREnvelope en;
poly1.getEnvelope(&en);
printf("%f, %f, %f, %f \n", en.MinX, en.MinY, en.MaxX, en.MaxY);
printf("P: %f, %f\n", en.MinX, en.MinY);
printf("Q: %f, %f\n", en.MinX, en.MaxY);
printf("R: %f, %f\n", en.MaxX, en.MaxY);
printf("S: %f, %f\n", en.MaxX, en.MinY);
OGRPoint G(-5.74264,-4.92212);
OGRPoint H(-8.0497,-7.86299);
OGRPoint I(-3.08064,-10.44894);
OGRPoint J(2.6997,-7.48271);
OGRPoint K(0.36729,-5.91086);
OGRPoint L(-4.09473,-6.95031);
OGRPoint M(-3.48628,-8.11652);
OGRPoint N(-0.5454,-7.9137);
OGRPoint O(-1.6609,-6.26579);
std::vector<OGRPoint> points2{G, H, I, J, K, G};
OGRLinearRing ring2;
for (auto &point : points2) {
ring2.addPoint(&point);
}
OGRPolygon poly2;
poly2.addRing(&ring2);
std::vector<OGRPoint> points3{L, M, N, O, L};
OGRLinearRing ring3;
for (auto &point : points3) {
ring3.addPoint(&point);
}
OGRPolygon poly3;
poly3.addRing(&ring3);
OGRMultiPolygon mploy;
mploy.addGeometry(&poly2);
mploy.addGeometry(&poly3);
mploy.getEnvelope(&en);
printf("%f, %f, %f, %f \n", en.MinX, en.MinY, en.MaxX, en.MaxY);
printf("T: %f, %f\n", en.MinX, en.MinY);
printf("U: %f, %f\n", en.MinX, en.MaxY);
printf("V: %f, %f\n", en.MaxX, en.MaxY);
printf("W: %f, %f\n", en.MaxX, en.MinY);
return 0;
}
对于点,MinX=MaxX=x,MinY=MaxY=y,所以,对于OGRPoint,调用getEnvelope,返回值为{x, y, x, y}(对应{Minx, MinY, MaxX, MaxY})。