AlexNetによる画像分類
AlexNetを使用した画像分類チュートリアル
Section titled “AlexNetを使用した画像分類チュートリアル”このチュートリアルでは、ONNX Runtimeを使用して、事前学習済みのAlexNetモデルで画像を分類する方法を示します。
- ONNX Runtimeがインストールされていること
- ONNXモデルズーからAlexNet ONNXモデルをダウンロードしていること
- OpenCVがインストールされていること
AlexNet ONNXモデルのダウンロード
Section titled “AlexNet ONNXモデルのダウンロード”ONNXモデルズーからAlexNet ONNXモデルをダウンロードできます。
wget https://github.com/onnx/models/raw/main/vision/classification/alexnet/model/bvlcalexnet-9.onnx次のPythonスクリプトは、ONNX Runtimeを使用して画像を分類する方法を示しています。
import onnxruntimeimport numpy as npfrom PIL import Imageimport cv2
# ONNXモデルをロードsession = onnxruntime.InferenceSession("bvlcalexnet-9.onnx")
# 入力名と出力名を取得input_name = session.get_inputs()[0].nameoutput_name = session.get_outputs()[0].name
# 画像をロードして前処理image = cv2.imread("image.jpg")image = cv2.resize(image, (224, 224))image = image.astype(np.float32) / 255.0image = np.transpose(image, (2, 0, 1))image = np.expand_dims(image, axis=0)
# 推論を実行result = session.run([output_name], {input_name: image})
# 出力を処理output = result[0]predicted_class = np.argmax(output)
# 予測されたクラスを出力print(predicted_class)このスクリプトは、画像をロードして前処理し、ONNX Runtimeを使用して推論を実行し、予測されたクラスを出力します。