我之前也遇到过这个问题,这是一个很好的做坐标变换的方法.
从注GDAL文件:
GDALDataset :: GetProjectionRef()返回的坐标系描述了由GDALDataset :: GetGeoTransform()返回的仿射地理坐标转换所隐含的地理坐标坐标.
我们可以使用它与OGRCoordinateTransformation为我们进行转换.
基本上代码看起来像这样:
// Load up some dataset.
dataset = (GDALDataset *) GDALOpen( mapfile, GA_ReadOnly );
// Define Geographic coordinate system - set it to WGS84.
OGRSpatialReference *poSRS_Geog = new OGRSpatialReference();
poSRS_Geog->importFromEPSG( 4326 ); // WGS84
// Define Projected coordinate system - set to the GeoTransform.
const char *sProj = dataset->GetProjectionRef();
OGRSpatialReference *poSRS_Proj = new OGRSpatialReference( sProj );
// Set up the coordinate transform (geographic-to-projected).
OGRCoordinateTransformation *poCT_Geog2Proj;
poCT_Geog2Proj = OGRCreateCoordinateTransformation( poSRS_Geog, poSRS_Proj );
// Now everything is set up and we set transforming coordinates!
// Pass Lon/Lat coordinates to the Transform function:
double x = lon;
double y = lat;
poCT_Geog2Proj->Transform( 1, &x, &y );
// Now x and y variables will contain the X/Y pixel coordinates.
Run Code Online (Sandbox Code Playgroud)
这就是你可以在经度/纬度和像素坐标之间进行转换的方法.请注意,您可以使用数组Transform(),并将多个坐标转换为一起.第一个参数是要转换的坐标对的数量,第二个和第三个参数是指向x和y的指针.我只是在这里改造一对.
注意,设置逆变换同样容易:
// Set up the coordinate transform (projected-to-geographic).
OGRCoordinateTransformation *poCT_Proj2Geog;
poCT_Proj2Geog = OGRCreateCoordinateTransformation( poSRS_Proj, poSRS_Geog );
Run Code Online (Sandbox Code Playgroud)
我使用图像的仿射变换来计算一些样本纬度/经度。我遇到的唯一问题是,如果图像朝北,则在计算纬度/经度时需要将 geoTransform[2] 和 geTransform[4] 归零。
x = (int)Math.Abs(Math.Round((Latitude - geotransform[0]) / geotransform[1]));
y = (int)Math.Abs(Math.Round((Longitude - geotransform[3]) / geotransform[5]));
如果你想暴力破解它,你可以执行以下操作(我这样做了并且它有效,但这只是伪代码):
//Get the Pixel for the length and width, this portion is for the full image
pixelXSize = AbsoluteValue((latitudeAt(Zero)-(latitudeAt(Length)-1))/imageLength);
pixelYSize = AbsoluteValue((longitudeAt(Zero)-(LongitudeAt(Width)-1))/imageWidth);
//Calculate the x,y conversion for the points you want to calculate
x = AbsoluteValue((latitudeToConvert-latitudeAt(Zero))/pixelXSize);
y = AbsoluteValue((longitudeToConvert-longitudteAt(Zero))/pixelYSize);
这个答案可能会偏离一两个像素。如果您使用地理变换,朝北的变量可能会再次弄乱返回的答案。到目前为止,我只针对朝北的图像进行了测试。