我想使用 Keras Resnet50 模型和 OpenCV 来读取输入图像并调整其大小。我使用 Keras 中的相同预处理代码(对于 OpenCV,我需要转换为 RGB,因为这是 preprocess_input() 期望的格式)。我使用 OpenCV 和 Keras 图像加载得到的预测略有不同。我不明白为什么预测不一样。
这是我的代码:
import numpy as np
import json
from tensorflow.keras.applications.resnet50 import ResNet50
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions
import cv2
model = ResNet50(weights='imagenet')
img_path = '/home/me/squirle.jpg'
# Keras prediction
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
preds = model.predict(x)
print('Predicted Keras:', decode_predictions(preds, top=3)[0])
# OpenCV prediction
imgcv = cv2.imread(img_path)
dim = (224, 224)
imgcv_resized = cv2.resize(imgcv, dim, interpolation=cv2.INTER_LINEAR)
x = cv2.cvtColor(imgcv_resized , cv2.COLOR_BGR2RGB)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
preds = model.predict(x)
print('Predicted OpenCV:', decode_predictions(preds, top=3)[0])
Predicted Keras: [('n02490219', 'marmoset', 0.28250763), ('n02356798', 'fox_squirrel', 0.25657368), ('n02494079', 'squirrel_monkey', 0.19992349)]
Predicted OpenCV: [('n02356798', 'fox_squirrel', 0.5161952), ('n02490219', 'marmoset', 0.21953616), ('n02494079', 'squirrel_monkey', 0.1160824)]
如何使用 OpenCVimread()并resize()获得与 Keras 图像加载相同的预测?
森栏
慕仙森
相关分类