利用Python计算遥感影像波段间的方差、协方差以及相关系数并保存到excel表格

利用Python计算遥感影像波段间的方差、协方差以及相关系数并保存到excel表格

1、读取遥感影像:gdal.Open(path)

if __name__ == '__main__':
    fn = r'*****.tif'
    img = gdal.Open(fn)
    path = r'******.xlsx' 
    data1 = np.zeros((img.shape[0],img.shape[0]),dtype='float32')    # 方差、协方差
    data2 = np.zeros((img.shape[0],img.shape[0]),dtype='float32')    # 相关系数
    #data3 = np.zeros(img.shape[0],img.shape[0])
    for ii in range(img.shape[0]):
        for jj in range(ii,img.shape[0]):    #对角阵,下半部分为0
            print("ii,jj : ",ii,jj)
            x = img[ii,:]
            y = img[jj,:]
            # 计算协方差矩阵
            #covxy = np.cov(x, y)
            #print("协方差矩阵:",covxy)
            covx = np.mean((x - x.mean()) ** 2)
            covy = np.mean((y - y.mean()) ** 2)
            print("covx = ",covx)
            print("covy = ",covy)
            # 这里计算的covxy等于上面的covxy[0, 1]和covxy[1, 0],三者相等
            covxy = np.mean((x - x.mean()) * (y - y.mean()))
            print("covxy = ",covxy)

            # 下面计算的是相关系数矩阵(和上面的协方差矩阵是类似的)
            coefxy = np.corrcoef(x, y)
            print("相关系数:",coefxy)
            # 将其存储到矩阵中
            if ii == jj :
                data1[ii,jj] = covx
                data2[ii,jj] = coefxy[0,0]
            else:
                data1[ii,jj] = covxy
                data2[ii,jj] = coefxy[0,1]

2、将数据保存为excel

注意:我用的anaconda3(python3.8)已经安装了pandas、xlsxwriter等函数库,无需额外进行安装。

import pandas as pd
index = ["band1","band2","band3","band4","band5","band6","band7","band8","band9","band10"]
df1 = pd.DataFrame(data1, index=index, columns=index)
df2 = pd.DataFrame(data2, index=index, columns=index)

dfs = {'Covariance':df1, 'Coefficient R':df2}
writer = pd.ExcelWriter(path, engine='xlsxwriter')
for sheet_name in dfs.keys():
    dfs[sheet_name].to_excel(writer, sheet_name=sheet_name) 
writer.save()

参考:
1、计算公式:https://blog.csdn.net/theonegis/article/details/85059105
2、excel读写与保存:https://blog.csdn.net/tz_zs/article/details/81137998

你可能感兴趣的:(Python,遥感图像处理,python,协方差,numpy,pandas)