未經(jīng)允許,不得轉(zhuǎn)載,謝謝~~
這篇文章整理了在處理大量圖片數(shù)據(jù)集時可能需要用到的一些東西。
主要包括:
- 用
urllib根據(jù)圖片url抓取圖片并保存; - 用
PIL的Image圖像庫加載圖片; - 用
crop函數(shù)對圖像進(jìn)行裁剪; - 處理數(shù)據(jù)集中的圖像通道數(shù),使其都為3通道;
1. 根據(jù)url下載圖片
數(shù)據(jù)集很大的情況,常常需要我們自己去下載圖片,這個時候就需要有個程序幫我們自動下載了。
- 用urllib獲取圖片并保存
import urllib
# img_url: the url of image
# img_path: the path you want to save image
urllib.urlretrieve(img_url,img_path)
2. 圖片加載與處理
1. 用PIL加載圖像
from PIL import Image
def get_image_from_path(img_path,img_region):
image = Image.open(img_path)
image = process_image_channels(image, img_path)
image = image.crop(img_region)
return image
2. 關(guān)于crop函數(shù)
- 一定要注意bounding_box的傳入?yún)?shù);
- crop接受的參數(shù)為(左上x,左上y,右下x,右下y)
- python的坐標(biāo)系為最左上角為(0,0),橫向x,縱向y;
- 這里踩了好久的坑。╮(╯﹏╰)╭
3. 關(guān)于處理圖像通道
- 在這次處理的數(shù)據(jù)集中有jpg的圖像,也有png的圖像;
- 以前從來不知道png會有
RGBA4個通道甚至有些圖片只有一個A通道,所以如果沒有提前處理后面訓(xùn)練或者換測試的時候會時不時的給你一個bug小彩蛋哈哈哈。 - 關(guān)鍵語句:
def process_image_channels(image, image_path):
# process the 4 channels .png
if image.mode == 'RGBA':
r, g, b, a = image.split()
image = Image.merge("RGB", (r, g, b))
# process the 1 channel image
elif image.mode != 'RGB':
image = image.convert("RGB")
os.remove(image_path)
image.save(image_path)
return image
簡單的做個整理吧,后期有新的問題也會繼續(xù)補(bǔ)充在這里。