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】

相关推荐
duapple25 分钟前
Golang基于反射的ioctl实现
开发语言·后端·golang
Dxy12393102161 小时前
Python 条件语句详解
开发语言·python
龙泉寺天下行走1 小时前
Python 翻译词典小程序
python·oracle·小程序
践行见远1 小时前
django之视图
python·django·drf
love530love2 小时前
Windows避坑部署CosyVoice多语言大语言模型
人工智能·windows·python·语言模型·自然语言处理·pycharm
prinrf('千寻)3 小时前
MyBatis-Plus 的 updateById 方法不更新 null 值属性的问题
java·开发语言·mybatis
m0_555762903 小时前
Qt缓动曲线详解
开发语言·qt
掘金-我是哪吒4 小时前
分布式微服务系统架构第132集:Python大模型,fastapi项目-Jeskson文档-微服务分布式系统架构
分布式·python·微服务·架构·系统架构
揽你·入怀4 小时前
数据结构:ArrayList简单实现与常见操作实例详解
java·开发语言
AA-代码批发V哥4 小时前
Math工具类全面指南
java·开发语言·数学建模