OpenCV以BGR格式讀取圖像,而在keras中,它以RGB表示。要使OpenCV版本符合我們期望的順序(RGB),
只需反轉通道:
test_image = cv2.imread('some.jpg')
test_image = cv2.resize(test_image, (224, 244))
test_image = test_image[...,::-1] # Added
最後一行將通道反轉爲RGB順序。然後,你可以將其提供給你的keras模型。
我想補充的另一點是,cv2.imread
通常會在uint8
精確地讀取圖像。檢查keras加載圖像的輸出,你可以看到數據是浮點精度,因此你可能還希望轉換爲浮點表示,例如float32
:
import numpy as np
# ...
# ...
test_image = test_image[...,::-1].astype(np.float32)
最後一點,根據你訓練模型的方式,通常習慣將圖像像素值標準化爲一個[0,1]
範圍。如果你使用keras模型執行此操作,請確保在通過OpenCV讀入的圖像中將值除以255:
import numpy as np
# ...
# ...
test_image = (test_image[...,::-1].astype(np.float32)) / 255.0