我正在尝试计算一个像素与整个图像的相关系数 . 我有以下代码可行
#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 回答
我不知道如何使用corrcoef功能加快速度 . 但是,如果你知道corrcoeff函数只是计算Pearson's correlation coefficient,那么's easy to write your own code to do the same. Here'是一个能够做你想要的函数:
这计算图像中一个像素和每个其他像素之间的相关系数 . 虽然如果你的最终目标是计算图像中每个像素和每个其他像素之间的相关性,你将耗尽内存(你需要大约1.5太字节来存储所有系数,对于给定的图像尺寸500 x 900 ) .