Ask Your Question

Revision history [back]

You can use the function copyMakeBorder

#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include "iostream"

using namespace cv;
using namespace std;

int main(int argc, char* argv[])
{
    Mat src = imread(argv[1]);
    if (src.empty())
    {
        cout << endl
             << "ERROR! Unable to read the image" << endl
             << "Press a key to terminate";
        cin.get();
        return 0;
    }

    imshow("Source image", src);

    Mat dst;

    Size dst_dims = Size(256,256); 

    int top = ( dst_dims.height - src.rows ) / 2;
    int bottom = ( ( dst_dims.height + 1 ) - src.rows ) / 2;
    int left = ( dst_dims.width - src.cols ) / 2;
    int right = ( ( dst_dims.width + 1 ) - src.cols ) / 2;

    copyMakeBorder(src, dst, top, bottom, left, right, BORDER_CONSTANT, Scalar(127,127,127));

    imshow("New image", dst);
    waitKey();

    return 0;
}