title: Vectorizing 2D Convolutions in NumPy
body: <p>I know there are various optimized off-the-shelf functions available for performing 2D convolutions, but just for the sake of understanding, I am trying to implement my own 2D convolution function.  </p>
  
  <p>The following is what I done as of now:</p>
  
  <pre><code>    convoluted = []
      # TODO: Vectorize
      for i in range(0, M - m + 1):
          for j in range(0, N - n + 1):
              submatrix = x[i:i+m, j:j+n]
              convoluted.append(np.sum([submatrix*kernel]))
      convoluted = np.array(convoluted).reshape(M - m + 1, N - n + 1)
  </code></pre>
  
  <p>Note that <code>x</code> is the input image array, <code>(M, N)</code> is the shape of the input image, and <code>(m, n)</code> is the shape of the kernel used.</p>
  
  <p>The 2 explicit for-loops are <em>quite</em> slow.<br>
  Is there any way to vectorize this? Any help is appreciated<br>
  (I know that python list comprehension can be used, at least for the inner loop, but I'm looking for a faster method, if any) </p>