predictor.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  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 typing import Any, Union, Dict, List, Tuple
  15. from ....utils.func_register import FuncRegister
  16. from ....modules.video_detection.model_list import MODELS
  17. from ...common.batch_sampler import VideoBatchSampler
  18. from ...common.reader import ReadVideo
  19. from ..common import (
  20. ToBatch,
  21. StaticInfer,
  22. )
  23. from ..base import BasicPredictor
  24. from .processors import ResizeVideo, Image2Array, NormalizeVideo, DetVideoPostProcess
  25. from .result import DetVideoResult
  26. class VideoDetPredictor(BasicPredictor):
  27. entities = MODELS
  28. _FUNC_MAP = {}
  29. register = FuncRegister(_FUNC_MAP)
  30. def __init__(
  31. self,
  32. nms_thresh: Union[float, None] = None,
  33. score_thresh: Union[float, None] = None,
  34. *args,
  35. **kwargs
  36. ):
  37. super().__init__(*args, **kwargs)
  38. self.nms_thresh = nms_thresh
  39. self.score_thresh = score_thresh
  40. self.pre_tfs, self.infer, self.post_op = self._build()
  41. def _build_batch_sampler(self):
  42. return VideoBatchSampler()
  43. def _get_result_class(self):
  44. return DetVideoResult
  45. def _build(self):
  46. pre_tfs = {}
  47. for cfg in self.config["PreProcess"]["transform_ops"]:
  48. tf_key = list(cfg.keys())[0]
  49. assert tf_key in self._FUNC_MAP
  50. func = self._FUNC_MAP[tf_key]
  51. args = cfg.get(tf_key, {})
  52. name, op = func(self, **args) if args else func(self)
  53. if op:
  54. pre_tfs[name] = op
  55. infer = StaticInfer(
  56. model_dir=self.model_dir,
  57. model_prefix=self.MODEL_FILE_PREFIX,
  58. option=self.pp_option,
  59. )
  60. post_op = {}
  61. for cfg in self.config["PostProcess"]["transform_ops"]:
  62. tf_key = list(cfg.keys())[0]
  63. assert tf_key in self._FUNC_MAP
  64. func = self._FUNC_MAP[tf_key]
  65. args = cfg.get(tf_key, {})
  66. if tf_key == "DetVideoPostProcess":
  67. args["label_list"] = self.config["label_list"]
  68. name, op = func(self, **args) if args else func(self)
  69. if op:
  70. post_op[name] = op
  71. return pre_tfs, infer, post_op
  72. def process(
  73. self,
  74. batch_data,
  75. nms_thresh: Union[float, None] = None,
  76. score_thresh: Union[float, None] = None,
  77. ):
  78. batch_raw_videos = self.pre_tfs["ReadVideo"](videos=batch_data)
  79. batch_videos = self.pre_tfs["ResizeVideo"](videos=batch_raw_videos)
  80. batch_videos = self.pre_tfs["Image2Array"](videos=batch_videos)
  81. x = self.pre_tfs["NormalizeVideo"](videos=batch_videos)
  82. num_seg = len(x[0])
  83. pred_seg = []
  84. for i in range(num_seg):
  85. batch_preds = self.infer(x=[x[0][i]])
  86. pred_seg.append(batch_preds)
  87. batch_bboxes = self.post_op["DetVideoPostProcess"](
  88. preds=[pred_seg],
  89. nms_thresh=nms_thresh or self.nms_thresh,
  90. score_thresh=score_thresh or self.score_thresh,
  91. )
  92. return {
  93. "input_path": batch_data,
  94. "result": batch_bboxes,
  95. }
  96. @register("ReadVideo")
  97. def build_readvideo(self, num_seg=8):
  98. return "ReadVideo", ReadVideo(backend="opencv", num_seg=num_seg)
  99. @register("ResizeVideo")
  100. def build_resize(self, target_size=224):
  101. return "ResizeVideo", ResizeVideo(
  102. target_size=target_size,
  103. )
  104. @register("Image2Array")
  105. def build_image2array(self, data_format="tchw"):
  106. return "Image2Array", Image2Array(data_format="tchw")
  107. @register("NormalizeVideo")
  108. def build_normalize(
  109. self,
  110. scale=255.0,
  111. ):
  112. return "NormalizeVideo", NormalizeVideo(scale=scale)
  113. @register("DetVideoPostProcess")
  114. def build_postprocess(self, nms_thresh, score_thresh, label_list=[]):
  115. if not self.nms_thresh:
  116. self.nms_thresh = nms_thresh
  117. if not self.score_thresh:
  118. self.score_thresh = score_thresh
  119. return "DetVideoPostProcess", DetVideoPostProcess(label_list=label_list)