Python圖像resize前后顏色不一致問題


今天幫師姐解決一個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()

 

九、實際測試,輸入輸出對比圖如下所示:

嗯,又解決了一個bug,坐等師姐請吃飯,哈哈

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM