推理处理样例(ResNet-50)
代码演示
import numpy as np from mindx.sdk import base from mindx.sdk.base import Image, Model, ImageProcessor, Size # 资源初始化 print('==========资源初始化=========') base.mx_init() # 设备Id device_id = 0 # 图像解码 # 初始化ImageProcessor对象 imageProcessor = ImageProcessor(device_id) image_path = "data/test_dog.jpg" # 读取图片路径进行解码,解码格式为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('==========图片解码完成=========') # 图像缩放 # 缩放尺寸 size_para = Size(224, 224) # 读取将解码后的Image类按尺寸进行缩放,缩放方式为华为自研的高阶滤波算法(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类转为Tensor类并传入列表 input_tensors = [resized_image.to_tensor()] # 模型路径 model_path = "./model/resnet50_batchsize_1.om" # 初始化Model类 # 也可使用model = base.model(modelPath=model_path, deviceId=device_id) model = Model(modelPath=model_path, deviceId=device_id) # 执行推理 outputs = model.infer(input_tensors) print('==========模型推理完成=========') # 后处理 # 获取推理结果置信度tensor confidence_tensor = outputs[0] # 将tensor数据转移到Host侧 confidence_tensor.to_host() # 将Tensor类转为numpy array类型 confidence_array = np.array(confidence_tensor) # 获取最大置信度序号和置信度 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) # 分类标签文件路径 label_path = "./model/resnet50_clsidx_to_labels.names" # 读取分类标签文件并查询分类结果 with open(label_path, 'r', encoding='utf-8') as f: file = f.read() label_list = file.split('\n')[1:-1] infer_result = label_list[max_confidence_index] print('classification result:{}'.format(infer_result))
父主题: 样例演示