[筆記] 手刻的圖片前處理步驟 Understanding Torchvision transform.Normalize

Understanding Torchvision transform.Normalize

做 Deep Learning 影像辨識實驗時最常用的 pre-train model 就是以 ImageNet 資料訓練出來的 model,此時使用 model 時的圖片前處理就要注意幾個事項:

  1. model 架構中要求的圖片長寬 (Height, Width)
  2. 讀取圖片時的 Channel 順序 RGB 或 BGR
  3. ImageNet 資料集的圖片 Channel 的平均值(mean)與標準差(std)
    以下順序為 [R, G, B]
    • Mean = [0.485, 0.456, 0.406]
    • Std = [0.229, 0.224, 0.225]

知名的深度學習框架 pytorch 有提供一個好用的圖片處理工具 torchvision 來做各式各樣常用圖片前處理,因此可以很簡地透過 torchvision 裡的 transform 做完以上幾件事

以下範例以 Inception V3 架構為例
這個模型要求圖片輸入尺寸為 299x299
Inception V3 paper: https://arxiv.org/abs/1512.00567v3

pytorch code:

from PIL import Image
from torchvision import transform

height = 299
width = 299

test_transform = transforms.Compose([
        transforms.Resize((height, width), interpolation=3),
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
    ])

image_path = 'data/dog.jpg' # 圖片所在的路徑
image = Image.open(image_path)
image = test_transform(image)

補充一個容易出錯的小重點

Pillow 跟 OpenCV 都是我非常常用於圖片讀取與處理的模組
唯一要注意的就是兩者在讀取圖片時,RGB 的通道順序
PIL (Pillow): [R, G, B]
cv2 (OpenCV): [B, G, R]

此外,在訓練為模型後做系統整合時,難免會遇到需要手動做以上的處理
因此特別在此紀錄一下,上面的 code 如果要手刻的話,詳細步驟如下

Image Normalization steps

  • Step 0: image resize to Height = 384, Width=128

  • Step1: range (0, 255) ro (0, 1)

for each pixel
    pixel = pixel / 255
  • Step 2: Mean = [0.485, 0.456, 0.406]
for each channel
    R channel: pixel = pixel - 0.485
    G channel: pixel = pixel - 0.456
    B channel: pixel = pixel - 0.406
  • Step 3: Std = [0.229, 0.224, 0.225]
for each channel
    R channel: pixel = pixel / 0.229
    G channel: pixel = pixel / 0.224
    B channel: pixel = pixel / 0.225


 

留言

這個網誌中的熱門文章

[筆記] CRLF跟LF之區別 --- 隱形的 bug

[ML筆記] Batch Normalization

[筆記] 統計實習(1) SAS 基礎用法 (匯入資料並另存SAS新檔,SUBSTR,計算總和與平均,BMI)

[ML筆記] Ensemble - Bagging, Boosting & Stacking