C++如何用 gdal 读取两张图像后转为opencv类型的完整代码
时间: 2024-05-16 20:12:58 浏览: 163
以下是C++中使用GDAL库读取两张图像并将其转换为OpenCV类型的完整代码:
```cpp
#include <iostream>
#include "gdal/gdal_priv.h"
#include "gdal/cpl_conv.h"
#include "opencv2/opencv.hpp"
using namespace std;
using namespace cv;
int main()
{
// 读取第一张图像
GDALAllRegister();
GDALDataset* poDataset1 = (GDALDataset*)GDALOpen("image1.tif", GA_ReadOnly);
if (poDataset1 == NULL)
{
cout << "Failed to open image1.tif" << endl;
exit(1);
}
// 将第一张图像转换为OpenCV类型
int nChannels1 = GDALGetRasterCount(poDataset1);
int nRows1 = poDataset1->GetRasterYSize();
int nCols1 = poDataset1->GetRasterXSize();
Mat mat1(nRows1, nCols1, CV_8UC(nChannels1));
GDALRasterBand* poBand;
for (int i = 0; i < nChannels1; i++)
{
poBand = poDataset1->GetRasterBand(i + 1);
poBand->RasterIO(GF_Read, 0, 0, nCols1, nRows1, mat1.data + i, nCols1, nRows1, GDT_Byte, 1, NULL, 0, 0, 0);
}
// 读取第二张图像
GDALDataset* poDataset2 = (GDALDataset*)GDALOpen("image2.tif", GA_ReadOnly);
if (poDataset2 == NULL)
{
cout << "Failed to open image2.tif" << endl;
exit(1);
}
// 将第二张图像转换为OpenCV类型
int nChannels2 = GDALGetRasterCount(poDataset2);
int nRows2 = poDataset2->GetRasterYSize();
int nCols2 = poDataset2->GetRasterXSize();
Mat mat2(nRows2, nCols2, CV_8UC(nChannels2));
for (int i = 0; i < nChannels2; i++)
{
poBand = poDataset2->GetRasterBand(i + 1);
poBand->RasterIO(GF_Read, 0, 0, nCols2, nRows2, mat2.data + i, nCols2, nRows2, GDT_Byte, 1, NULL, 0, 0, 0);
}
// 显示第一张图像
namedWindow("Image1", WINDOW_NORMAL);
imshow("Image1", mat1);
// 显示第二张图像
namedWindow("Image2", WINDOW_NORMAL);
imshow("Image2", mat2);
waitKey(0);
return 0;
}
```
请注意,此代码需要在包含GDAL和OpenCV库的环境中编译。
阅读全文