首页 文章

Numpy计算大型多光谱图像的corrcoef

提问于
浏览
2

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

#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)矩阵,该矩阵失败了 . 我需要的值是在这个巨大的矩阵的对角线之一 .

  • 有没有办法在使用corrcoef时避免产生这么多数据?将图像切成1000个像素批次并将它们送到corrcoef需要更长的时间,然后只使用单个像素!

  • python / numpy有没有任何批处理执行例程可以加快这个速度?

1 回答

  • 0

    我不知道如何使用corrcoef功能加快速度 . 但是,如果你知道corrcoeff函数只是计算Pearson's correlation coefficient,那么's easy to write your own code to do the same. Here'是一个能够做你想要的函数:

    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])
    

    这计算图像中一个像素和每个其他像素之间的相关系数 . 虽然如果你的最终目标是计算图像中每个像素和每个其他像素之间的相关性,你将耗尽内存(你需要大约1.5太字节来存储所有系数,对于给定的图像尺寸500 x 900 ) .

相关问题