clarkk
clarkk

Reputation: 27685

Crop image and then add border

Mat img = imread(input);

// Crop a part out of the image
img = img(Rect(x, y, width, height));

// Add a white border around the cropped image
int border = 100;
copyMakeBorder(img, img, border, border, border, border, BORDER_CONSTANT, Scalar(0, 255, 255));

I have a problem.. I need to add a border to an image..

But first I have to crop out some content..

The problem is when adding the border afterwards the content I just cropped out comes back..

Is it possible somehow to "commit" the changes after the cropping before the borders are added?

Upvotes: 1

Views: 873

Answers (1)

sturkmen
sturkmen

Reputation: 3550

You should use a new Mat and clone the ROI.

#include "opencv2/highgui.hpp"
using namespace cv;

int main(int argc, char* argv[])
{
    Mat img = imread(argv[1]);

    // Crop a part out of the image
    Mat cropped = img(Rect(10, 10, 100, 100)).clone();

    // Add a white border around the cropped image
    int border = 100;
    copyMakeBorder(cropped, cropped, border, border, border, border, BORDER_CONSTANT, Scalar(0, 255, 255));
    imshow("cropped", cropped);
    waitKey();
    return 0;
}

Upvotes: 3

Related Questions