使用OpenCV 实现matlab的padarray(A, padsize, ‘symmetric’)函数简单实现

  • Matlab文档padarray方法说明:
    B = padarray(A,padsize,padval) pads array A where padval specifies the value to use as the pad value. padarray uses the value 0 (zero) as the default. padval can be a scalar that specifies the pad value directly or one of the following text strings that specifies the method padarray uses to determine the values of the elements added as padding.
Value Meaning
‘circular’ Pad with circular repetition of elements within the dimension.
‘replicate’ Pad by repeating border elements of array.
‘symmetric’ Pad array with mirror reflections of itself.

Example 1
Add three elements of padding to the beginning of a vector. The padding elements, indicated by the gray shading, contain mirror copies of the array elements.
将三个填充元素添加到向量的开头。由灰色底纹指示的填充元素包含数组元素的镜像副本。

a = [ 1 2 3 4 ];
b = padarray(a,[0 3],'symmetric','pre')

结果:

b ==
3 2 1 1 2 3 4
% 前3个数字3 2 1为填充的元素
  • OpenCV 实现matlab的padarray(A, padsize, ‘symmetric’)函数:
    在C++代码中函数为
//Replicate the boundaries of the InImage image
//复制输入图像的边界
//symmetric:Pad array with mirror reflections of itself.
Mat PadArray(Mat Image, int RowPad, int ColPad)
{   
    int n = Image.rows;
    int m = Image.cols;
    Mat temp1 = Mat::zeros(n, m + ColPad * 2, Image.type());
    Mat temp2 = Mat::zeros(n + RowPad * 2, m + ColPad * 2, Image.type());
    for (int i = 0; i < ColPad; i++)
    {
        Image.col(i).copyTo(temp1.col(ColPad - 1 - i));
        Image.col(m - 1 - i).copyTo(temp1.col(m + ColPad + i));
    }
    Image.copyTo(temp1.colRange(ColPad, m + ColPad));
    for (int j = 0; j < RowPad; j++)
    {
        temp1.row(j).copyTo(temp2.row(RowPad - 1 - j));
        temp1.row(n - 1 - j).copyTo(temp2.row(n + RowPad + j));
    }
    temp1.copyTo(temp2.rowRange(RowPad, n + RowPad));
    return temp2;
}

main函数:

int main()
{
    Mat C = (Mat_<double>(3, 3) << 1, 2, 3, 4, 5, 6789);
    cout << C << endl << endl << endl;
    Mat B = PadArray(C, 1, 2);
    cout << B << endl;

    return 0;
}

运行结果:

在原有矩阵的周围进行镜像填充后的结果

使用OpenCV 实现matlab的padarray(A, padsize, ‘symmetric’)函数简单实现_第1张图片

  • 其他说明:
    关于padarray方法的其他重载函数以后再上传,这只是一个简单的实现。

你可能感兴趣的:(opencv)