Ask Your Question

# Filter 2D with even length kernels

I'm new to using OpenCV, and want to convolve an even length kernel, say 4 x 4 kernel with an image. Does filter 2D handle only odd length kernels?

Can anyone show me an example of how to use it with even length kernels for convolution?

Thanks H

edit retag close merge delete

## 2 answers

Sort by » oldest newest most voted

Filter2D() has no problem with even size kernel, but some other functions use it in their implementations do, like GaussianBlur (see more at link text). But I think this small obstacle is not the problem, you can rectify it by adding a new row (if kernel's row is even) or a new col (if kernel's col is even) with zero values to the first or the last row, (or column) of the kernel, depending on where you want the anchor point of the kernel is. Following is a small example of using filter2D function and its result:

#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
int main(int argc, char * argv[])
{
Mat kernel=(Mat_<float>(2,2)<<
0.0,-1.0,
1.0,0.0);
Mat src = imread(argv[1], CV_LOAD_IMAGE_GRAYSCALE);

Mat dst;

// anchor Point
Point anchor(kernel.cols - kernel.cols/2 - 1, kernel.rows - kernel.rows/2 - 1);

// flip the kernel
Mat fl_kernel;
int flip_code = -1; // -1-both axis, 0-x-axis, 1-y-axis
cv::flip(kernel, fl_kernel, flip_code);

int borderMode = BORDER_CONSTANT;
filter2D(src, dst, src.depth(), fl_kernel, anchor, borderMode);
cv::normalize(dst, dst, 0, 255, cv::NORM_MINMAX, CV_8U);
imshow("Filter2D demo-Source image",src);
imshow("Filter2D demo-Result image",dst);
waitKey(0);

return 0;
}

more

Hi, the same like odd length kernel, for example:

Mat ker=(Mat_<float>(2,2)<<
0.0,-1.0,
1.0,0.0);

filter2D(src,dst,prewit,CV_32FC,ker)//other paramemter set default


....................

more

## Stats

Asked: 2014-03-19 11:42:34 -0500

Seen: 2,019 times

Last updated: Mar 20 '14