convolution: conv2 matlab to opencv



如果我在中设置输入图像和内核

cv::Mat conv2D(cv::Mat input,cv::Mat kernel){
printf("nINPUT [ %d x %d ]n",input.rows,input.cols);
cout << input <<endl;
printf("nKERNEL [ %d x %d ]n",kernel.rows,kernel.cols);
cout << kernel <<endl;
cv::Mat flipped_kernel;
cv::Point2i pad;
cv::Mat result;
cv::Mat padded;
cv::Point anchor(kernel.cols -kernel.cols/2 -1,kernel.rows -kernel.rows/2 -1 );
cv::flip( kernel, flipped_kernel, -1 );
printf("nFLIPPED KERNEL [ %d x %d ]n",flipped_kernel.rows,flipped_kernel.cols);
cout << flipped_kernel <<endl;
pad = cv::Point2i( kernel.cols - 1, kernel.rows - 1);
cv::copyMakeBorder( input, padded, pad.y, pad.y, pad.x, pad.x, cv::BORDER_CONSTANT,cv::Scalar(0) );
cv::Rect region = cv::Rect( pad.x / 2, pad.y / 2, padded.cols - pad.x, padded.rows - pad.y);
cv::filter2D( padded, result , padded.depth(), flipped_kernel, anchor, 0, cv::BORDER_CONSTANT );
cv::Mat out = result( region );
printf("nOUT [ %d x %d ]n",out.rows,out.cols);
cout << out <<endl;
return out;
}

输出不同于:

conv2(input,kernel)

在网上阅读,有人告诉翻转是错误的,但其他人没有告诉。所以我使用了一个对旋转对称的矩阵作为核,结果仍然是错误的。如何在c++中执行二维卷积和二维互相关?

问题a是我通过了CV_32F类型的opencv垫,这给了我错误的结果,我用方法将图像转换为CV_8UC1

input.convertTo(输入,CV_8UC1(;flipped_kernel.convertTo(输入,CV_8UC1(;

并在操作后更改输出类型:

out.convertTo(输入,CV_32F(;

所以这个方法有效!

相关内容

  • 没有找到相关文章