OpenCV实现Matlab中的conv2的功能

参考的帖子:http://www.opencv.org.cn/forum/viewtopic.php?t=5385

对此处代码只做了一点修改。

#pragma once
enum ConvolutionType {
 /* Return the full convolution, including border */
 CONVOLUTION_FULL,
 
 /* Return only the part that corresponds to the original image */
 CONVOLUTION_SAME,

 /* Return only the submatrix containing elements that were not influenced by the border */
 CONVOLUTION_VALID
};

Mat conv2(const Mat &img, const Mat& ikernel, ConvolutionType type)
{
 Mat dest;
 Mat kernel;
 flip(ikernel,kernel,-1);

 Mat source = img;
 if(CONVOLUTION_FULL == type)
 {
  source = Mat();
  const int additionalRows = kernel.rows-1, additionalCols = kernel.cols-1;
  copyMakeBorder(img, source, (additionalRows+1)/2, additionalRows/2, (additionalCols+1)/2, additionalCols/2, BORDER_CONSTANT, Scalar(0));
 }
 Point anchor(kernel.cols - kernel.cols/2 - 1, kernel.rows - kernel.rows/2 - 1);
 int borderMode = BORDER_CONSTANT;
 filter2D(source, dest, img.depth(), kernel, anchor, 0, borderMode);
 
 if(CONVOLUTION_VALID == type)
 {
  dest = dest.colRange((kernel.cols-1)/2, dest.cols - kernel.cols/2).rowRange((kernel.rows-1)/2, dest.rows - kernel.rows/2);
 }
 return dest;
}

经验证,CONVOLUTION_SAME,与Matlab中的conv2(a,b,'same')结果一致,其他两种情况未检验!

你可能感兴趣的:(图像处理)