End-to-End Inference Processing Example (ResNet-50)
Sample Code
import numpy as np
from mindx.sdk import base
from mindx.sdk.base import Image, Model, ImageProcessor, Size
try:
# Resource initialization
print('==========resource initialization=========')
base.mx_init()
# Device ID
device_id = 0
# Image decoding
# Initialize the ImageProcessor object.
imageProcessor = ImageProcessor(device_id)
image_path = "data/test_dog.jpg"
# Read the image path for decoding. The decoding format is nv12 (YUV_SP_420).
decoded_image = imageProcessor.decode(image_path, base.nv12)
print('decoded_image width: {}'.format(decoded_image.original_width))
print('decoded_image height: {}'.format(decoded_image.original_height))
print('==========image decoding completed=========')
# Image resizing
# Resizing size
size_para = Size(224, 224)
# Resizes the decoded Image class by size. The resizing mode is the high-order filtering algorithm developed by Huawei (huaweiu_high_order_filter).
resized_image = imageProcessor.resize(decoded_image, size_para, base.huaweiu_high_order_filter)
print('resized_image width: ', resized_image.original_width)
print('resized_image height: ', resized_image.original_height)
print('==========image resizing completed=========')
# Model inference
# Convert the Image class to the Tensor class and transfer it to the list.
input_tensors = [resized_image.to_tensor()]
# Model path
model_path = "./model/resnet50_batchsize_1.om"
# Initialize the Model class.
# You can also use model = base.model(modelPath=model_path, deviceId=device_id).
model = Model(modelPath=model_path, deviceId=device_id)
# Execute inference.
outputs = model.infer(input_tensors)
print('==========model inference completed=========')
# Post-processing
# Obtain the confidence tensor of the inference result.
confidence_tensor = outputs[0]
# Transfer tensor data to the host.
confidence_tensor.to_host()
# Convert the Tensor class to the NumPy array.
confidence_array = np.array(confidence_tensor)
# Obtain the maximum confidence sequence number and confidence.
max_confidence_index = confidence_array.argmax(axis=1)[0]
max_confidence_value = confidence_array[0][max_confidence_index]
print('max_confidence_index:', max_confidence_index)
print('max_confidence_value:', max_confidence_value)
# Classification label file
label_path = "./model/resnet50_clsidx_to_labels.names"
# Read the classification label file and query the classification result.
with open(label_path, 'r', encoding='utf-8') as f:
file = f.read()
label_list = file.split('\n')[0:-1]
infer_result = label_list[max_confidence_index]
print('classification result:{}'.format(infer_result))
except Exception as err:
print('Exception detected: ', err)
Parent topic: Samples