图片峰值信噪比计算
时间: 2025-06-24 19:41:33 浏览: 15
### 计算图像的峰值信噪比 (PSNR)
为了计算两幅图像之间的峰值信噪比(Peak Signal-to-Noise Ratio, PSNR),可以采用多种方法和工具。以下是基于 Python 和 OpenCV 的实现方式。
#### 使用 Python 和 OpenCV 实现 PSNR
OpenCV 提供了一个内置函数 `cv2.PSNR` 来简化 PSNR 的计算过程[^2]。该函数可以直接接受两张相同尺寸的灰度图或彩色图作为输入参数,并返回它们之间的 PSNR 值。
下面是具体的代码示例:
```python
import cv2
# 加载原始图像和压缩后的图像
original_image = cv2.imread('original.jpg', cv2.IMREAD_GRAYSCALE)
compressed_image = cv2.imread('compressed.jpg', cv2.IMREAD_GRAYSCALE)
# 确保两张图像大小一致
if original_image.shape != compressed_image.shape:
raise ValueError("The images must have the same dimensions.")
# 计算 PSNR
psnr_value = cv2.PSNR(original_image, compressed_image)
print(f"The Peak Signal-to-Noise Ratio (PSNR) is {psnr_value} dB.")
```
如果需要手动实现 PSNR 而不依赖于 OpenCV,则可以通过以下公式完成计算[^3]:
\[
PSNR = 10 \cdot \log_{10}\left(\frac{L^2}{MSE}\right)
\]
其中 \( L \) 是像素的最大可能值(对于8位图像,\( L=255 \)),而 MSE 表示均方误差,其定义为:
\[
MSE = \frac{1}{mn} \sum_{i=0}^{m-1} \sum_{j=0}^{n-1} [I(i,j) - K(i,j)]^2
\]
下面是一个手动实现 PSNR 的代码示例:
```python
import numpy as np
def calculate_psnr(image1, image2):
mse = np.mean((image1.astype(float) - image2.astype(float)) ** 2)
if mse == 0:
return float('inf') # 如果完全无误码则返回无穷大
max_pixel_value = 255.0 # 对于8位图像
psnr = 20 * np.log10(max_pixel_value / np.sqrt(mse))
return psnr
# 加载原始图像和压缩后的图像
original_image = cv2.imread('original.jpg', cv2.IMREAD_GRAYSCALE)
compressed_image = cv2.imread('compressed.jpg', cv2.IMREAD_GRAYSCALE)
# 确保两张图像大小一致
if original_image.shape != compressed_image.shape:
raise ValueError("The images must have the same dimensions.")
psnr_value_manual = calculate_psnr(original_image, compressed_image)
print(f"Manually calculated PSNR: {psnr_value_manual} dB.")
```
以上两种方法都可以有效地计算图像的 PSNR 值。第一种方法利用了 OpenCV 库中的预置功能,第二种则是通过数学公式的直接应用来获得结果。
---
阅读全文
相关推荐




















