Python 3.4。计算均方误差。我无法解释astype()如何影响numpy mean和sum。什么形式是正确的?
import cv2
import numpy as np
InputImage = cv2.imread('Crocus.jpg')
BlurredImage = cv2.GaussianBlur(InputImage, ( 5, 5), 2.0)
GrayImage = cv2.cvtColor( BlurredImage, cv2.COLOR_BGR2GRAY)
I0 = cv2.cvtColor( InputImage, cv2.COLOR_BGR2GRAY)
MN = float(I0.shape[0] * I0.shape[1])
MSE = np.mean((I0 - GrayImage) ** 2, axis=None)
print(MSE)
MSE = np.mean((I0.astype("float") - GrayImage.astype("float")) ** 2)
print(MSE)
MSE2 = np.sum((I0 - GrayImage) ** 2, axis=None) / MN
print(MSE2)
MSE2 = np.sum((I0.astype("float") - GrayImage.astype("float")) ** 2) / MN
print(MSE2)
输出是(对于我的图像):
63.4138313802
224.549664714
63.4138313802
224.549664714
astype(“float”)为这两个公式提供了不同的答案。图像值都是uint8。为什么浮动会对结果产生影响?什么是正确的答案?
保罗,谢谢。数字是uint8,因此差异不能小于零。将数组转换为int8或float将处理差异。答案 0 :(得分:3)
我很确定你所看到的是广场上的溢出:
import numpy as np
mock_data = np.random.randint(0, 256, (100,)).astype(np.uint8)
blurred = np.convolve(mock_data, (0.25,0.5,0.25), 'same').astype(np.uint8)
print(np.mean((mock_data-blurred)**2))
print(np.mean((mock_data.astype(float)-blurred.astype(float))**2))
# truncating squared floats below 256 gives same result as uint8
print(np.mean(((mock_data.astype(float)-blurred.astype(float))**2) % 256))
# squared uint8 is truncated below 256
print(np.all((mock_data-blurred)**2 < 256))
# but non-squared difference is not bounded by +/-16
print(np.all((np.abs(mock_data-blurred)) < 16))
打印:
115.87
2337.95
115.87
True
False
所以,我的建议是使用float结果。