Conv2 to opencv

I am working on image processing and should know the conv2 equivalent from Matlab in C ++ OpenCV.
I found this link , but it does not meet my requirements.

The problem I am facing is that I need to convolve the Mat image with a two-dimensional double array, which does not match the link above.

Matlab code:

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

Where

Mx = {  
  {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}  
};

Thank.

+4
source share
2 answers

Decision

Use the OpenCV filter2D function .

Code example

//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);
+5
source

Here's my attempt, I'm not sure how accurate this is, but for a very small amount of test data, this worked for me:

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 );
}
+2

Source: https://habr.com/ru/post/1679019/


All Articles