【python PIL】数字水印添加以及检测
时间: 2023-07-12 17:44:26 浏览: 97
要在图片上添加数字水印,可以使用Python的PIL库(Python Imaging Library),具体步骤如下:
1.导入PIL库
```python
from PIL import Image, ImageDraw, ImageFont
```
2.打开图片
```python
im = Image.open('image.jpg')
```
3.创建字体对象
```python
font = ImageFont.truetype('arial.ttf', size=20)
```
4.创建Draw对象
```python
draw = ImageDraw.Draw(im)
```
5.添加水印
```python
draw.text((0, 0), '123', fill=(255, 0, 0), font=font)
```
6.保存图片
```python
im.save('watermark.jpg')
```
为了检测数字水印是否被修改或删除,可以使用数字水印算法。一种常见的数字水印算法是LSB(Least Significant Bit)算法,即将数字水印嵌入到图片的最低有效位中。具体步骤如下:
1.将数字水印转换为二进制序列
```python
watermark = '123'
watermark_binary = ''.join(format(ord(c), '08b') for c in watermark)
```
2.打开图片
```python
im = Image.open('watermark.jpg')
```
3.将图片转换为像素矩阵
```python
pixels = im.load()
width, height = im.size
```
4.将数字水印嵌入到最低有效位中
```python
index = 0
for y in range(height):
for x in range(width):
r, g, b = pixels[x, y]
if index < len(watermark_binary):
r_binary = format(r, '08b')
r_binary = r_binary[:-1] + watermark_binary[index]
r = int(r_binary, 2)
pixels[x, y] = (r, g, b)
index += 1
else:
break
else:
continue
break
```
5.保存图片
```python
im.save('watermark_modified.jpg')
```
6.检测数字水印是否被修改或删除
```python
im_modified = Image.open('watermark_modified.jpg')
pixels_modified = im_modified.load()
width_modified, height_modified = im_modified.size
index = 0
watermark_binary_modified = ''
for y in range(height_modified):
for x in range(width_modified):
r_modified, g_modified, b_modified = pixels_modified[x, y]
r_binary_modified = format(r_modified, '08b')
watermark_binary_modified += r_binary_modified[-1]
index += 1
if index == len(watermark_binary):
break
else:
continue
break
watermark_modified = ''.join(chr(int(watermark_binary_modified[i:i+8], 2)) for i in range(0, len(watermark_binary_modified), 8))
if watermark == watermark_modified:
print('数字水印未被修改或删除')
else:
print('数字水印已被修改或删除')
```
阅读全文