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】

相关推荐
Flittly5 分钟前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(3)TodoWrite (待办写入)
python·agent
千寻girling4 小时前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
databook8 小时前
探索视觉的边界:用 Manim 重现有趣的知觉错觉
python·动效
明月_清风9 小时前
Python 性能微观世界:列表推导式 vs for 循环
后端·python
明月_清风9 小时前
Python 性能翻身仗:从 O(n) 到 O(1) 的工程实践
后端·python
helloweilei1 天前
python 抽象基类
python
用户8356290780511 天前
Python 实现 PPT 转 HTML
后端·python
zone77391 天前
004:RAG 入门-LangChain读取PDF
后端·python·面试
zone77391 天前
005:RAG 入门-LangChain读取表格数据
后端·python·agent
树獭非懒2 天前
AI大模型小白手册|Embedding 与向量数据库
后端·python·llm