在python中利用GDAL对tif文件进行读写的方法
作者:train_for_skills 时间:2022-03-25 08:08:07
利用GDAL库对tif影像进行读取
示例代码默认波段为[B、G、R、NIR的顺序,且为四个波段]
import gdal
def readTif(fileName):
dataset = gdal.Open(fileName)
if dataset == None:
print(fileName+"文件无法打开")
return
im_width = dataset.RasterXSize #栅格矩阵的列数
im_height = dataset.RasterYSize #栅格矩阵的行数
im_bands = dataset.RasterCount #波段数
im_data = dataset.ReadAsArray(0,0,im_width,im_height)#获取数据
im_geotrans = dataset.GetGeoTransform()#获取仿射矩阵信息
im_proj = dataset.GetProjection()#获取投影信息
im_blueBand = im_data[0,0:im_height,0:im_width]#获取蓝波段
im_greenBand = im_data[1,0:im_height,0:im_width]#获取绿波段
im_redBand = im_data[2,0:im_height,0:im_width]#获取红波段
im_nirBand = im_data[3,0:im_height,0:im_width]#获取近红外波段
写tif影像函数
#保存tif文件函数
import gdal
import numpy as np
def writeTiff(im_data,im_width,im_height,im_bands,im_geotrans,im_proj,path):
if 'int8' in im_data.dtype.name:
datatype = gdal.GDT_Byte
elif 'int16' in im_data.dtype.name:
datatype = gdal.GDT_UInt16
else:
datatype = gdal.GDT_Float32
if len(im_data.shape) == 3:
im_bands, im_height, im_width = im_data.shape
elif len(im_data.shape) == 2:
im_data = np.array([im_data])
else:
im_bands, (im_height, im_width) = 1,im_data.shape
#创建文件
driver = gdal.GetDriverByName("GTiff")
dataset = driver.Create(path, im_width, im_height, im_bands, datatype)
if(dataset!= None):
dataset.SetGeoTransform(im_geotrans) #写入仿射变换参数
dataset.SetProjection(im_proj) #写入投影
for i in range(im_bands):
dataset.GetRasterBand(i+1).WriteArray(im_data[i])
del dataset
来源:https://blog.csdn.net/t46414704152abc/article/details/77482747
标签:python,GDAL,tif
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
javascript-表格排序(降序/反序)实现介绍(附图)
2023-08-19 15:57:10
![](https://img.aspxhome.com/file/2023/8/55948_0s.gif)
谈谈设计师的发展
2009-03-17 18:20:00
python GUI模拟实现计算器
2023-01-08 22:20:40
![](https://img.aspxhome.com/file/2023/6/66906_0s.jpg)
Javascript——浅析注册事件
2008-08-19 12:44:00
CentOS 6.3安装配置nginx+php+mysql
2023-11-24 11:11:33
python中文文本切词Kmeans聚类
2023-06-01 18:35:57
简单的淡入淡出图片轮换效果
2009-05-22 18:38:00
正则表达式学习笔记
2008-04-15 07:44:00
Python reques接口测试框架实现代码
2023-10-07 12:47:08
![](https://img.aspxhome.com/file/2023/9/63219_0s.png)
python放大图片和画方格实现算法
2023-05-21 15:22:41
Python使用matplotlib简单绘图示例
2023-11-03 01:33:00
![](https://img.aspxhome.com/file/2023/2/62902_0s.jpg)
Python3实现的爬虫爬取数据并存入mysql数据库操作示例
2022-11-06 15:18:59
![](https://img.aspxhome.com/file/2023/1/66351_0s.png)
一篇文章带你入门Python正则表达式
2021-11-29 03:00:56
![](https://img.aspxhome.com/file/2023/6/70126_0s.jpg)
JavaScript程序执行顺序问题总结
2010-01-29 13:06:00
.NET 2.0 的压缩功能代码
2023-07-14 05:25:22
sql查询点滴记录
2012-01-05 19:07:49
JavaScript setTimeout和setInterval的使用方法 说明
2023-08-31 10:48:19
python 用pandas实现数据透视表功能
2022-04-23 02:49:40
![](https://img.aspxhome.com/file/2023/7/65217_0s.png)
Python利用matplotlib绘制约数个数统计图示例
2023-11-12 16:00:43
![](https://img.aspxhome.com/file/2023/4/63564_0s.png)
DD_belatedPNG,解决IE6不支持PNG绝佳方案
2009-04-27 16:30:00