Traceback (most recent call last): File "C:\Users\86158\PycharmProjects\pythonProject\psnr.py", line 17, in <module> print(psnr(img1, img2)) File "C:\Users\86158\PycharmProjects\pythonProject\psnr.py", line 9, in psnr mse = np.mean((img1-img2)**2) ValueError: operands could not be broadcast together with shapes (935,1920,3) (1200,1920,3)
时间: 2023-09-03 20:10:57 浏览: 115
这个错误提示是因为您的两张图片的尺寸不同,无法进行运算。在计算 PSNR 时,需要保证两张图片的尺寸大小相等,可以将其中一张图片调整为与另一张图片相同的尺寸。您可以使用 OpenCV 提供的 `resize()` 函数将图片进行缩放,使其尺寸相同,然后再计算 PSNR,具体实现方法如下:
```
import cv2
import numpy as np
def psnr(img1, img2):
# 将图片的尺寸调整为相同的大小
img1 = cv2.resize(img1, (img2.shape[1], img2.shape[0]))
# 计算 MSE
mse = np.mean((img1 - img2) ** 2)
# 计算 PSNR
if mse == 0:
return float('inf')
else:
pixel_max = 255.0
psnr = 20 * np.log10(pixel_max / np.sqrt(mse))
return psnr
img1 = cv2.imread('image1.jpg')
img2 = cv2.imread('image2.jpg')
print(psnr(img1, img2))
```
注意,缩放后的图片可能会失真,从而影响 PSNR 的计算结果。因此,尽量保证两张图片的尺寸相同,或者使用其他的图像质量评价指标。
阅读全文
相关推荐













