【Python】OpenCV-图片添加水印处理

图片添加水印处理

1. 引言

图像处理中的水印添加是一种常见的操作,用于在图片上叠加一些信息或标识。本文将介绍如何使用OpenCV库在图片上添加水印,并通过详细的代码注释来解释每一步的操作。

2. 代码示例

以下是一个使用OpenCV库的简单代码示例,演示了如何在图片上添加水印:

python 复制代码
import cv2
import numpy as np

# 读取原始图片
img = cv2.imread("img.png")

# 将图像类型转换为float16,以便后续处理
img = img.astype(np.float16)

# 读取水印图片
shuiyin_img = cv2.imread('shuiyin.png')

# 指定水印位置
shuiyin_pos = [80, 50]

# 在原图上叠加水印
img[shuiyin_pos[0]:shuiyin_pos[0] + shuiyin_img.shape[0], shuiyin_pos[1]:shuiyin_pos[1] + shuiyin_img.shape[1], :] += shuiyin_img

# 处理超过255的像素值,将其设为255
index = img >= 255
img[index] = 255

# 将图像类型重新转换为uint8
img = img.astype(np.uint8)

# 显示带水印的图片
cv2.imshow("img", img)
cv2.waitKey(0)

# 保存处理后的图片
cv2.imwrite('result.png', img)
  • 代码运行效果:

3. 代码解释

3.1 读取原始图片

python 复制代码
img = cv2.imread("img.png")

通过cv2.imread函数读取原始图片,将其赋值给变量img

3.2 图像类型转换

python 复制代码
img = img.astype(np.float16)

将原始图片的数据类型转换为float16,这是为了在后续的处理中避免像素值溢出。

3.3 读取水印图片

python 复制代码
shuiyin_img = cv2.imread('shuiyin.png')

使用cv2.imread函数读取水印图片,将其赋值给变量shuiyin_img

3.4 叠加水印

python 复制代码
img[shuiyin_pos[0]:shuiyin_pos[0] + shuiyin_img.shape[0], shuiyin_pos[1]:shuiyin_pos[1] + shuiyin_img.shape[1], :] += shuiyin_img

在原始图片的指定位置上叠加水印。

3.5 处理像素值超过255

python 复制代码
index = img >= 255
img[index] = 255

处理叠加水印后可能超过255的像素值,将其设为255,避免溢出。

3.6 图像类型转换

python 复制代码
img = img.astype(np.uint8)

将处理后的图像数据类型重新转换为uint8

3.7 显示图片

python 复制代码
cv2.imshow("img", img)
cv2.waitKey(0)

通过OpenCV库的imshow函数显示添加水印后的图片。

3.8 保存处理后的图片

python 复制代码
cv2.imwrite('result.png', img)

使用cv2.imwrite函数将添加水印后的图片保存为新的文件。

4. 结论

通过以上详细的代码注释,我们展示了如何使用OpenCV库在图片上添加水印的整个过程。这是一个简单而实用的图像处理技术,可以用于为图片增添特定信息或标识。

代码参考源自:Shady的混乱空间

相关推荐
IVEN_15 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang16 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮16 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling16 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮20 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽20 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞2 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽2 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers