Skip to main content
 首页 » 编程设计

python之用于大型多光谱图像的 Numpy 计算 corrcoef

2025年05月04日798°冷暖

我正在尝试计算一个像素与整个图像的相关系数。 我有以下有效的代码

#load picture from serialized data 21 channels, ~500 x ~900 px 
pic=pickle.load(open('hyper.p','rb')) 
 
#prepare result table 
result=zeros((pic.shape[1],pic.shape[2])) 
 
#one pixel(10,10) from the image, all the channels 
pixel=pic[:,10,10] 
 
#for all pixels 
for x in xrange(pic.shape[1]): 
    for y in xrange(pic.shape[2]): 
            #calculate correlation coeficient between one pixel and current pixel 
        miniciurek = corrcoef(pixel,pic[:,x,y]) 
        result[x,y] = miniciurek[1,0] 
 
imshow(result) 
colorbar() 
show() 

上面的代码可以工作,但是需要很长时间才能完成, 我听说有一种更好的计算值的方法,一种可以一次性进行批量计算的方法,所以我想出了这样的解决方案:

#flattern the (21,~500,~900) matrix into a (21,500*900) matrix 
orka = pic.reshape((pic.shape[0],pic.shape[1]*pic.shape[2],)) 
 
#create a matrix full of pixels same as the chosen one 
pur = zeros((pic.shape[0],pic.shape[1]*pic.shape[2])) 
for a in xrange(pic.shape[0]): 
    pur[a,:].fill(krzywa1[a]) 
 
#at this point I have two (21,~300000) matrixes 
tempResult = corrcoef(pur ,orka ,0) 

我被困在这一点上,因为 corrcoef 试图分配一个 (600k,600k) 矩阵,但失败了。我需要的值位于这个巨大矩阵的对角线之一。

  1. 有什么方法可以避免在使用 corrcoef 时生成如此大量的数据?将图像分成 1000 个像素的批处理并将它们提供给 corrcoef 比仅使用单个像素需要更长的时间!

  2. python/numpy 是否有任何可以加快速度的批处理执行例程?

请您参考如下方法:

我不确定如何使用 corrcoef 函数加快速度。但是,如果您知道 corrcoeff 函数只是计算 Pearson's correlation coefficient ,很容易编写自己的代码来执行相同的操作。这是一个可以执行您想要的操作的函数:

import numpy as np 
 
def correlation(pixel, image): 
    c, m, n = image.shape 
    image = image.reshape(c, m * n) 
 
    pixel_mean = pixel.mean() 
    pixel_std = pixel.std() 
    means = image.mean(0) 
    stds = image.std(0) 
 
    # calculate the covariance between `pixel` and each image pixel 
    covs = np.dot(pixel - pixel_mean, image - means) / float(c) 
 
    # calculate Pearson's correlation coefficient 
    corr = covs / (pixel_std * stds) 
    return corr.reshape(m, n) 
 
# generate a random image to test 
c = 21 
m = 500 
n = 900 
image = np.random.randn(c, m, n) 
corr = correlation(image[:,10,10], image) 
 
# check an arbitrary point to make sure it works 
assert np.allclose(corr[302, 411],  
                   np.corrcoef(image[:,10,10], image[:,302,411])[0,1]) 

这会计算图像中一个像素与每个其他像素之间的相关系数。尽管如果您的最终目标是计算图像中每个像素与每个其他像素之间的相关性,您将耗尽内存(对于给定的图像大小 500 x 900,您需要大约 1.5 TB 的空间来存储所有系数).