OpenCV zero padding
I'm using cvFilter2D
to filter images. Its documentation says:
When the aperture is partially outside the image, the function interpolates outlier pixel values from the nearest pixels that are inside the image.
While such extrapolation is fine in a majority of cases, I want to handle such outlier pixel values by zero padding (here's a 1D example of what this means).
Here's the way I'm currently doing it:
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.ResetImageRO开发者_运维百科I(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
Basically:
- Create padded image and copy contents from input
- Filter
- Trim away padded areas
I don't like this because I have to do a lot of busy work just moving pixels around. It's slow.
Is there a better way to do zero padding when filtering?
EDIT
I've found cvCopyMakeBorder which is slightly cleaner, but still copies the image, and is thus slow.
EDIT 2
cv::filter2D 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).
If you don't mind losing a the external 1-pixel thick edge of your image, you can set it to 0, and then the "interpolation" will give you what you want.
I'm not sure about Python, but the in C/C++, you can specify that you want a certain constant to be used for the "undefined" pixels. Set this constant to 0, and you'll have your problem solved. I'm sure Python has something similar as well.
精彩评论