读取一幅灰度图像,分别实现空域和频域两种算法对图像进行水印嵌入和提取;显示水印嵌入前后的图像,并显示水印嵌入前后的图像psnr值,以及水印提取的nc值
时间: 2023-12-12 19:04:22 浏览: 274
空域算法:
水印嵌入:
1. 读取灰度图像
```python
import cv2
import numpy as np
img = cv2.imread('lena.jpg', cv2.IMREAD_GRAYSCALE)
```
2. 设计水印,并将其转化为二值化图像
```python
watermark = np.random.randint(0, 2, size=img.shape[:2], dtype=np.uint8)*255
```
3. 将水印嵌入到图像中
```python
alpha = 0.1 # 水印强度
img_watermark = cv2.addWeighted(img, 1-alpha, watermark, alpha, 0)
```
4. 显示水印嵌入前后的图像,并计算PSNR值
```python
psnr_before = cv2.PSNR(img, img)
psnr_after = cv2.PSNR(img, img_watermark)
cv2.imshow('original', img)
cv2.imshow('watermarked', img_watermark)
print('PSNR before:', psnr_before)
print('PSNR after:', psnr_after)
```
水印提取:
1. 从水印嵌入后的图像中提取水印
```python
img_extract = img_watermark - img
```
2. 将提取出的水印二值化
```python
_, watermark_extract = cv2.threshold(img_extract, 127, 255, cv2.THRESH_BINARY)
```
3. 计算NC值
```python
nc = np.sum(watermark_extract == watermark) / (watermark.shape[0]*watermark.shape[1])
print('NC:', nc)
```
频域算法:
水印嵌入:
1. 读取灰度图像
```python
import cv2
import numpy as np
img = cv2.imread('lena.jpg', cv2.IMREAD_GRAYSCALE)
```
2. 设计水印,并将其转化为二值化图像
```python
watermark = np.random.randint(0, 2, size=img.shape[:2], dtype=np.uint8)*255
```
3. 将水印嵌入到图像中
```python
alpha = 0.1 # 水印强度
dct = cv2.dct(np.float32(img)/255.0)
dct_watermark = dct + alpha*watermark
img_watermark = cv2.idct(dct_watermark)*255.0
```
4. 显示水印嵌入前后的图像,并计算PSNR值
```python
psnr_before = cv2.PSNR(img, img)
psnr_after = cv2.PSNR(img, img_watermark)
cv2.imshow('original', img)
cv2.imshow('watermarked', img_watermark)
print('PSNR before:', psnr_before)
print('PSNR after:', psnr_after)
```
水印提取:
1. 从水印嵌入后的图像中提取水印
```python
dct_extract = cv2.dct(np.float32(img_watermark)/255.0)
dct_watermark_extract = dct_extract - cv2.dct(np.float32(img)/255.0)
```
2. 将提取出的水印二值化
```python
_, watermark_extract = cv2.threshold(dct_watermark_extract, 0, 255, cv2.THRESH_BINARY)
```
3. 计算NC值
```python
nc = np.sum(watermark_extract == watermark) / (watermark.shape[0]*watermark.shape[1])
print('NC:', nc)
```
阅读全文