python图像resize_Python图像resize前后颜色不一致问题

今天帮师姐解决一个bug,测试了Python图像resize前后颜色不一致问题。

代码片段执行的功能:图像指定倍数超分辨率,输入为[0-1] float型数据,输出为格式不限的图像

bug:输入图像与输出图像颜色不一致

一、把产生bug的功能片段做分离测试:

1 importh5py2 importnumpy as np3 importmatplotlib.pyplot as plt4 from PIL importImage5 from scipy importmisc6

7

8 defget_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()

运行代码:

2bb92d28fc4fdc41653360fac4ac9bfe.bmp

a7c62fd6394fe640bd03f6c61cbbbb82.png

左图为输入图像,右图为输出图像。为了便于对比,把输出图像缩放至与输入图像一致,由图可见,输出图像色彩严重失真。

二、在pycharm中,Ctrl+B 查看源码:

87273973abb07f17fd5e1dc11fbba092.png

三、发现可以选择模式,猜想可能是模式有误:

ec8fb8835a09c6304647b3acd05438dd.png

四、在函数的实现的第一行,初始化Image类,猜想初始化参数设置错误。

09f5b18c53932bf5b6cb647db59d575a.png

五、在类的初始化过程中,默认图像的最大值为255,而实际输入是0-1的float型数据。找到了错误之处。

5f00765ac9972fdcbe8df767624b6160.png

六、仔细查看文档,mode可以修改。0-1float型数据对应mode=“F”:

0f26431d9aef708f836beabf094e27da.png

七、于是,在代码中加入参数:

27adc6da64fd0312de360b8fdb2606a3.png

八、最终代码如下:

1 importh5py2 importnumpy as np3 importmatplotlib.pyplot as plt4 from PIL importImage5 from scipy importmisc6

7

8 defget_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 img = misc.toimage(arr=data_out, mode="YCbCr")23 img.save("out_4.jpg")24

25

26 if __name__==‘__main__‘:27 get_result_array()

九、实际测试,输入输出对比图如下所示:

3ebbdc0924d2a1186d583aafa4423df0.png

cd5e012b16d01e04796f83c4c4ea2341.gif

a16bf6f890858d3669869c0a369a9885.png

嗯,又解决了一个bug,坐等师姐请吃饭,哈哈

原文:http://www.cnblogs.com/nwpuxuezha/p/7236155.html


版权声明:本文为weixin_39856803原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。