【发布时间】:2015-01-16 09:38:47
【问题描述】:
我想使用滑动窗口对图像进行一些运算 (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]
但在这种情况下,y[:,:] 没有 ndim==2 作为 y[0,0] 而是 ndim==4,等等。我找不到以智能方式迭代所有保留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])
处理时间增加...
【问题讨论】:
标签: python numpy multidimensional-array glcm