Python:使用GDAL读写栅格数据/影像

Python有许多的库可以用来读写栅格数据,比如常见的GDAL、rasterio等,这里介绍一下如何使用GDAL来读写栅格数据,把读写栅格数据分别封装成了两个函数,直接复制使用即可:

读取栅格数据:

python 复制代码
from osgeo import gdal
from osgeo import ogr
from osgeo import osr
import numpy as np
# read data: nodata -> 0
def ReadData(filepath):  # 输入文件路径,tif格式
    gdal.AllRegister()
    ds = gdal.Open(filepath)
    clos = ds.RasterXSize  # 列数
    rows = ds.RasterYSize  # 行数
    bands = ds.RasterCount  # 波段数
    geotrans = ds.GetGeoTransform()  # 坐标系基准
    proj = ds.GetProjection()  # 投影
    data = ds.ReadAsArray() 
    data[data == data[0,0]] = 0  # nodata转为0,这里可以自己设置
    return [clos, rows, data, geotrans, proj]

写出栅格数据:

python 复制代码
def Write2Tiff(newpath,im_data,im_geotrans,im_proj):  # 输入写出路径;写出数据;写出数据的基准;投影
    if 'int8' in im_data.dtype.name:
        datatype = gdal.GDT_Int16
    elif 'int16' in im_data.dtype.name:
        datatype = gdal.GDT_Int16
    else:
        datatype = gdal.GDT_Float32
        
    if len(im_data.shape) == 3:
        im_bands, im_height, im_width = im_data.shape
    else:
        im_bands, (im_height, im_width) = 1, im_data.shape
        
    driver = gdal.GetDriverByName('GTiff')
    new_data = driver.Create(newpath, im_width, im_height, im_bands, datatype)
    new_data.SetGeoTransform(im_geotrans)
    new_data.SetProjection(im_proj)
    if im_bands == 1:
        new_data.GetRasterBand(1).WriteArray(im_data)
    else:
        for i in range(im_bands):
            new_data.GetRasterBand(i+1).WriteArray(im_data[i])
    del new_data

以上就是关于如何使用GDAL读写栅格数据。

更多内容关注公众号【GISerQ】

相关推荐
该用户已不存在2 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
站大爷IP4 小时前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python
用户83562907805110 小时前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
侃侃_天下10 小时前
最终的信号类
开发语言·c++·算法
c8i10 小时前
python中类的基本结构、特殊属性于MRO理解
python
echoarts10 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
liwulin050610 小时前
【ESP32-CAM】HELLO WORLD
python
Aomnitrix11 小时前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
Doris_202311 小时前
Python条件判断语句 if、elif 、else
前端·后端·python
Doris_202311 小时前
Python 模式匹配match case
前端·后端·python