title: How to get area of image with boundary conditions?
body: <p>Many functions in <code>scipy.ndimage</code> accept an optional <code>mode=nearest|wrap|reflect|constant</code> argument which determines how to handle cases in which the function needs some data from outside the area of the image (padding).  The padding is handled internally by <a href="https://github.com/scipy/scipy/blob/master/scipy/ndimage/src/ni_support.c#L198" rel="nofollow">NI_ExtendLine()</a> in native code.</p>
  
  <p>Instead of running a ndimage function on padded data, I would like to <em>just get the padded data</em> using the same choice of padding modes as ndimage uses.</p>
  
  <p>Here is an example (for mode=nearest only, assumes 2d image):</p>
  
  <pre><code>"""
  Get padded data.  Returns numpy array with shape (y1-y0, x1-x0, ...)
  Any of x0, x1, y0, y1 may be outside of the image
  """
  def get(img, y0, y1, x0, x1, mode="nearest"):
      out_img = numpy.zeros((y1-y0, x1-x0))
      for y in range(y0, y1):
          for x in range(x0, x1):
              yc = numpy.clip(y, 0, img.shape[0])
              xc = numpy.clip(x, 0, img.shape[1])
              out_img[y-y0, x-x0] = img[yc, xc]
      return out_img
  </code></pre>
  
  <p>This does the right thing, but is <em>slow</em> since it iterates one pixel at a time.</p>
  
  <p>What is the best (fastest, clearest, most pythonic) way to do this?</p>