我正在寻找一种将一个图像放置在另一个图像上特定位置的方法。
我已经使用cv::addWeighted
将图像叠加在一起,但是当我搜索这个特定的问题时,我没有找到任何与C++
相关的帖子。
快速示例:
200x200
红色正方形和100x100
蓝色正方形
&
将蓝色正方形放置于红色正方形上, 位置为70x70
(从蓝色正方形左上角像素计算)
您可以创建一个指向原始图像的矩形区域的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);
从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);
注意:如果两个图像具有不同的格式,例如一个是彩色图像而另一个是灰度图像,则此方法仍可能失败。
建议的显式算法:
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);
}
}
返回底部图片。