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】

相关推荐
凛铄linshuo10 分钟前
爬虫简单实操2——以贴吧为例爬取“某吧”前10页的网页代码
爬虫·python·学习
牛客企业服务13 分钟前
2025年AI面试推荐榜单,数字化招聘转型优选
人工智能·python·算法·面试·职场和发展·金融·求职招聘
charlie11451419124 分钟前
深入理解Qt的SetWindowsFlags函数
开发语言·c++·qt·原理分析
胡斌附体25 分钟前
linux测试端口是否可被外部访问
linux·运维·服务器·python·测试·端口测试·临时服务器
likeGhee1 小时前
python缓存装饰器实现方案
开发语言·python·缓存
whoarethenext1 小时前
使用 C++/Faiss 加速海量 MFCC 特征的相似性搜索
开发语言·c++·faiss
项目題供诗1 小时前
黑马python(二十五)
开发语言·python
读书点滴1 小时前
笨方法学python -练习14
java·前端·python
慌糖2 小时前
RabbitMQ:消息队列的轻量级王者
开发语言·javascript·ecmascript
笑衬人心。2 小时前
Ubuntu 22.04 修改默认 Python 版本为 Python3 笔记
笔记·python·ubuntu