yolov5.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from __future__ import absolute_import
  15. import logging
  16. from .... import UltraInferModel, ModelFormat
  17. from .... import c_lib_wrap as C
  18. class YOLOv5Preprocessor:
  19. def __init__(self):
  20. """Create a preprocessor for YOLOv5"""
  21. self._preprocessor = C.vision.detection.YOLOv5Preprocessor()
  22. def run(self, input_ims):
  23. """Preprocess input images for YOLOv5
  24. :param: input_ims: (list of numpy.ndarray)The input image
  25. :return: list of FDTensor
  26. """
  27. return self._preprocessor.run(input_ims)
  28. @property
  29. def size(self):
  30. """
  31. Argument for image preprocessing step, the preprocess image size, tuple of (width, height), default size = [640, 640]
  32. """
  33. return self._preprocessor.size
  34. @property
  35. def padding_value(self):
  36. """
  37. padding value for preprocessing, default [114.0, 114.0, 114.0]
  38. """
  39. # padding value, size should be the same as channels
  40. return self._preprocessor.padding_value
  41. @property
  42. def is_scale_up(self):
  43. """
  44. is_scale_up for preprocessing, the input image only can be zoom out, the maximum resize scale cannot exceed 1.0, default true
  45. """
  46. return self._preprocessor.is_scale_up
  47. @property
  48. def is_mini_pad(self):
  49. """
  50. is_mini_pad for preprocessing, pad to the minimum rectange which height and width is times of stride, default false
  51. """
  52. return self._preprocessor.is_mini_pad
  53. @property
  54. def stride(self):
  55. """
  56. stride for preprocessing, only for mini_pad mode, default 32
  57. """
  58. return self._preprocessor.stride
  59. @size.setter
  60. def size(self, wh):
  61. assert isinstance(
  62. wh, (list, tuple)
  63. ), "The value to set `size` must be type of tuple or list."
  64. assert (
  65. len(wh) == 2
  66. ), "The value to set `size` must contatins 2 elements means [width, height], but now it contains {} elements.".format(
  67. len(wh)
  68. )
  69. self._preprocessor.size = wh
  70. @padding_value.setter
  71. def padding_value(self, value):
  72. assert isinstance(
  73. value, list
  74. ), "The value to set `padding_value` must be type of list."
  75. self._preprocessor.padding_value = value
  76. @is_scale_up.setter
  77. def is_scale_up(self, value):
  78. assert isinstance(
  79. value, bool
  80. ), "The value to set `is_scale_up` must be type of bool."
  81. self._preprocessor.is_scale_up = value
  82. @is_mini_pad.setter
  83. def is_mini_pad(self, value):
  84. assert isinstance(
  85. value, bool
  86. ), "The value to set `is_mini_pad` must be type of bool."
  87. self._preprocessor.is_mini_pad = value
  88. @stride.setter
  89. def stride(self, value):
  90. assert isinstance(value, int), "The value to set `stride` must be type of int."
  91. self._preprocessor.stride = value
  92. class YOLOv5Postprocessor:
  93. def __init__(self):
  94. """Create a postprocessor for YOLOv5"""
  95. self._postprocessor = C.vision.detection.YOLOv5Postprocessor()
  96. def run(self, runtime_results, ims_info):
  97. """Postprocess the runtime results for YOLOv5
  98. :param: runtime_results: (list of FDTensor)The output FDTensor results from runtime
  99. :param: ims_info: (list of dict)Record input_shape and output_shape
  100. :return: list of DetectionResult(If the runtime_results is predict by batched samples, the length of this list equals to the batch size)
  101. """
  102. return self._postprocessor.run(runtime_results, ims_info)
  103. @property
  104. def conf_threshold(self):
  105. """
  106. confidence threshold for postprocessing, default is 0.25
  107. """
  108. return self._postprocessor.conf_threshold
  109. @property
  110. def nms_threshold(self):
  111. """
  112. nms threshold for postprocessing, default is 0.5
  113. """
  114. return self._postprocessor.nms_threshold
  115. @property
  116. def multi_label(self):
  117. """
  118. multi_label for postprocessing, set true for eval, default is True
  119. """
  120. return self._postprocessor.multi_label
  121. @conf_threshold.setter
  122. def conf_threshold(self, conf_threshold):
  123. assert isinstance(
  124. conf_threshold, float
  125. ), "The value to set `conf_threshold` must be type of float."
  126. self._postprocessor.conf_threshold = conf_threshold
  127. @nms_threshold.setter
  128. def nms_threshold(self, nms_threshold):
  129. assert isinstance(
  130. nms_threshold, float
  131. ), "The value to set `nms_threshold` must be type of float."
  132. self._postprocessor.nms_threshold = nms_threshold
  133. @multi_label.setter
  134. def multi_label(self, value):
  135. assert isinstance(
  136. value, bool
  137. ), "The value to set `multi_label` must be type of bool."
  138. self._postprocessor.multi_label = value
  139. class YOLOv5(UltraInferModel):
  140. def __init__(
  141. self,
  142. model_file,
  143. params_file="",
  144. runtime_option=None,
  145. model_format=ModelFormat.ONNX,
  146. ):
  147. """Load a YOLOv5 model exported by YOLOv5.
  148. :param model_file: (str)Path of model file, e.g ./yolov5.onnx
  149. :param params_file: (str)Path of parameters file, e.g yolox/model.pdiparams, if the model_fomat is ModelFormat.ONNX, this param will be ignored, can be set as empty string
  150. :param runtime_option: (ultra_infer.RuntimeOption)RuntimeOption for inference this model, if it's None, will use the default backend on CPU
  151. :param model_format: (ultra_infer.ModelForamt)Model format of the loaded model
  152. """
  153. # 调用基函数进行backend_option的初始化
  154. # 初始化后的option保存在self._runtime_option
  155. super(YOLOv5, self).__init__(runtime_option)
  156. self._model = C.vision.detection.YOLOv5(
  157. model_file, params_file, self._runtime_option, model_format
  158. )
  159. # 通过self.initialized判断整个模型的初始化是否成功
  160. assert self.initialized, "YOLOv5 initialize failed."
  161. def predict(self, input_image, conf_threshold=0.25, nms_iou_threshold=0.5):
  162. """Detect an input image
  163. :param input_image: (numpy.ndarray)The input image data, 3-D array with layout HWC, BGR format
  164. :param conf_threshold: confidence threshold for postprocessing, default is 0.25
  165. :param nms_iou_threshold: iou threshold for NMS, default is 0.5
  166. :return: DetectionResult
  167. """
  168. self.postprocessor.conf_threshold = conf_threshold
  169. self.postprocessor.nms_threshold = nms_iou_threshold
  170. return self._model.predict(input_image)
  171. def batch_predict(self, images):
  172. """Classify a batch of input image
  173. :param im: (list of numpy.ndarray) The input image list, each element is a 3-D array with layout HWC, BGR format
  174. :return list of DetectionResult
  175. """
  176. return self._model.batch_predict(images)
  177. @property
  178. def preprocessor(self):
  179. """Get YOLOv5Preprocessor object of the loaded model
  180. :return YOLOv5Preprocessor
  181. """
  182. return self._model.preprocessor
  183. @property
  184. def postprocessor(self):
  185. """Get YOLOv5Postprocessor object of the loaded model
  186. :return YOLOv5Postprocessor
  187. """
  188. return self._model.postprocessor