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

基于MobileNet V2迁移学习的动物分类器:单张JPG图片推理方法

单张JPG图片分类实现方案

前提说明

假设你已经完成MobileNet V2迁移学习的训练流程,保存了训练好的模型文件(如animal_classifier.h5),并记录了训练时的类别标签顺序(需与数据集文件夹分类顺序完全一致)。


1. 安装必要依赖

确保环境中已安装核心库,未安装则执行:

pip install tensorflow opencv-python numpy

2. 加载模型与类别标签

首先需要把训练时的类别标签保存为可读取的格式(比如JSON文件),如果训练时没保存,可根据数据集文件夹名称按训练时的排序重新生成。示例代码:

import tensorflow as tf
import json
import cv2
import numpy as np

# 加载训练好的迁移学习模型
model = tf.keras.models.load_model('animal_classifier.h5')

# 加载类别标签(替换为你实际的标签列表,顺序必须和训练时一致)
# 若之前未保存,可通过读取数据集文件夹生成:os.listdir(train_dir) 后按训练时的排序保存
with open('class_labels.json', 'r') as f:
    class_labels = json.load(f)

3. 单张图片预处理函数

MobileNet V2要求输入尺寸为(224,224,3),且需匹配模型的归一化规则:

def preprocess_single_image(image_path):
    # 读取JPG图片并转换为RGB格式(OpenCV默认读为BGR)
    img = cv2.imread(image_path)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    # 调整尺寸到模型要求的输入大小
    img = cv2.resize(img, (224, 224))
    # 应用MobileNet V2官方预处理规则
    img = tf.keras.applications.mobilenet_v2.preprocess_input(img)
    # 添加batch维度(模型接受批量输入格式:(batch_size, 224,224,3))
    img = tf.expand_dims(img, axis=0)
    return img

# 替换为你要分类的目标JPG图片路径
target_img_path = "your_test_image.jpg"
processed_img = preprocess_single_image(target_img_path)

4. 执行预测并输出结果

# 生成预测概率
predictions = model.predict(processed_img, verbose=0)
# 获取最大概率对应的类别索引
predicted_idx = tf.argmax(predictions[0]).numpy()
# 匹配类别名称与置信度
predicted_class = class_labels[predicted_idx]
confidence_score = predictions[0][predicted_idx] * 100

# 打印结果
print(f"预测类别: {predicted_class}")
print(f"置信度: {confidence_score:.2f}%")

关键注意事项

  • 标签顺序一致性:类别标签的顺序必须和训练时数据集文件夹的遍历顺序完全一致,否则预测结果会错位。
  • 图片格式兼容:若读取失败,可替换为PIL库读取:
    from PIL import Image
    def preprocess_single_image(image_path):
        img = Image.open(image_path).convert('RGB')
        img = img.resize((224, 224))
        img = tf.keras.applications.mobilenet_v2.preprocess_input(np.array(img))
        img = tf.expand_dims(img, axis=0)
        return img
    
  • 异常处理:可添加try-except块捕获图片读取失败、模型加载失败等异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 09:57:31