本样例以Atlas 200I/500 A2 推理产品,使用mxVision Python接口开发图像分类应用进行演示,图像分类模型推理流程图如图1所示。
样例取用Caffe框架ResNet-50模型。模型的输入、输出数据格式参见如下。
软件依赖名称 |
推荐版本 |
获取链接 |
---|---|---|
系统依赖 |
- |
|
CANN开发套件包 |
7.0.0 |
CANN获取链接。 |
npu-driver驱动包 |
23.0.0 |
请参见版本配套表,根据实际硬件设备型号选择配套的驱动、固件。 请参见各硬件产品中驱动和固件安装升级指南获取对应的指导。 |
npu-firmware固件包 |
23.0.0 |
|
numpy |
- |
pip3 install numpy |
opencv-python |
- |
pip3 install opencv-python |
opencv3-python |
- |
|
请访问获取链接,获取样例代码压缩包。
unzip resnet50_sdk_python_sample.zip cd resnet50_sdk_python_sample
样例代码目录结构参考如下,其中om模型仅供示例,用户可通过模型转换功能(ATC)转换为om模型进行推理。
resnet50_sdk_python_sample ├── data │ ├── test.jpg # 测试图片 ├── model │ ├── resnet50.caffemodel # ResNet-50网络的权重文件 │ ├── resnet50.om # ResNet-50网络的om模型 │ ├── resnet50.prototxt # ResNet-50网络的模型文件 ├── utils │ ├── resnet50.cfg # 用于后处理的配置文件,包含类别数量和是否包含softmax操作,具体可打开文件查看 │ ├── resnet50_clsidx_to_labels.names # 类别标签文件 ├── main.py # 运行程序的脚本
用户可使用样例中的“test.jpg”测试图片,也可获取其他图片进行测试(请将获取的图片名称更名为“test.jpg”)。
在该样例中,关键步骤与代码参考如下,不可以直接拷贝编译运行,完整样例代码请参考样例文件。
import numpy as np # 用于对多维数组进行计算 import cv2 # 图片处理三方库,用于对图片进行前后处理 from mindx.sdk import Tensor # mxVision 中的 Tensor 数据结构 from mindx.sdk import base # mxVision 推理接口 from mindx.sdk.base import post # post.Resnet50PostProcess 为 resnet50 后处理接口
if __name__ == "__main__": base.mx_init() # 初始化 mxVision 资源 process() # 程序主要逻辑 base.mx_deinit() # 去初始化 mxVision 资源
'''配置模型相关变量''' pic_path = 'data/test.jpg' # 单张图片 model_path = "model/resnet50.om" # 模型路径 device_id = 0 # 指定运算的Device config_path='utils/resnet50.cfg' # 后处理配置文件 label_path='utils/resnet50_clsidx_to_labels.names' # 类别标签文件 img_size = 256
'''前处理''' img_bgr = cv2.imread(pic_path) img_rgb = img_bgr[:,:,::-1] img = cv2.resize(img_rgb, (img_size, img_size)) # 缩放到目标大小 hw_off = (img_size - 224) // 2 # 对图片进行切分,取中间区域 crop_img = img[hw_off:img_size - hw_off, hw_off:img_size - hw_off, :] img = crop_img.astype("float32") # 转为 float32 数据类型 img[:, :, 0] -= 104 # 常数 104,117,123 用于将图像转换到Caffe模型需要的颜色空间 img[:, :, 1] -= 117 img[:, :, 2] -= 123 img = np.expand_dims(img, axis=0) # 扩展第一维度,适应模型输入 img = img.transpose([0, 3, 1, 2]) # 将 (batch,height,width,channels) 转为 (batch,channels,height,width) img = np.ascontiguousarray(img) # 将内存连续排列 img = Tensor(img) # 将numpy转为转为Tensor类
'''模型推理''' model = base.model(modelPath=model_path, deviceId=device_id) # 初始化 base.model 类 output = model.infer([img])[0] # 执行推理。输入数据类型:List[base.Tensor], 返回模型推理输出的 List[base.Tensor]
'''后处理''' postprocessor = post.Resnet50PostProcess(config_path=config_path, label_path=label_path) # 获取后处理对象 pred = postprocessor.process([output])[0][0] # 利用mxVision接口进行后处理,pred:<ClassInfo classId=... confidence=... className=...> confidence = pred.confidence # 获取类别置信度 className = pred.className # 获取类别名称 print('{}: {}'.format(className, confidence)) # 打印出结果 '''保存推理图片''' img_res = cv2.putText(img_bgr, f'{className}: {confidence:.2f}', (20, 20), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 1) # 将预测的类别与置信度添加到图片 cv2.imwrite('result.png', img_res) print('save infer result success')
source /usr/local/Ascend/ascend-toolkit/set_env.sh
source /usr/local/Ascend/mxVision-{version}/set_env.sh
python main.py
如返回如下信息,则表示运行成功。
Standard Poodle: 0.98583984375 save infer result success
推理完成后,在当前文件夹下生成“result.png”文件,图片结果如图3所示。