Ask Your Question

Revision history [back]

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;
}

Result.