一、问题描述
cv2.imread读入图像,并显示读入图像间的残差热图,获取的结果明显不是我们想要的结果。
import matplotlib.pyplot as plt
import numpy as np
import cv2
import seaborn as sns
dirpath = r"C:/Users/zhang/Desktop/testResult/ImageQuality/Image/DuiBi49_13/"
CBCT0 = cv2.imread(dirpath + 'CBCT.png')
PCT0 = cv2.imread(dirpath + 'PCT.png')
SPCT0 = cv2.imread(dirpath + 'MindCg.png')
CPerr = CBCT-PCT
SPerr = SPCT-PCT
热图中显示的像素值有大量的200以上的像素值,与我预期想得到的很不一样。
二、解决
查看读取的图像的数据类型是uint8类型的,无符号整型的数据求差,我们将问题简化一下:
import numpy as np
a = np.uint8([1,2,3,4,5])
b = np.uint8([5,4,3,2,1])
e = a - b
print(e)
这[252,254,0,2,4]显然不是我们想要的结果[-4,-2,02,4],主要是因为无符号整型的运算:就是那些源码、反码、补码的那些知识。那我们可以将a,b转换为有符号整型吗:
import numpy as np
a = np.uint8([1,2,3,4,5])
b = np.uint8([5,4,3,2,1])
c = int(a)
b = int(b)
e = c - d
print(e)
没有查询到python中的无符号整型如何强制类型转换成有符号数,但是我们分情况处理仍然能解决,记录一下:
import numpy as np
a = np.uint8([1,2,3,4,5])
b = np.uint8([5,4,3,2,1])
n = len(a)
e = [1]*n
for i in range(n):
if a[i] >= b[i]:
e[i] = a[i] - b[i]
else:
e[i] = (a[i] -b[i]) - 256
print(e)
应用到开始的图像上:
import matplotlib.pyplot as plt
import numpy as np
import cv2
import seaborn as sns
dirpath = r"C:/Users/zhang/Desktop/testResult/ImageQuality/Image/DuiBi49_13/"
CBCT0 = cv2.imread(dirpath + 'CBCT.png')
PCT0 = cv2.imread(dirpath + 'PCT.png')
SPCT0 = cv2.imread(dirpath + 'MindCg.png')
CPerr = [[1 for i in range(256)] for i in range(256)]
SPerr = [[1 for i in range(256)] for i in range(256)]
for i in range(256):
for j in range(256):
if CBCT[i][j] >= PCT[i][j]:
CPerr[i][j] = CBCT[i][j] - PCT[i][j]
else:
CPerr[i][j] = (CBCT[i][j] - PCT[i][j]) - 256
for i in range(256):
for j in range(256):
if SPCT[i][j] >= PCT[i][j]:
SPerr[i][j] = SPCT[i][j] - PCT[i][j]
else:
SPerr[i][j] = (SPCT[i][j] - PCT[i][j]) - 256
cmap = sns.diverging_palette(0,230,90,60,as_cmap=True)
plt.subplot(2,3,1)
plt.imshow(PCT0)
plt.subplot(2,3,2)
plt.imshow(CBCT0)
plt.subplot(2,3,3)
plt.imshow(SPCT0)
plt.subplot(2,2,3)
sns.heatmap(CPerr,vmin=-100,vmax=100,cmap=cmap)
plt.subplot(2,2,4)
sns.heatmap(SPerr,vmin=-100,vmax=100,cmap=cmap)
plt.tight_layout()
plt.show()