{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "19329612-70a9-473b-a5f4-02eb497f597b",
   "metadata": {},
   "outputs": [],
   "source": [
    "import onnxruntime as ort\n",
    "import numpy as np\n",
    "import scipy.special\n",
    "from PIL import Image\n",
    "\n",
    "\n",
    "# 预处理图像\n",
    "def preprocess_image(image, resize_size=256, crop_size=224, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]):\n",
    "  image = image.resize((resize_size, resize_size), Image.BILINEAR)\n",
    "  w, h = image.size\n",
    "  left = (w - crop_size) / 2\n",
    "  top = (h - crop_size) / 2\n",
    "  image = image.crop((left, top, left + crop_size, top + crop_size))\n",
    "  image = np.array(image).astype(np.float32)\n",
    "  image = image / 255.0\n",
    "  image = (image - mean) / std\n",
    "  image = np.transpose(image, (2, 0, 1))\n",
    "  image = image.reshape((1,) + image.shape)\n",
    "  return image\n",
    "\n",
    "\n",
    "# 模型加载 2分\n",
    "session = _________________\n",
    "\n",
    "\n",
    "# 加载类别标签\n",
    "labels_path = 'labels.txt'\n",
    "with open(labels_path) as f:\n",
    "  labels = [line.strip() for line in f.readlines()]\n",
    "\n",
    "\n",
    "# 获取模型输入和输出的名称\n",
    "input_name = session.get_inputs()[0].name\n",
    "output_name = session.get_outputs()[0].name\n",
    "\n",
    "\n",
    "# 加载图片 2分\n",
    "image = _________________('RGB')\n",
    "\n",
    "\n",
    "# 预处理图片 2分\n",
    "processed_image = _________________\n",
    "\n",
    "\n",
    "# 确保输入数据是 float32 类型\n",
    "processed_image = processed_image.astype(np.float32)\n",
    "\n",
    "\n",
    "# 进行图片识别 2分\n",
    "output = _________________([output_name], {input_name: processed_image})[0]\n",
    "\n",
    "\n",
    "# 应用 softmax 函数获取概率 2分\n",
    "probabilities = _________________(output, axis=-1)\n",
    "\n",
    "\n",
    "# 获取最高的5个概率和对应的类别索引 3分\n",
    "top5_idx = _________________[-5:][::-1]\n",
    "top5_prob = _________________\n",
    "\n",
    "\n",
    "# 打印结果\n",
    "print(\"Top 5 predicted classes:\")\n",
    "for i in range(5):\n",
    "  print(f\"{i+1}: {labels[top5_idx[i]]} - Probability: {top5_prob[i]}\")\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
