计算图像的PSNR和SSIM,代码
时间: 2024-06-11 17:04:11 浏览: 111
PSNR+SSIM代码
3星 · 编辑精心推荐
这里提供Python代码来计算图像的PSNR和SSIM。
首先,导入必要的库:
```python
import cv2
import numpy as np
from skimage.measure import compare_ssim as ssim
```
然后,读取两个图像并将它们转换为灰度图像:
```python
img1 = cv2.imread('image1.jpg')
img2 = cv2.imread('image2.jpg')
img1_gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
img2_gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
```
计算PSNR:
```python
mse = np.mean((img1_gray - img2_gray) ** 2)
if mse == 0:
psnr = 100
else:
max_pixel = 255.0
psnr = 20 * np.log10(max_pixel / np.sqrt(mse))
print('PSNR:', psnr)
```
计算SSIM:
```python
ssim_val = ssim(img1_gray, img2_gray)
print('SSIM:', ssim_val)
```
完整代码:
```python
import cv2
import numpy as np
from skimage.measure import compare_ssim as ssim
img1 = cv2.imread('image1.jpg')
img2 = cv2.imread('image2.jpg')
img1_gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
img2_gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
mse = np.mean((img1_gray - img2_gray) ** 2)
if mse == 0:
psnr = 100
else:
max_pixel = 255.0
psnr = 20 * np.log10(max_pixel / np.sqrt(mse))
print('PSNR:', psnr)
ssim_val = ssim(img1_gray, img2_gray)
print('SSIM:', ssim_val)
```
阅读全文