You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将未见过的图像输入已保存的CNN模型并查看分类结果?

如何用已保存的CNN模型分类新图像

看起来你已经搞定了最关键的前几步——加载预训练模型和图像预处理!接下来只需要补全预测和结果解析的环节,就能得到分类结果了。我帮你完善代码并拆解每一步的细节:

完整代码示例

from keras.models import load_model
from keras.preprocessing import image
import numpy as np

# 1. 加载模型和图像路径
img_path = '/Users/eoind/code/1.jpg'
model = load_model('food.h5')
model.summary()

# 2. 图像预处理(和训练时的预处理逻辑必须完全一致!)
img = image.load_img(img_path, target_size=(100,100))  # 调整到模型输入的尺寸
img_array = image.img_to_array(img)  # 转成numpy数组
img_array = np.expand_dims(img_array, axis=0)  # 添加batch维度(模型默认接受批量输入)

# 重要:如果训练模型时用了像素归一化(比如rescale=1./255),这里必须同步处理
img_array = img_array / 255.0

# 3. 执行预测
print("classifying...")
predictions = model.predict(img_array)

# 4. 解析预测结果(根据你的任务类型选择)
# --- 情况1:多分类任务(比如你的食物分类有多个类别)---
# 这里的class_names要和你训练时的类别顺序完全一致!
class_names = ['汉堡', '披萨', '寿司', '沙拉']  # 替换成你实际的类别列表
predicted_class_idx = np.argmax(predictions[0])  # 取概率最高的类别索引
predicted_class = class_names[predicted_class_idx]
predicted_probability = np.max(predictions[0])  # 获取该类别的概率
print(f"预测结果:{predicted_class},置信度:{predicted_probability:.2f}")

# --- 情况2:二分类任务(比如只有两类食物)---
# predicted_prob = predictions[0][0]
# if predicted_prob > 0.5:
#     print(f"预测类别:类别X,置信度:{predicted_prob:.2f}")
# else:
#     print(f"预测类别:类别Y,置信度:{1 - predicted_prob:.2f}")

关键注意事项

  • 预处理一致性:图像的尺寸、归一化方式必须和训练模型时完全相同。比如训练时用了target_size=(100,100)和rescale=1./255,预测时就不能改,否则模型会输出错误结果。
  • 类别顺序匹配:多分类任务中,class_names的顺序要和你训练时生成数据集的类别顺序一致(比如用ImageDataGenerator.flow_from_directory时,类别顺序是按文件夹名称排序的)。
  • 批量输入逻辑:模型的predict方法默认接受批量图像输入,所以我们用np.expand_dims给单张图像添加了batch维度,这一步是必须的。

内容的提问来源于stack exchange,提问作者eoind94

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:12:51