|   | 1 |  initial version  | 
// Mat_<uchar> is only here for ease of demonstration
Mat_<uchar> in(3,3); inner << 1,2,3,4,5,6,7,8,9;
Mat out = Mat(in.rows+2, in.cols+2, in.type());
copyMakeBorder(in,out,1,1,1,1,BORDER_REPLICATE);
cerr << inner << endl;
cerr << outer << endl;
[  1,   2,   3;
   4,   5,   6;
   7,   8,   9]
[  1,   1,   2,   3,   3;
   1,   1,   2,   3,   3;
   4,   4,   5,   6,   6;
   7,   7,   8,   9,   9;
   7,   7,   8,   9,   9]
|   | 2 |  No.2 Revision  | 
you can use the builtin ( but undocumented ;[ ) copyMakeBorder() (from core):
// Mat_<uchar> is only here for ease of demonstration
Mat_<uchar> in(3,3); inner << 1,2,3,4,5,6,7,8,9;
Mat out = Mat(in.rows+2, in.cols+2, in.type());
copyMakeBorder(in,out,1,1,1,1,BORDER_REPLICATE);
cerr << inner << endl;
cerr << outer << endl;
[  1,   2,   3;
   4,   5,   6;
   7,   8,   9]
[  1,   1,   2,   3,   3;
   1,   1,   2,   3,   3;
   4,   4,   5,   6,   6;
   7,   7,   8,   9,   9;
   7,   7,   8,   9,   9]
|   | 3 |  No.3 Revision  | 
you can use the builtin ( but undocumented ;[ ) copyMakeBorder() (from core):
// Mat_<uchar> is only here for ease of demonstration
Mat_<uchar> in(3,3); inner(3,3); inner << 1,2,3,4,5,6,7,8,9;
Mat out outer = Mat(in.rows+2, in.cols+2, in.type());
copyMakeBorder(in,out,1,1,1,1,BORDER_REPLICATE);
Mat(inner.rows+2, inner.cols+2, inner.type());
copyMakeBorder(inner,outer ,1,1,1,1,BORDER_REPLICATE);
cerr << inner << endl;
cerr << outer << endl;
[  1,   2,   3;
   4,   5,   6;
   7,   8,   9]
[  1,   1,   2,   3,   3;
   1,   1,   2,   3,   3;
   4,   4,   5,   6,   6;
   7,   7,   8,   9,   9;
   7,   7,   8,   9,   9]