感想
我們在做深度學習處理圖片的時候,如果是自己制作或者收集的數據集,不可避免的要對數據集進行處理,然后大多數模型都只支持RGB格式的圖片,這個時候,我們需要把其他格式的圖片,例如灰度圖像轉換為RGB的圖片,網上只有灰度圖像轉換為RGB的教程,我這里彌補一下空缺。
1
2
3
4
5
6
7
8
9
|
from PIL import Image import numpy as np L_path = 'train/5509031.jpg' L_image = Image. open (L_path) out = L_image.convert( "RGB" ) img = np.array(out) print (out.mode) print (out.size) print (img.shape) |
然后就可以轉換了哈。
如果是大量的圖片呢,那就笨辦法,用循環判斷吧:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
from PIL import Image from tqdm import tqdm import numpy as np root_path = 'data' for item in tqdm(examples): arr = item.strip().split( '*' ) img_name = arr[ 0 ] image_path = os.path.join(root_path,img_name) img = Image. open (image_path) if (img.mode! = 'RGB' ): img = img.convert( "RGB" ) img = np.array(img) print (img_name) print (img.shape) # add your code |
我的圖片路徑是通過一個txt文件讀取的,這里給出一些train.txt里面樣例:
1
2
3
|
train / 1769512.jpg * postcard construction 67 mixed media epoxy collage 7 x 135 x 4 * art||drawing||sculpture train / 5020991.jpg * en el cuadro de honor de todas las 50appsalud en un grfico en espaol * mhealth train / 3525659.jpg * information mogadishu port expansion turkish company * somalia |
以上這篇python3用PIL把圖片轉換為RGB圖片的實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/w5688414/article/details/84798844