【C++】【GADL】读取栅格数据(tif),遍历数组

every blog every motto: Light tomorrow with today.

0. 前言

简单记录下用c++读取栅格数据,遍历数组

1. 正文

1.1 参数说明

图像坐标轴:
在这里插入图片描述

CPLErr GDALRasterBand::RasterIO (   GDALRWFlag eRWFlag, // 读入还是写入
int     nXOff, // 起始坐标(左上角x值)
int     nYOff, // 起始坐标(左上角y值)
int     nXSize, // (读入/写入)图像的宽
int     nYSize, // (读入/写入)图像的高
void * pData, // 指向(读入/写入)的指针
int     nBufXSize, // 缓冲区宽(真正显示的宽)
int     nBufYSize, // 缓冲区高(真正显示的高)
GDALDataType    eBufType, // (读入/写入)的数据的类型
int     nPixelSpace, // 像素间隔,默认0
int     nLineSpace  // 像素行间隔,默认0
)

1.2 读取

#include<iostream>
#include<algorithm>
#include<vector>
#include "gdal_priv.h"

BYTE * loadRasterData()
{
    
    		
		const char * fileName = "D:\\Programme\\Viual Studio\\C++\\learning\\point_to_line\\Project1_test\\images\\grid.tiff";
		GDALAllRegister(); // 注册驱动
		// 支持中文路径
		CPLSetConfigOption("GDAL_FILENAME_IS_UTF8", "NO");
		// 读取数据
		GDALDataset * pDataset = (GDALDataset *)GDALOpen(fileName, GA_ReadOnly);

		// 判断是否读取成功
		if (NULL == pDataset)
		{
    
    
			cout << "未能成功读取!" << endl;
			return 0;
		}

	// 图像波段信息
	GDALRasterBand * pRasterBand;
	pRasterBand = pDataset->GetRasterBand(1); // 第一个波段指针
	CPLString DataType = GDALGetDataTypeName(pRasterBand->GetRasterDataType()); // 获取数据类型名字
	int imgX = pRasterBand->GetXSize();
	int imgY = pRasterBand->GetYSize();
	cout << "x,y分别为:" << imgX << "  " << imgY << endl;
	cout << "数据类型:" << DataType << endl;
	cout << "-------------------------------------------------------" << endl;

	// 读取数据
	int size_m = sizeof(int)*imgX*imgY;
	cout << size_m << endl;
	BYTE * mat = (BYTE *)CPLMalloc(size_m); // 分配内存
	pRasterBand->RasterIO(GF_Read, 0, 0, imgX, imgY, mat, imgX, imgY, GDT_Byte, 0, 0);

	// 打印数组
	for (int i = 0; i < imgX; i++)
	{
    
    
		for (int j = 0; j < imgY; j++)
		{
    
    
			cout << (int) mat[i*imgX+j] << " ";
		}
	}

	return mat; // 返回数组的首地址
}


int main()
{
    
    
	// 加载数据
	BYTE *mat = loadRasterData();

}

参考文献

[1] https://blog.csdn.net/weixin_39190382/article/details/108111601
[2] https://blog.csdn.net/liminlu0314/article/details/8301585
[3] https://blog.csdn.net/liminlu0314/article/details/7072224

猜你喜欢

转载自blog.csdn.net/weixin_39190382/article/details/107999112