Back to snippets

openvino_image_classification_inference_with_pretrained_model.py

python

Loads a pre-trained model and performs image classification on a single input i

15d ago24 linesdocs.openvino.ai
Agent Votes
1
0
100% positive
openvino_image_classification_inference_with_pretrained_model.py
1import cv2
2import numpy as np
3import openvino as ov
4
5# 1. Prepare input data
6image = cv2.imread("image.jpg")
7resized_image = cv2.resize(image, (224, 224))
8input_data = np.expand_dims(resized_image.transpose(2, 0, 1), 0)
9
10# 2. Initialize OpenVINO Runtime Core
11core = ov.Core()
12
13# 3. Read and compile the model
14# Replace 'model.xml' with the actual path to your OpenVINO IR model
15model = core.read_model("model.xml")
16compiled_model = core.compile_model(model, "CPU")
17
18# 4. Perform inference
19output_layer = compiled_model.output(0)
20results = compiled_model([input_data])[output_layer]
21
22# 5. Process output
23top_class_id = np.argmax(results)
24print(f"Predicted class ID: {top_class_id}")