title: Iteration multi-dimensional array in Python
body: <p>I want to compute some operation (GLCM) over an image using a sliding window. The code to achieve it is:</p>
  
  <pre><code>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]
  </code></pre>
  
  <p>It works but two for loops is very expensive. I want to increase the speed and so, looking around on the web, I tried to use the <em>as_stride</em> trick:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>To compute, for e.g., the GLCM for the first window:</p>
  
  <pre><code>glcm = greycoprops(greycomatrix(y[0,0], [1], [0], 256, symmetric=False, normed=True))[0][0]
  </code></pre>
  
  <p>I tried to apply for all the sliding window as:</p>
  
  <pre><code>glcm[:,:] = greycoprops(greycomatrix(y[:,:], [1], [0], 256, symmetric=False, normed=True))[0][0]
  </code></pre>
  
  <p>But in this case, the <code>y[:,:]</code> doesn't have <code>ndim==2</code> as <code>y[0,0]</code> but <code>ndim==4</code>, and so . I can't find a way to iterate in a smart way over all the subset keeping the <code>ndim == 2</code> (required by the <em>greycomatrix</em> function). </p>
  
  <p><strong>Edit</strong></p>
  
  <p>I tried to use ravel and work over 1D vector and so, just 1 for-loop. This is the code:</p>
  
  <pre><code>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])
  </code></pre>
  
  <p>The processing time increase...</p>