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;
}
已经测试了,三个参数的运行结果都和MATLAB中的运行结果相同。原博文:http://blog.csdn.net/windydreams/article/details/8110112
测试结果:
如上图:A和B两个矩阵。
conv2(A,B,'valid')运行的结果:
conv2(A,B,'full')运行的结果:
以上是MATLAB中的结果:
下面是opencv中的结果:
Mat A = (Mat_<float>(4,4)<<16,2,3,13,5,11,10,8,9,7,6,12,4,14,15,1);
Mat B = (Mat_<float>(3,3)<<0.8000,0.1000,-0.6000,0.3000,0.5000,0.7000,-0.4000,0,-0.2000);
Mat C = conv2(A,B,CONVOLUTION_VALID);
Mat D = conv2(A,B,CONVOLUTION_FULL);
cout.setf(ios::fixed);
cout<<"valid:"<<endl<<C<<endl<<endl<<"full:"<<endl<<D<<endl;
结果:
和MATLAB中的运行结果一致,CONVOLUTION_SAME参数原博主已经验证。