ssd_inference.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. """
  2. 定义SSD推理流程
  3. """
  4. import numpy as np
  5. from mindx.sdk import Tensor # mxVision 中的 Tensor 数据结构
  6. from mindx.sdk import base # mxVision 推理接口
  7. from PIL import Image
  8. from watermark_verify.utils.anchors import get_anchors
  9. from watermark_verify.utils.utils_bbox import BBoxUtility
  10. class SSDInference:
  11. def __init__(self, model_path, input_size=(300, 300), num_classes=20, num_iou=0.45, confidence=0.5, swap=(2, 0, 1)):
  12. """
  13. 初始化SSD模型推理流程
  14. :param model_path: 图像分类模型onnx文件路径
  15. :param input_size: 模型输入大小
  16. :param num_classes: 模型目标检测分类数
  17. :param num_iou: iou阈值
  18. :param confidence: 置信度阈值
  19. :param swap: 变换方式,pytorch需要进行轴变换(默认参数),tensorflow无需进行轴变换
  20. """
  21. self.model_path = model_path
  22. self.input_size = input_size
  23. self.swap = swap
  24. self.num_classes = num_classes
  25. self.nms_iou = num_iou
  26. self.confidence = confidence
  27. def input_processing(self, image_path):
  28. """
  29. 对输入图片进行预处理
  30. :param image_path: 图片路径
  31. :return: 图片经过处理完成的ndarray
  32. """
  33. image = Image.open(image_path)
  34. image_shape = np.array(np.shape(image)[0:2])
  35. # ---------------------------------------------------------#
  36. # 在这里将图像转换成RGB图像,防止灰度图在预测时报错。
  37. # 代码仅仅支持RGB图像的预测,所有其它类型的图像都会转化成RGB
  38. # ---------------------------------------------------------#
  39. if not (len(np.shape(image)) == 3 and np.shape(image)[2] == 3):
  40. image = image.convert('RGB')
  41. image_data = resize_image(image, self.input_size, False)
  42. MEANS = (104, 117, 123)
  43. image_data = np.array(image_data, dtype='float32')
  44. image_data = image_data - MEANS
  45. image_data = np.expand_dims(np.transpose(image_data, self.swap).copy(), 0)
  46. image_data = image_data.astype('float32')
  47. return image_data, image_shape
  48. def predict(self, image_path):
  49. """
  50. 对单张图片进行推理
  51. :param image_path: 图片路径
  52. :return: 推理结果
  53. """
  54. image_data, image_shape = self.input_processing(image_path)
  55. # 使用mindx框架进行om权重文件推理
  56. base.mx_init()
  57. model = base.model(modelPath=self.model_path) # 初始化 base.model 类
  58. if model is None:
  59. raise Exception("模型导入失败!请检查model_path和device_id.")
  60. # 确保img_tensor是正确的输入格式
  61. input_tensors = Tensor(image_data) # 将numpy转为转为Tensor类
  62. outputs = model.infer([input_tensors]) # 执行推理
  63. output = []
  64. for item in outputs:
  65. item.to_host() # 将Tensor数据转移到内存
  66. item = np.array(item)
  67. if item.size == 0:
  68. return False
  69. output.append(item)
  70. output = self.output_processing(output, image_shape)
  71. return output
  72. def output_processing(self, outputs, image_shape):
  73. """
  74. 对模型输出进行后处理工作
  75. :param outputs: 模型原始输出
  76. :param image_shape: 原始图像大小
  77. :return: 经过处理完成的模型输出
  78. """
  79. # 处理模型预测输出
  80. bbox_util = BBoxUtility(self.num_classes)
  81. anchors = get_anchors(self.input_size)
  82. results = bbox_util.decode_box(outputs, anchors, image_shape, self.input_size, False, nms_iou=self.nms_iou,
  83. confidence=self.confidence)
  84. return results
  85. def resize_image(image, size, letterbox_image):
  86. iw, ih = image.size
  87. w, h = size
  88. if letterbox_image:
  89. scale = min(w / iw, h / ih)
  90. nw = int(iw * scale)
  91. nh = int(ih * scale)
  92. image = image.resize((nw, nh), Image.BICUBIC)
  93. new_image = Image.new('RGB', size, (128, 128, 128))
  94. new_image.paste(image, ((w - nw) // 2, (h - nh) // 2))
  95. else:
  96. new_image = image.resize((w, h), Image.BICUBIC)
  97. return new_image