转自 https://www.cnblogs.com/nwpuxuezha/p/7236155.html 师弟很厉害,可以加鸡腿了。
以下为原文:
今天帮师姐解决一个bug,测试了Python图像resize前后颜色不一致问题。
代码片段执行的功能:图像指定倍数超分辨率,输入为[0-1] float型数据,输出为格式不限的图像
bug:输入图像与输出图像颜色不一致
一、把产生bug的功能片段做分离测试:
1 import h5py
2 import numpy as np
3 import matplotlib.pyplot as plt
4 from PIL import Image
5 from scipy import misc
6
7
8 def get_result_array():
9 file_name = "./butterfly_GT.bmp"
10 img_no_expand = misc.imread(file_name, flatten=False, mode='YCbCr')
11 img_no_expand = img_no_expand / 255.0
12 # img_no_expand = np.uint8(img_no_expand*255)
13 h, w = img_no_expand.shape[:2]
14 print(img_no_expand.shape)
15 h *= 2
16 w *= 2
17 data = list()
18
19 data.append(misc.imresize(img_no_expand[:, :, 0], [h, w], 'bicubic')[:,:,None])
20 data.append(misc.imresize(img_no_expand[:, :, 1], [h, w], 'bicubic')[:,:,None])
21 data.append(misc.imresize(img_no_expand[:, :, 2], [h, w], 'bicubic')[:,:,None])
22 data_out = np.concatenate(data, axis=2)
23 img = misc.toimage(arr=data_out, mode="YCbCr")
24 img.save("out_3.jpg")
25
26
27 if __name__=='__main__':
28 get_result_array()
运行代码:
左图为输入图像,右图为输出图像。为了便于对比,把输出图像缩放至与输入图像一致,由图可见,输出图像色彩严重失真。
二、在pycharm中,Ctrl+B 查看源码:
三、发现可以选择模式,猜想可能是模式有误:
四、在函数的实现的第一行,初始化Image类,猜想初始化参数设置错误。
五、在类的初始化过程中,默认图像的最大值为255,而实际输入是0-1的float型数据。找到了错误之处。
六、仔细查看文档,mode可以修改。0-1float型数据对应mode=“F”:
七、于是,在代码中加入参数:
八、插值后处理
插值之后部分像素点数值可能大于1,这时有两种做法,一种是归一化,一种是截断。经过实验发现,归一化操作往往会使图像整体亮度变暗,对图像整体视觉效果有较大影响,因此这里选择截断。
九、最终代码如下:
1 import h5py
2 import numpy as np
3 import matplotlib.pyplot as plt
4 from PIL import Image
5 from scipy import misc
6
7
8 def get_result_array():
9 file_name = "./butterfly_GT.bmp"
10 img_no_expand = misc.imread(file_name, flatten=False, mode='YCbCr')
11 img_no_expand = img_no_expand / 255.0
12 # img_no_expand = np.uint8(img_no_expand*255)
13 h, w = img_no_expand.shape[:2]
14 print(img_no_expand.shape)
15 h *= 2
16 w *= 2
17 data = list()
18 data.append(misc.imresize(img_no_expand[:, :, 0], [h, w], 'bicubic', mode="F")[:,:,None])
19 data.append(misc.imresize(img_no_expand[:, :, 1], [h, w], 'bicubic', mode="F")[:,:,None])
20 data.append(misc.imresize(img_no_expand[:, :, 2], [h, w], 'bicubic', mode="F")[:,:,None])
21 data_out = np.concatenate(data, axis=2)
22 data_out[data_out > 1] = 1.0
23 data_out = np.uint8(data_out * 255)
24 img = misc.toimage(arr=data_out, mode="YCbCr")
25 img.save("out_4.jpg")
26
27
28 if __name__=='__main__':
29 get_result_array()
九、实际测试,输入输出对比图如下所示: