我想使用滑动窗口在图像上计算一些操作(GLCM)。实现它的代码是:
import numpy as np
from skimage.feature import greycomatrix, greycoprops
from numpy.lib.stride_tricks import as_strided
image = np.arange(36).reshape((6,6))
window = 5
result = np.zeros(image.shape)
for i in xrange(window/2,image.shape[0]-window/2):
for j in xrange(window/2,image.shape[1]-window/2):
sample = image[i-(window/2):i+(window/2)+1, j - (window/2):j+(window/2)+1]
glcm = greycomatrix(sample, [1], [0], 256, symmetric=False, normed=True)
result[i,j] = greycoprops(glcm, 'contrast')[0, 0]
它可以工作,但是两个 for 循环非常昂贵。我想提高速度,所以在网上环顾四周,我尝试使用as_stride技巧:
from numpy.lib.stride_tricks import as_strided
image = np.arange(36).reshape((6,6))
window = 5
y = as_strided(image,shape=(image.shape[0] - window + 1,\
image.shape[1] - window + 1,) +\
(window,window), strides=image.strides * 2)
例如,计算第一个窗口的 GLCM:
glcm = greycoprops(greycomatrix(y[0,0], [1], [0], 256, symmetric=False, normed=True))[0][0]
我尝试将所有滑动窗口申请为:
glcm[:,:] = greycoprops(greycomatrix(y[:,:], [1], [0], 256, symmetric=False, normed=True))[0][0]
但在这种情况下, they[:,:]
没有ndim==2
asy[0,0]
但是ndim==4
,以及 so 。我找不到一种方法来以智能方式迭代所有保留ndim == 2
(greycomatrix函数所需)的子集。
编辑
我尝试使用 ravel 并处理一维向量,因此只有 1 个 for 循环。这是代码:
a = y.ravel()
print a.shape
glcm=np.zeros(a.shape[0]/(window*window))
for i in np.arange(a.shape[0]/(window*window)):
glcm[i] = greycoprops(greycomatrix(a[i*25:i*25+25].reshape(5,5), [1], [0], 256, symmetric=False, normed=True))[0][0]
result= glcm.reshape(y.shape[0],y.shape[1])
处理时间增加...