C++如何在指定位置将一张图片覆盖到另一张图片上面

11

我正在寻找一种将一个图像放置在另一个图像上特定位置的方法。

我已经使用cv::addWeighted将图像叠加在一起,但是当我搜索这个特定的问题时,我没有找到任何与C++相关的帖子。

快速示例:

200x200红色正方形和100x100蓝色正方形

enter image description here&enter image description here

将蓝色正方形放置于红色正方形上, 位置为70x70(从蓝色正方形左上角像素计算)

enter image description here

3个回答

11

您可以创建一个指向原始图像的矩形区域的Mat,并将蓝色图像复制到其中:

cv::Mat bigImage = cv::imread("redSquare.png", cv::IMREAD_UNCHANGED);
cv::Mat lilImage = cv::imread("blueSquare.png", cv::IMREAD_UNCHANGED);

cv::Mat insetImage(bigImage, cv::Rect(70, 70, 100, 100));
lilImage.copyTo(insetImage);
    
cv::imshow("Overlay Image", bigImage);

1
//将图像放置在位置Point(70,70);smallImg.copyTo(BigImage(cv::Rect(10, 10, smallImg.cols, smallImg.rows)));此图像 - Milind Morey
@MilindMorey 为什么在 Point(70,70) 中使用 Rect(10, 10, ...)?你是怎么找到 10 的? - Talha Ç

4

beaker的答案开始,通用于任何输入图像大小,并进行一些错误检查:

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);

请查看cv::Mat::operator()

注意:如果两个图像具有不同的格式,例如一个是彩色图像而另一个是灰度图像,则此方法仍可能失败。


0

建议的显式算法:

1- 读取两个图像。例如,bottom.ppm,top.ppm, 2- 读取叠加位置。例如,让“top.ppm”的所需左上角在“bottom.ppm”上的坐标为(x,y),其中0 < x < bottom.height()且0 < y < bottom.width(), 3- 最后,在顶部图像上嵌套循环,逐像素修改底部图像:

for(int i=0; i<top.height(); i++) {
    for(int j=0; j<top.width(), j++) {
        bottom(x+i, y+j) = top(i,j);
    }
}

返回底部图片。


1
你应该明确指出你提供的是伪代码。 - Antonio

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接