新手的python学习笔记1
自己合成的23波段的影像,研究半天怎么弄到三维数组里面去,也是在网上找了很多篇大佬的代码,拼拼补补。啊啊啊啊啊我好笨:(
代码部分:
import numpy as np
#import matplotlib as mpl
#import matplotlib.pyplot as plt
import gdal
#import cv2
import os
#读文件
def image_read(imagepath, bandnum):
image = gdal.Open(imagepath) # 打开该图像
if image == None:
print(imagepath + "该影像不能打开!")
return
lie = image.RasterXSize # 栅格矩阵的列数
hang = image.RasterYSize # 栅格矩阵的行数
im_bands = image.RasterCount # 波段数
im_proj = image.GetProjection() # 获取投影信息
im_geotrans = image.GetGeoTransform() # 仿射矩阵
print('该tif:{}个行,{}个列,{}层波段, 取出第{}层波段.'.format(hang, lie, im_bands, bandnum))
band = image.GetRasterBand(bandnum) # Get the information of band num.
band_array = band.ReadAsArray(0,0,lie,hang) # Getting data from zeroth rows and 0 columns
# band_df = pd.DataFrame(band_array)
del image # 减少冗余
return band_array #, im_proj, im_geotrans
#读到三维数组中
def read_in_array(image_path, nband):
aa = image_read(image_path, 1)
bb = image_read(image_path, 2)
aa = np.array([aa,bb])
for n in range(3,nband+1):
bb = image_read(image_path, n)
cc = np.append(aa,bb) #先拼接成一个行向量
dim = aa.shape #获取原矩阵的维数
print('原矩阵维数:',dim)
aa = cc.reshape(dim[0]+1,dim[1],dim[2]) #再通过原矩阵的维数重新组合
print('维数:',aa.shape)
return aa
#文件目录
dir_path = r"E:\filter\little\NDVI" #路径名
image_name = "NDVI_test_2011" #文件名
image_path = os.path.join(dir_path, image_name)
out_array = read_in_array(image_path, 23) #波段是1-23
显示结果: