Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Place an image on top of another image in a certain location

Tags:

c++

image

opencv

I'm looking for a way to place on image on top of another image at a set location.

I have been able to place images on top of each other using cv::addWeighted but when I searched for this particular problem, there wasn't any posts that I could find relating to C++.

Quick Example:

200x200 Red Square & 100x100 Blue Square

enter image description here& enter image description here

Blue Square on the Red Square at 70x70 (From top left corner Pixel of Blue Square)

enter image description here

like image 879
fakeaccount Avatar asked Apr 01 '15 16:04

fakeaccount


2 Answers

You can also create a Mat that points to a rectangular region of the original image and copy the blue image to that:

Mat bigImage = imread("redSquare.png", -1);
Mat lilImage = imread("blueSquare.png", -1);

Mat insetImage(bigImage, Rect(70, 70, 100, 100));
lilImage.copyTo(insetImage);

imshow("Overlay Image", bigImage);
like image 59
beaker Avatar answered Sep 19 '22 18:09

beaker


Building from beaker answer, and generalizing to any input images size, with some error checking:

cv::Mat bigImage = cv::imread("redSquare.png", -1);
const cv::Mat smallImage = cv::imread("blueSquare.png", -1);

const int x = 70;
const int y = 70;
cv::Mat destRoi;
try {
    destRoi = bigImage(cv::Rect(x, y, smallImage.cols, smallImage.rows));
}  catch (...) {
    std::cerr << "Trying to create roi out of image boundaries" << std::endl;
    return -1;
}
smallImage.copyTo(destRoi);

cv::imshow("Overlay Image", bigImage);

Check cv::Mat::operator()

Note: Probably this will still fail if the 2 images have different formats, e.g. if one is color and the other grayscale.

like image 35
Antonio Avatar answered Sep 16 '22 18:09

Antonio