1. tiff数据
read TIFF image
#?读取tiff数据需要GDAL库
from osgeo import gdal
def Read_tiff(file_path):
# img_file_path: 栅格数据路径
# return: 返回投影,几何信息,和转换后的数组
????dataset?=?gdal.Open(img_file_path)??#?读取栅格数据
# 判断是否读取到数据
if dataset is None:
print('Unable to open *.tif')
sys.exit(1) # 退出
projection = dataset.GetProjection() # 投影信息
geotrans = dataset.GetGeoTransform() # 几何信息
im_width = dataset.RasterXSize #栅格矩阵的列数
im_height = dataset.RasterYSize #栅格矩阵的行数
im_bands = dataset.RasterCount #波段数
???#?读取dataset
img_array = dataset.ReadAsArray()
return im_width,im_height,im_bands,projection, geotrans, img_array
#?输出为tiff格式
def Write_tiff(tiff_file, im_proj, im_geotrans, data_array):
if 'int8' in data_array.dtype.name:
datatype = gdal.GDT_Int16
elif 'int16' in data_array.dtype.name:
datatype = gdal.GDT_Int16
else:
datatype = gdal.GDT_Float32
?
if len(data_array.shape) == 3:
im_bands, im_height, im_width = data_array.shape
else:
im_bands, (im_height, im_width) = 1, data_array.shape
?
driver = gdal.GetDriverByName("GTiff")
dataset = driver.Create(tiff_file, im_width, im_height, im_bands, datatype)
dataset.SetGeoTransform(im_geotrans)
dataset.SetProjection(im_proj)
?
if im_bands == 1:
dataset.GetRasterBand(1).WriteArray(data_array)
else:
for i in range(im_bands):
dataset.GetRasterBand(i + 1).WriteArray(data_array[i])
del dataset
2.nc数据
read NC image
# nc格式的遥感数据比较常见,在使用之间需要确定该nc文件的数据组织格式
import netCDF4
from?netCDF4?import?Dataset
def Read_nc(path, name):
nc_obj = Dataset(path)
# 查看文件中的变量
print(nc_obj.variables.keys())
# for i in nc_obj.variables.keys():
# print(i)
# 获取到变量的信息
info = nc_obj.variables[name]
# 获取到变量的值
data = nc_obj.variables[name][:]
????return?data
3.hdf数据
read HDF image
from pyhdf import SD
from pyhdf.SD import SD, SDC
def Read_hdf(path,name):
f_data = SD(path, SDC.READ)
????#?name为获取到变量名称
data = f_data.select(name)[:, :]
????data?=?data.astype(np.float)
return data
?# 注意hdf数据读取时不能包含中文路径
?# 除此之外,hdf数据还可以通过h5py库读取
4.mat数据
read MAT image
# mat数据格式是Matlab的数据存储的标准格式
from?scipy.io?import?loadmat
def Read_mat(path,name):
dataset = loadmat(path)
data = dataset[name]
print(data.shape)
return data
# 在python中使用函数savemat保存文件
5.grib数据
read GRIB image
#?grib数据相对少见,例如再分析数据JRA55
# pygrib?需要选择合适兼容的python版本
import pygrib as pg
def Read_grib(path, var, num):
dataset = pg.open(path) # path文件路径
data = dataset.select(name= var)[num].values
????#?var为读取的变量名称,可以在panoply中查看
????#?values?获取到值
?? # 返回数组
return data
?
#?举个例子:读取JRA55下行长波辐射数据
path?=?r'F:\JRA55(2000-2020)\JRA55\2017_2020\DLW\fcst_phy2m.205_dlwrf.reg_tl319.2018120100_2018123121.grib'????
data?=?Read_grib(path,?'Downward?long-wave?radiation?flux',0)
#?获取到的结果是 20181201天00:00的下行长波数据
6.RAW数据
read RAW image
import numpy as np
def Read_RAW(path,rows,cols,channels):
????#?rows,cols为数据的行数列数,channels为数据通道数
????#?注意RAW文件中的数据类型,否则会读取错误
data = np.fromfile(path, dtype=np.uint16)
????data?=?data.reshape(rows,?cols, channels)
data = data.astype(np.float)
????return?data
更多精彩请关注
|