|
@@ -4,7 +4,8 @@
|
|
|
|
|
|
import numpy as np
|
|
|
from PIL import Image
|
|
|
-import onnxruntime as ort
|
|
|
+from mindx.sdk import Tensor # mxVision 中的 Tensor 数据结构
|
|
|
+from mindx.sdk import base # mxVision 推理接口
|
|
|
|
|
|
|
|
|
class ClassificationInference:
|
|
@@ -48,11 +49,13 @@ class ClassificationInference:
|
|
|
:param image_path: 图片路径
|
|
|
:return: 推理结果
|
|
|
"""
|
|
|
- session = ort.InferenceSession(self.model_path) # 加载 ONNX 模型
|
|
|
- input_name = session.get_inputs()[0].name
|
|
|
image = self.input_processing(image_path)
|
|
|
- # 执行预测
|
|
|
- outputs = session.run(None, {input_name: np.expand_dims(image, axis=0)})
|
|
|
+ # 执行推理
|
|
|
+ base.mx_init() # 初始化 mxVision 资源
|
|
|
+ img = Tensor(image[None, :, :, :])
|
|
|
+ model = base.model(modelPath=self.model_path) # 初始化 base.model 类
|
|
|
+ outputs = model.infer([img])[0] # 执行推理。输入数据类型:List[base.Tensor], 返回模型推理输出的List[base.Tensor]
|
|
|
+ outputs = np.array(outputs.to_host()) # 将outputs移动到内存中,并且将base.Tensor类转为numpy array
|
|
|
return outputs
|
|
|
|
|
|
def predict_batch(self, image_paths):
|
|
@@ -61,8 +64,6 @@ class ClassificationInference:
|
|
|
:param image_paths: 待推理的图片路径列表
|
|
|
:return: 批量推理结果
|
|
|
"""
|
|
|
- session = ort.InferenceSession(self.model_path) # 加载 ONNX 模型
|
|
|
- input_name = session.get_inputs()[0].name
|
|
|
batch_images = []
|
|
|
|
|
|
for image_path in image_paths:
|
|
@@ -71,7 +72,10 @@ class ClassificationInference:
|
|
|
|
|
|
# 将批次图片堆叠成 (batch_size, 3, 224, 224) 维度
|
|
|
batch_images = np.stack(batch_images)
|
|
|
-
|
|
|
- # 执行预测
|
|
|
- outputs = session.run(None, {input_name: batch_images})
|
|
|
+ batch_images = Tensor(batch_images)
|
|
|
+ # 执行推理
|
|
|
+ base.mx_init() # 初始化 mxVision 资源
|
|
|
+ model = base.model(modelPath=self.model_path) # 初始化 base.model 类
|
|
|
+ outputs = model.infer([batch_images])[0] # 执行推理。输入数据类型:List[base.Tensor], 返回模型推理输出的List[base.Tensor]
|
|
|
+ outputs = np.array(outputs.to_host()) # 将outputs移动到内存中,并且将base.Tensor类转为numpy array
|
|
|
return outputs
|