本文介绍opencv给图片加水印的方法。
目录
- 1、添加水印
- 1.1、铺满
- 1.2、在指定区域添加
- 1.3、一比一铺满
1、添加水印
添加水印的原理是调低两张图片的透明度,然后叠加起来。公式如下:
dst = src1 * opacity + src2 * (1 - opacity) + gamma;
opacity是透明度,取值范围为0 - 1。
gamma是增益,用来调整图像亮度。
准备好以下素材,在说明书上添加小鸟水印。
下面是几种添加水印的形式。
1.1、铺满
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
using namespace cv;
int main() {
Mat wordSrc = imread("word.png");
Mat birdSrc = imread("bird.jpg");
int rOffset, cOffset;
float bOca = 0.3, wOca = 1 - bOca;
int gamma = 0;
for (int r = 0; r < wordSrc.rows; r++) {
rOffset = r / birdSrc.rows * birdSrc.rows;
for (int c = 0; c < wordSrc.cols; c++) {
cOffset = c / birdSrc.cols * birdSrc.cols;
Vec3b *wPixel = wordSrc.ptr<Vec3b>(r, c);
Vec3b *bPixel = birdSrc.ptr<Vec3b>(r - rOffset, c - cOffset);
int val;
val = wPixel->val[0] * wOca + bPixel->val[0] * bOca + gamma;//B
wPixel->val[0] = val > 255 ? 255 : (val < 0 ? 0 : val);
val = wPixel->val[1] * wOca + bPixel->val[1] * bOca + gamma;//G
wPixel->val[1] = val > 255 ? 255 : (val < 0 ? 0 : val);
val = wPixel->val[2] * wOca + bPixel->val[2] * bOca + gamma;//R
wPixel->val[2] = val > 255 ? 255 : (val < 0 ? 0 : val);
}
}
imshow("word", wordSrc);
waitKey(0);
}
1.2、在指定区域添加
int main()
{
Mat wordSrc = imread("word.png");
Mat birdSrc = imread("bird.jpg");
int rOffset = wordSrc.rows - birdSrc.rows, cOffset = wordSrc.cols - birdSrc.cols;
float bOca = 0.3, wOca = 1 - bOca;
int gamma = -20;
for (int r = 0; r < birdSrc.rows; r++) {
for (int c = 0; c < birdSrc.cols; c++) {
Vec3b *wPixel = wordSrc.ptr<Vec3b>(r + rOffset, c + cOffset);
Vec3b *bPixel = birdSrc.ptr<Vec3b>(r, c);
int val;
val = wPixel->val[0] * wOca + bPixel->val[0] * bOca + gamma;//B
wPixel->val[0] = val > 255 ? 255 : (val < 0 ? 0 : val);
val = wPixel->val[1] * wOca + bPixel->val[1] * bOca + gamma;//G
wPixel->val[1] = val > 255 ? 255 : (val < 0 ? 0 : val);
val = wPixel->val[2] * wOca + bPixel->val[2] * bOca + gamma;//R
wPixel->val[2] = val > 255 ? 255 : (val < 0 ? 0 : val);
}
}
imshow("word", wordSrc);
waitKey(0);
}
1.3、一比一铺满
如果水印大小和图像大小一直,可以使用opencv自带的函数addWeighted(src1, alpha, src2, beta, gamma, dst, dtype = -1)。
用法可以参考:https://blog.csdn.net/weixin_45001971/article/details/129042853
在“图片叠加”一节中有介绍用法。