当两幅图像尺寸相同时,给图像加上水印效果其实很简单,就是简单的将一幅图像加到另一幅图像上(两幅图像乘以一定的系数就可以控制相加的效果):
#include<opencv2/core/core.hpp> #include<opencv2/highgui/highgui.hpp> using namespace cv; int main() { Mat image1 = imread("D:/picture/images/boldt.jpg"); Mat image2 = imread("D:/picture/images/rain.jpg"); waitKey(0); Mat result; //调用addWeighted函数 //addWeighted(image1,0.7,image2,0.9,0.,result); //利用它的重载函数可以简单的写为 result= 0.7*image1+0.9*image2; namedWindow("output"); imshow("output",result); waitKey(0); return 0; }
当图像的尺寸不同时,需要在较大的图像上定义一个与较小的图像尺寸相同的感兴趣的区域ROI,把较小的图像加到感兴趣区域上:
#include<opencv2/core/core.hpp> #include<opencv2/highgui/highgui.hpp> using namespace cv; int main() { Mat image1 = imread("D:/picture/images/boldt.jpg"); Mat logo = imread("D:/picture/images/logo.bmp"); Mat imageROI = image1(Rect(50,50,logo.cols,logo.rows)); addWeighted(imageROI,1.0,logo,1.0,0.,imageROI); imshow("结果图像",image1); waitKey(0); return 0; }
这样做有一个明显的问题,就是ROI区域的像素点有可能超过255,导致饱和而显示出白色。怎么办呢?可以通过掩码来完成,使得在感兴趣区域点,只有较小图像的内容,而没有较大图像的内容:
#include<opencv2/core/core.hpp> #include<opencv2/highgui/highgui.hpp> using namespace cv; int main() { Mat image1 = imread("D:/picture/images/boldt.jpg"); Mat logo = imread("D:/picture/images/logo.bmp"); Mat imageROI = image1(Rect(50,50,logo.cols,logo.rows)); Mat mask = imread("D:/picture/images/logo.bmp",0); logo.copyTo(imageROI,mask); imshow("结果图像",image1); waitKey(0); return 0; }