title: OpenCV zero padding
body: <p>I'm using <code>cvFilter2D</code> to filter images.  Its <a href="http://opencv.willowgarage.com/documentation/c/imgproc_image_filtering.html?highlight=filter2d" rel="nofollow">documentation</a> says:</p>
  
  <blockquote>
    <p>When the aperture is partially outside
    the image, the function interpolates
    outlier pixel values from the nearest
    pixels that are inside the image.</p>
  </blockquote>
  
  <p>While such extrapolation is fine in a majority of cases, I want to handle such outlier pixel values by <strong>zero padding</strong> (here's a 1D <a href="https://ccrma.stanford.edu/~jos/st/Zero_Padding.html" rel="nofollow">example</a> of what this means).</p>
  
  <p>Here's the way I'm currently doing it:</p>
  
  <pre><code>def do_filter(im, filt):
      N, M = cv.GetSize(filt)
      _, _, width, height = cv.GetImageROI(im)
      padded = cv.CreateImage((width + N, height + M), im.depth, im.nChannels)
      cv.SetZero(padded)
      roi = (N/2, M/2, width, height)
      cv.SetImageROI(padded, roi)
      cv.Copy(im, padded)
      cv.ResetImageROI(padded)
      cv.Filter2D(padded, padded, filt)
      result = cv.CreateImage(cv.GetSize(im), im.depth, im.nChannels)
      cv.SetImageROI(padded, roi)
      cv.Copy(padded, result)
      return result
  </code></pre>
  
  <p>Basically:</p>
  
  <ul>
  <li>Create padded image and copy contents from input</li>
  <li>Filter</li>
  <li>Trim away padded areas</li>
  </ul>
  
  <p>I don't like this because I have to do a lot of busy work just moving pixels around.  It's slow.</p>
  
  <p>Is there a better way to do zero padding when filtering?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>I've found <a href="http://opencv.willowgarage.com/documentation/c/imgproc_image_filtering.html?highlight=filter2d#cvCopyMakeBorder" rel="nofollow">cvCopyMakeBorder</a> which is slightly cleaner, but still copies the image, and is thus slow.</p>
  
  <p><strong>EDIT 2</strong></p>
  
  <p><a href="http://opencv.willowgarage.com/documentation/cpp/imgproc_image_filtering.html?highlight=filter2d#filter2D" rel="nofollow">cv::filter2D</a> in the C++ API does this.  I'd like to know if the old C API has the same functionality buried somewhere (I can't access the C++ API from Python, but I can access the C API from Python).</p>