PSNR python代码
时间: 2024-05-02 07:15:52 浏览: 153
SSIM和PSNR的python代码
PSNR(Peak Signal-to-Noise Ratio)是一种用于衡量图像或视频质量的指标,可以通过计算原始图像与压缩/恢复后的图像之间的峰值信噪比来评估图像的失真程度。下面是一个简单的Python代码示例,用于计算两个图像之间的PSNR值:
```python
import cv2
import numpy as np
def calculate_psnr(original_image, compressed_image):
# 读取原始图像和压缩/恢复后的图像
img1 = cv2.imread(original_image)
img2 = cv2.imread(compressed_image)
# 将图像转换为灰度图像
gray_img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
gray_img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
# 计算MSE(均方误差)
mse = np.mean((gray_img1 - gray_img2) **2)
# 计算PSNR值
if mse == 0:
psnr = float('inf')
else:
max_pixel_value = 255.0
psnr = 20 * np.log10(max_pixel_value / np.sqrt(mse))
return psnr
# 示例用法
original_image_path = 'original_image.jpg'
compressed_image_path = 'compressed_image.jpg'
psnr_value = calculate_psnr(original_image_path, compressed_image_path)
print("PSNR value:", psnr_value)
```
请注意,上述代码使用了OpenCV库来读取和处理图像。在运行代码之前,请确保已经安装了OpenCV库。另外,需要将`original_image.jpg`和`compressed_image.jpg`替换为实际的图像文件路径。
阅读全文