title: Efficient way to handle boundary pixels when implementing arbitrary image algorithms in Python
body: <p>Image processing algorithms often require pixel values within a neighborhood of individual image locations. However, the neighborhood for boundary points is incomplete and needs special handling with various methods, e.g., mirror-reflecting, periodic, etc.</p>
  
  <p>For linear operation, an efficient way is to turn the algorithm into a kernel and do 2D convolution. The convolution routine usual has boundary handling methods built in.</p>
  
  <p>For arbitrary (non-linear) algorithms, one possibility is to <a href="https://stackoverflow.com/questions/5715220/what-is-usually-done-with-the-boundary-pixels-of-the-image">pad</a> the image first, gather all neighborhoods at once (e.g., with <a href="http://scikit-image.org/docs/dev/api/skimage.util.html#pad" rel="nofollow noreferrer">pad</a>+<a href="http://scikit-image.org/docs/0.8.0/api/skimage.util.html#view-as-windows" rel="nofollow noreferrer">neighbor</a>), and do your operation in a vectorized way. However, this can be memory heavy as the doc suggested.</p>
  
  <p>Loop through pixels and handle boundaries case by case is another way. But this can be slow in Python (though feasible in C/C++), and to provide all this mirror/periodic stuff seems to be cumbersome...</p>
  
  <p>How to do this efficiently (and perhaps Pythonic) when implementing you own algorithms in Python?  </p>
  
  <p>And is there some function that returns the neighborhood of a <a href="https://stackoverflow.com/questions/18793406/ndimage-or-skimage-functions-for-returning-pixel-neighborhoods">specified pixel</a>, and with specified boundary handling method?</p>