python计算psnr和ssim
时间: 2023-08-03 07:08:05 浏览: 228
你可以使用Python中的OpenCV库来计算图像的PSNR(峰值信噪比)和SSIM(结构相似性指数)。
首先,确保你已经安装了OpenCV库。可以使用以下命令安装:
```
pip install opencv-python
```
接下来,你可以使用以下代码计算PSNR和SSIM:
```python
import cv2
import numpy as np
def calculate_psnr(original_image, compressed_image):
mse = np.mean((original_image - compressed_image) ** 2)
if mse == 0:
return float('inf')
max_pixel = 255.0
psnr = 20 * np.log10(max_pixel / np.sqrt(mse))
return psnr
def calculate_ssim(original_image, compressed_image):
ssim = cv2.SIFT_score(original_image, compressed_image)
return ssim
# 读取原始图像和压缩后的图像
original_image = cv2.imread('original_image.jpg')
compressed_image = cv2.imread('compressed_image.jpg')
# 将图像转为灰度图像
original_gray = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY)
compressed_gray = cv2.cvtColor(compressed_image, cv2.COLOR_BGR2GRAY)
# 计算PSNR和SSIM
psnr = calculate_psnr(original_gray, compressed_gray)
ssim = calculate_ssim(original_gray, compressed_gray)
print(f"PSNR: {psnr} dB")
print(f"SSIM: {ssim}")
```
请确保将 `original_image.jpg` 和 `compressed_image.jpg` 替换为你实际的图像文件路径。这段代码将计算灰度图像的PSNR和SSIM,并输出结果。
希望这可以帮到你!如果有任何疑问,请随时问我。
阅读全文