gdal复制某一区域的影像给另一栅格影像C++
时间: 2024-06-09 19:08:39 浏览: 17
你可以使用GDAL库中的函数来实现这个任务。以下是一个简单的C++代码示例,它将一个输入栅格影像的指定区域复制到一个新的输出栅格影像中:
```cpp
#include "gdal_priv.h"
int main() {
// Open input raster dataset
GDALDataset* inputDataset = (GDALDataset*) GDALOpen("input_raster.tif", GA_ReadOnly);
if (inputDataset == NULL) {
// Handle error
return 1;
}
// Define region of interest (ROI) in input raster
int xMin = 100; // Minimum X coordinate of ROI
int yMin = 200; // Minimum Y coordinate of ROI
int xMax = 300; // Maximum X coordinate of ROI
int yMax = 400; // Maximum Y coordinate of ROI
// Compute ROI dimensions
int roiWidth = xMax - xMin + 1;
int roiHeight = yMax - yMin + 1;
// Create output raster dataset
GDALDriver* driver = GetGDALDriverManager()->GetDriverByName("GTiff");
GDALDataset* outputDataset = driver->Create("output_raster.tif", roiWidth, roiHeight, inputDataset->GetRasterCount(), inputDataset->GetRasterDataType(1), NULL);
if (outputDataset == NULL) {
// Handle error
GDALClose(inputDataset);
return 1;
}
// Set output raster geotransform
double geotransform[6];
inputDataset->GetGeoTransform(geotransform);
geotransform[0] += xMin * geotransform[1];
geotransform[3] += yMin * geotransform[5];
outputDataset->SetGeoTransform(geotransform);
// Copy ROI from input raster to output raster
int bufferWidth = roiWidth;
int bufferHeight = roiHeight;
void* buffer = CPLMalloc(bufferWidth * bufferHeight * GDALGetDataTypeSize(inputDataset->GetRasterDataType(1)) / 8);
inputDataset->RasterIO(GF_Read, xMin, yMin, roiWidth, roiHeight, buffer, bufferWidth, bufferHeight, inputDataset->GetRasterDataType(1), inputDataset->GetRasterCount(), NULL, 0, 0, 0);
outputDataset->RasterIO(GF_Write, 0, 0, roiWidth, roiHeight, buffer, bufferWidth, bufferHeight, inputDataset->GetRasterDataType(1), inputDataset->GetRasterCount(), NULL, 0, 0, 0);
CPLFree(buffer);
// Close datasets
GDALClose(inputDataset);
GDALClose(outputDataset);
return 0;
}
```
请注意,此代码未进行错误处理和边界检查。您需要根据实际情况进行调整。此外,此代码仅复制单波段栅格影像。如果您需要处理多波段栅格影像,请修改代码以处理所有波段。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)