好久好久没有写博客了,最近看见一个很有意思的文章:小心你的电脑被窃听,就是说在一些公司,截图都会存在水印,方便溯源,然后出于技术的好奇,我在github上搜了一下,还真有相关的github项目:对图片进行水印增加和提取,下面是地址:blind_watermark
1.实现对图片的水印提取
pip install blind-watermark
# 嵌入水印: blind_watermark --embed --pwd 1234 examples/pic/ori_img.jpeg "watermark text" examples/output/embedded.png
# 提取水印: blind_watermark --extract --pwd 1234 --wm_shape 111 examples/output/embedded.png
很简单,就是按着命令后走就行,但是问题是:公司的图片里面隐藏的水印的加密方式,我们也不知道啊,我提取了一下我的截图,出现的就是乱码
2.实现对视频的水印添加和提取
这个没什么,就是在上面的基础上,对视频进行分帧,然后对每帧进行水印的添加,然后再加添加了水印的图片合成video,还有对每帧进行水印的提取。
import os
from blind_watermark import WaterMark
import cv2
def frames_to_video(frame_folder, output_video_path, frame_rate):frame_paths = sorted([os.path.join(frame_folder, f) for f in os.listdir(frame_folder)])first_frame = cv2.imread(frame_paths[0])height, width, _ = first_frame.shapefourcc = cv2.VideoWriter_fourcc(*'mp4v')video = cv2.VideoWriter(output_video_path, fourcc, frame_rate, (width, height))for frame_path in frame_paths:frame = cv2.imread(frame_path)video.write(frame)video.release()def embed_watermark_on_frames(input_folder, output_folder, password_img, password_wm, watermark):bwm = WaterMark(password_img=password_img, password_wm=password_wm)bwm.read_wm(watermark, mode='str')for frame_path in os.listdir(input_folder):frame_full_path = os.path.join(input_folder, frame_path)bwm.read_img(frame_full_path)output_frame_path = os.path.join(output_folder, frame_path)bwm.embed(output_frame_path)def video_to_frames(video_path, output_folder):cap = cv2.VideoCapture(video_path)frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))frame_rate = int(cap.get(cv2.CAP_PROP_FPS))frame_idx = 0while cap.isOpened():ret, frame = cap.read()if not ret:breakframe_path = f"{output_folder}/frame_{frame_idx:04d}.png"cv2.imwrite(frame_path, frame)frame_idx += 1cap.release()return frame_count, frame_rate
def extract_watermark_from_frames(frame_folder, password_img, password_wm, wm_shape):bwm = WaterMark(password_img=password_img, password_wm=password_wm)for frame_path in os.listdir(frame_folder):frame_full_path = os.path.join(frame_folder, frame_path)watermark = bwm.extract(frame_full_path, wm_shape=wm_shape, mode='str')print(f"Watermark from {frame_path}: {watermark}")# 分解视频
video_path = "test.mp4"
output_frames_folder = "frames"
os.makedirs(output_frames_folder, exist_ok=True)
frame_count, frame_rate = video_to_frames(video_path, output_frames_folder)# 嵌入水印
watermark = "secret"
password_img = 1
password_wm = 1
output_watermarked_frames = "watermarked_frames"
os.makedirs(output_watermarked_frames, exist_ok=True)
embed_watermark_on_frames(output_frames_folder, output_watermarked_frames, password_img, password_wm, watermark)# 合成为视频
output_video_path = "watermarked_video.mp4"
frames_to_video(output_watermarked_frames, output_video_path, frame_rate)# 提取水印
extract_watermark_from_frames(output_watermarked_frames, password_img, password_wm, wm_shape=len(watermark))