1. 程式人生 > >OpenCV實現Matlab中的conv2的功能

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')結果一致,其他兩種情況未檢驗!