susanswj的个人博客分享 http://blog.sciencenet.cn/u/susanswj

博文

[转载]python使用gdal实现影像重采样(上采样和下采样)

已有 4956 次阅读 2020-5-21 13:14 |系统分类:科研笔记|文章来源:转载

gdal实现影像重采样至高分辨率(30m->15m)

'''
Created on 2020年5月21日

@author: wjshen
'''
from osgeo import gdal
import os
path=r"D:\test"
os.chdir(path)
in_ds=gdal.Open("p122r043.tif")
in_band=in_ds.GetRasterBand(1)
xsize=in_band.XSize
ysize=in_band.YSize
geotrans=list(in_ds.GetGeoTransform())
geotrans[1]/=2#像元宽度变为原来的0.5倍
geotrans[5]/=2#像元高度变为原来的0.5倍
#重采样后的影像
if os.path.exists('resampled.tif'):#如果已存在同名影像
    os.remove('resampled.tif')#则删除之
out_ds=in_ds.GetDriver().Create('resampled.tif',xsize*2,ysize*2,1,in_band.DataType)#创建一幅重采样后的影像的句柄,行列数都变成原来的2倍
out_ds.SetProjection(in_ds.GetProjection())#设置投影坐标
out_ds.SetGeoTransform(geotrans)#设置地理变换参数
data=in_band.ReadAsArray(buf_xsize=xsize*2, buf_ysize=ysize*2)#使用更大的缓冲读取影像,与重采样后影像行列对应
out_band=out_ds.GetRasterBand(1)
out_band.WriteArray(data)#写入数据到新影像中
out_band.FlushCache()
out_band.ComputeBandStats(False)#计算统计信息
out_ds.BuildOverviews('average',[1,2,4,8,16,32])#构建金字塔
del out_ds#删除句柄
del in_ds
print("This process has succeeded!")

gdal实现重采样至更低分辨率(30m->60m)


from osgeo import gdal
import os
import numpy as np
path=r"D:\TEST"
os.chdir(path)
image_name='p122R043.tif'
in_ds=gdal.Open(image_name)
geotrans=list(in_ds.GetGeoTransform())
geotrans[1]*=2#像元宽度变为原来的两倍
geotrans[5]*=2#像元高度也变为原来的两倍
in_band=in_ds.GetRasterBand(1)
xsize=in_band.XSize
ysize=in_band.YSize
x_resolution=int(xsize/2)#影像的行列都变为原来的一半
y_resolution=int(ysize/2)
if os.path.exists('LowerResolutionImage.tif'):#如果存在重采样后的影像,则删除之
    os.remove('LowerResolutionImage.tif')
out_ds=in_ds.GetDriver().Create('LowerResolutionImage.tif',x_resolution,y_resolution,1,in_band.DataType)#创建一个构建重采样影像的句柄
out_ds.SetProjection(in_ds.GetProjection())#设置投影信息
out_ds.SetGeoTransform(geotrans)#设置地理变换信息
data=np.empty((y_resolution,x_resolution),np.int)#设置一个与重采样影像行列号相等的矩阵去接受读取所得的像元值
in_band.ReadAsArray(buf_obj=data)
out_band=out_ds.GetRasterBand(1)
out_band.WriteArray(data)
out_band.FlushCache()
out_band.ComputeStatistics(False)#计算统计信息
out_ds.BuildOverviews('average',[1,2,4,8,16,32])#构建金字塔
del in_ds#删除句柄
del out_ds
print("This process has succeeded!")



https://blog.sciencenet.cn/blog-726435-1234254.html


收藏 IP: 112.1.54.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...
扫一扫,分享此博文

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-4-20 14:12

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部