基于python和GDAL实现遥感影像重采样(改变分辨率)
很多时候都需要改变已经影像的分辨率,这里自己动手研究了一下相关原理,并进行了实现,以后可以很方便地改变影像的分辨率。影像重采样核心重采样的核心是影像的坐标范围不变,改变影像像元的大小,来实现像元个数的增减,即分辨率的改变。像元的面积*像元个数=固定值像元大小变为原来的1/2时,影像的像元数量变为原来的四倍。代码实现from osgeo import gdal, gdalconstimport os
·
很多时候都需要改变已经影像的分辨率,这里自己动手研究了一下相关原理,并进行了实现,以后可以很方便地改变影像的分辨率。
影像重采样核心
重采样的核心是影像的坐标范围不变,改变影像像元的大小,来实现像元个数的增减,即分辨率的改变。
像元的面积*像元个数=固定值
像元大小变为原来的1/2时,影像的像元数量变为原来的四倍。
代码实现
from osgeo import gdal, gdalconst
import os
import numpy as np
def resampling(source_file, target_file, scale=1.0):
"""
影像重采样
:param source_file: 源文件
:param target_file: 输出影像
:param scale: 像元缩放比例
:return:
"""
dataset = gdal.Open(source_file, gdalconst.GA_ReadOnly)
band_count = dataset.RasterCount # 波段数
if band_count == 0 or not scale > 0:
print("参数异常")
return
cols = dataset.RasterXSize # 列数
rows = dataset.RasterYSize # 行数
cols = int(cols * scale) # 计算新的行列数
rows = int(rows * scale)
geotrans = list(dataset.GetGeoTransform())
print(dataset.GetGeoTransform())
print(geotrans)
geotrans[1] = geotrans[1] / scale # 像元宽度变为原来的scale倍
geotrans[5] = geotrans[5] / scale # 像元高度变为原来的scale倍
print(geotrans)
if os.path.exists(target_file) and os.path.isfile(target_file): # 如果已存在同名影像
os.remove(target_file) # 则删除之
band1 = dataset.GetRasterBand(1)
data_type = band1.DataType
target = dataset.GetDriver().Create(target_file, xsize=cols, ysize=rows, bands=band_count,
eType=data_type)
target.SetProjection(dataset.GetProjection()) # 设置投影坐标
target.SetGeoTransform(geotrans) # 设置地理变换参数
total = band_count + 1
for index in range(1, total):
# 读取波段数据
print("正在写入" + str(index) + "波段")
data = dataset.GetRasterBand(index).ReadAsArray(buf_xsize=cols, buf_ysize=rows)
out_band = target.GetRasterBand(index)
out_band.SetNoDataValue(dataset.GetRasterBand(index).GetNoDataValue())
out_band.WriteArray(data) # 写入数据到新影像中
out_band.FlushCache()
out_band.ComputeBandStats(False) # 计算统计信息
print("正在写入完成")
del dataset
del target
if __name__ == "__main__":
source_file = r"E:\商丘yx\相交4.tiff"
target_file = r"E:\商丘yx\相交411.tiff"
resampling(source_file, target_file, scale=1.1)
target_file = r"E:\商丘yx\相交05.tiff"
resampling(source_file, target_file, scale=0.5)
结果展示
改变前
增大分辨率后
减小分辨率后
不适用场景
经过多轮测试对比发现,在以下情况时使用GDAL进行重采样会出现采样后的影像旋转、大小不一致的问题:
- 影像未定义坐标系
- 影像大小为0.0001这种特别小的情况
更多推荐
所有评论(0)