实验目的
(1)理解空域添加数字水印的原理。 (2)熟练安装Python扩展库pillow。 (3)熟悉Python扩展库pillow操作图像的方法。 (4)熟练运用字典结构。
实验内容
首先准备一个图像文件,然后把该文件中的图像内容作为数字水印批量添加到当前文件夹中所有图像文件中,要求水印在目标图像文件中的位置随机选择为左上角、右下角或图像中间,并且水印图像的背景在目标图像中设置为透明。
代码
from PIL import Image
import random
import os
def addwm(imagepath, k):
path1 = "D:/Desktop/PyCharmWork/Demo/work-09-2022-04-22/水印.png"
path2 = "D:/Desktop/PyCharmWork/Demo/work-09-2022-04-22/picture/" + imagepath
path3 = "D:/Desktop/PyCharmWork/Demo/work-09-2022-04-22/result/"
wm = Image.open(path1).convert("RGBA")
img = Image.open(path2).convert("RGBA")
newwm = wm.resize((300, 300))
newimg = img.resize((450, 500))
width1, height1 = newwm.size
width2, height2 = newimg.size
for i in range(width1):
for j in range(height1):
rgba = newwm.getpixel((i, j))
newrgba = rgba[:-1] + (100,)
newwm.putpixel((i, j), newrgba)
position = [(0, 0), (width2 // 2 - width1 // 2, height2 // 2 - height1 // 2), (width2 - width1, height2 - height1)]
tuce = Image.new("RGBA", (width2, height2), (0, 0, 0, 0))
tuce.paste(newwm, random.choice(position))
out = Image.composite(tuce, newimg, tuce)
out.save(path3 + str(k + 1) + ".png")
def start():
path = "D:/Desktop/PyCharmWork/Demo/work-09-2022-04-22/picture/"
images = os.listdir(path)
withs = [".jpg", ".png", ".bmp"]
for i in range(len(images)):
hname = os.path.splitext(images[i])[1]
if hname in withs:
addwm(images[i], i)
print("图片" + images[i] + "添加水印成功")
if __name__ == "__main__":
start()
结果:
Python 3.9.7 (default, Sep 16 2021, 16:59:28) [MSC v.1916 64 bit (AMD64)] on win32
runfile('D:/Desktop/PyCharmWork/Demo/work-09-2022-04-22/__init__.py', wdir='D:/Desktop/PyCharmWork/Demo/work-09-2022-04-22')
图片111111.jpg添加水印成功
图片picture.jpg添加水印成功
参考资料
【1】图像批量添加数字水印_变强的猴子的博客-CSDN博客
|