Conv2在opencv中

时间:2017-06-12 05:21:24

标签: c++ matlab opencv

我从事图像处理工作,需要在c ++ OpenCV中了解matlab的conv2等效内容。
我找到了this link,但它并不符合我的要求。

我面临的问题是我需要用2-D双数组卷积Mat图像,这不是上面链接中给出的情况。

matlab代码是:

url-pattern

其中

img = conv2(img1,Mx,'same')

谢谢。

2 个答案:

答案 0 :(得分:5)

<强>解决方案

使用OpenCV的filter2D功能。

代码示例

//initializes matrix
cv::Mat mat = cv::Mat::ones(50, 50, CV_32F); 

//initializes kernel
float  Mx[36] = { 0, 0, 0, 0, 0, 0 ,
     0, -0.0003, -0.0035, 0, 0.0035, 0.0003  ,
     0, -0.0090, -0.0903, 0, 0.0903, 0.0090  ,
     0, -0.0229, -0.2292, 0, 0.2292, 0.0229  ,
     0, -0.0090, -0.0903, 0, 0.0903, 0.0090  ,
     0, -0.0003, -0.0035, 0, 0.0035, 0.0003 
};
cv::Mat kernel(6, 6, CV_32F, Mx);

//convolove
cv::Mat dst;
cv::filter2D(mat, dst, mat.depth(), kernel);

答案 1 :(得分:2)

这是我的尝试,我不确定它是否准确,但对于非常少量的测试数据,它对我有用:

enum Conv2DShape {
    FULL,
    SAME,
    VALID,
};

Mat conv2D( const Mat& input, const Mat& kernel, const Conv2DShape shape ){
    Mat flipped_kernel;
    flip( kernel, flipped_kernel, -1 );

    Point2i pad;
    Mat result, padded;

    switch( shape ) {
        case SAME:
            padded = input;
            pad = Point2i( 0, 0 );
            break;

        case VALID:
            padded = input;
            pad = Point2i( kernel.cols - 1, kernel.rows - 1);
            break;

        case FULL:
            pad = Point2i( kernel.cols - 1, kernel.rows - 1);
            copyMakeBorder( input, padded, pad.y, pad.y, pad.x, pad.x, BORDER_CONSTANT );
            break;

        default:
            throw runtime_error("Unsupported convolutional shape");
    }

    Rect region = Rect( pad.x / 2, pad.y / 2, padded.cols - pad.x, padded.rows - pad.y);
    filter2D( padded, result , -1, flipped_kernel, Point(-1, -1), 0, BORDER_CONSTANT );

    return result( region );
}