最近嘗試用預設 rcnn 模型來抓物件位置

訓練都很簡單
要應用就需要轉來轉去

因為轉失敗會跳很多錯誤
例如:  File "\lib\site-packages\PIL\Image.py", line 3098, in fromarray mode, rawmode = _fromarray_typemap[typekey] KeyError: ((1, 1, 256), '|u1')

或是 \lib\site-packages\PIL\Image.py", line 3102, in fromarray raise TypeError(msg) from e TypeError: Cannot handle this data type: (1, 1, 256), <f4


卡一下
就在這邊記一下

 

# 假設 chkImg 是 (256, 256 ) 的黑白2D影像
# 影像增強 detTransform = T.Compose([ T.Resize((256, 256)), T.ToTensor(), ]) # 先確定數值是 uint8 detChkImg = chkImg.astype(np.uint8) # 轉彩色後數值應該是 (256, 256, 3 ) detChkImg = cv2.cvtColor(detChkImg, cv2.COLOR_GRAY2RGB) # 這時候再進去 Image.fromarray 才會正確 detChkImg = Image.fromarray(detChkImg) # 這邊 PIL 影像就可以進去 Transform 裡面轉換成 Tensor detChkImg = detTransform(detChkImg) # 出來的影像再加上第一維度 detChkImg = detChkImg.unsqueeze(0) # shape: [1, 3, H, W] # 就可以進去預測了 outputs = detModel(detChkImg.to('cuda'))

重點就是 cv2 轉 PIL 的過程
給大家參考囉