infer_demo.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  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. import cv2
  15. import numpy as np
  16. import argparse
  17. import onnxruntime as ort
  18. from pathlib import Path
  19. from tqdm import tqdm
  20. class PicoDet():
  21. def __init__(self,
  22. model_pb_path,
  23. label_path,
  24. prob_threshold=0.4,
  25. iou_threshold=0.3):
  26. self.classes = list(
  27. map(lambda x: x.strip(), open(label_path, 'r').readlines()))
  28. self.num_classes = len(self.classes)
  29. self.prob_threshold = prob_threshold
  30. self.iou_threshold = iou_threshold
  31. self.mean = np.array(
  32. [103.53, 116.28, 123.675], dtype=np.float32).reshape(1, 1, 3)
  33. self.std = np.array(
  34. [57.375, 57.12, 58.395], dtype=np.float32).reshape(1, 1, 3)
  35. so = ort.SessionOptions()
  36. so.log_severity_level = 3
  37. self.net = ort.InferenceSession(model_pb_path, so)
  38. inputs_name = [a.name for a in self.net.get_inputs()]
  39. inputs_shape = {
  40. k: v.shape
  41. for k, v in zip(inputs_name, self.net.get_inputs())
  42. }
  43. self.input_shape = inputs_shape['image'][2:]
  44. def _normalize(self, img):
  45. img = img.astype(np.float32)
  46. img = (img / 255.0 - self.mean / 255.0) / (self.std / 255.0)
  47. return img
  48. def resize_image(self, srcimg, keep_ratio=False):
  49. top, left, newh, neww = 0, 0, self.input_shape[0], self.input_shape[1]
  50. origin_shape = srcimg.shape[:2]
  51. im_scale_y = newh / float(origin_shape[0])
  52. im_scale_x = neww / float(origin_shape[1])
  53. img_shape = np.array([
  54. [float(self.input_shape[0]), float(self.input_shape[1])]
  55. ]).astype('float32')
  56. scale_factor = np.array([[im_scale_y, im_scale_x]]).astype('float32')
  57. if keep_ratio and srcimg.shape[0] != srcimg.shape[1]:
  58. hw_scale = srcimg.shape[0] / srcimg.shape[1]
  59. if hw_scale > 1:
  60. newh, neww = self.input_shape[0], int(self.input_shape[1] /
  61. hw_scale)
  62. img = cv2.resize(
  63. srcimg, (neww, newh), interpolation=cv2.INTER_AREA)
  64. left = int((self.input_shape[1] - neww) * 0.5)
  65. img = cv2.copyMakeBorder(
  66. img,
  67. 0,
  68. 0,
  69. left,
  70. self.input_shape[1] - neww - left,
  71. cv2.BORDER_CONSTANT,
  72. value=0) # add border
  73. else:
  74. newh, neww = int(self.input_shape[0] *
  75. hw_scale), self.input_shape[1]
  76. img = cv2.resize(
  77. srcimg, (neww, newh), interpolation=cv2.INTER_AREA)
  78. top = int((self.input_shape[0] - newh) * 0.5)
  79. img = cv2.copyMakeBorder(
  80. img,
  81. top,
  82. self.input_shape[0] - newh - top,
  83. 0,
  84. 0,
  85. cv2.BORDER_CONSTANT,
  86. value=0)
  87. else:
  88. img = cv2.resize(
  89. srcimg, self.input_shape, interpolation=cv2.INTER_LINEAR)
  90. return img, img_shape, scale_factor
  91. def get_color_map_list(self, num_classes):
  92. color_map = num_classes * [0, 0, 0]
  93. for i in range(0, num_classes):
  94. j = 0
  95. lab = i
  96. while lab:
  97. color_map[i * 3] |= (((lab >> 0) & 1) << (7 - j))
  98. color_map[i * 3 + 1] |= (((lab >> 1) & 1) << (7 - j))
  99. color_map[i * 3 + 2] |= (((lab >> 2) & 1) << (7 - j))
  100. j += 1
  101. lab >>= 3
  102. color_map = [color_map[i:i + 3] for i in range(0, len(color_map), 3)]
  103. return color_map
  104. def detect(self, srcimg):
  105. img, im_shape, scale_factor = self.resize_image(srcimg)
  106. img = self._normalize(img)
  107. blob = np.expand_dims(np.transpose(img, (2, 0, 1)), axis=0)
  108. inputs_dict = {
  109. 'im_shape': im_shape,
  110. 'image': blob,
  111. 'scale_factor': scale_factor
  112. }
  113. inputs_name = [a.name for a in self.net.get_inputs()]
  114. net_inputs = {k: inputs_dict[k] for k in inputs_name}
  115. outs = self.net.run(None, net_inputs)
  116. outs = np.array(outs[0])
  117. expect_boxes = (outs[:, 1] > 0.5) & (outs[:, 0] > -1)
  118. np_boxes = outs[expect_boxes, :]
  119. color_list = self.get_color_map_list(self.num_classes)
  120. clsid2color = {}
  121. for i in range(np_boxes.shape[0]):
  122. classid, conf = int(np_boxes[i, 0]), np_boxes[i, 1]
  123. xmin, ymin, xmax, ymax = int(np_boxes[i, 2]), int(np_boxes[
  124. i, 3]), int(np_boxes[i, 4]), int(np_boxes[i, 5])
  125. if classid not in clsid2color:
  126. clsid2color[classid] = color_list[classid]
  127. color = tuple(clsid2color[classid])
  128. cv2.rectangle(
  129. srcimg, (xmin, ymin), (xmax, ymax), color, thickness=2)
  130. print(self.classes[classid] + ': ' + str(round(conf, 3)))
  131. cv2.putText(
  132. srcimg,
  133. self.classes[classid] + ':' + str(round(conf, 3)), (xmin,
  134. ymin - 10),
  135. cv2.FONT_HERSHEY_SIMPLEX,
  136. 0.8, (0, 255, 0),
  137. thickness=2)
  138. return srcimg
  139. def detect_folder(self, img_fold, result_path):
  140. img_fold = Path(img_fold)
  141. result_path = Path(result_path)
  142. result_path.mkdir(parents=True, exist_ok=True)
  143. img_name_list = filter(
  144. lambda x: str(x).endswith(".png") or str(x).endswith(".jpg"),
  145. img_fold.iterdir(), )
  146. img_name_list = list(img_name_list)
  147. print(f"find {len(img_name_list)} images")
  148. for img_path in tqdm(img_name_list):
  149. img = cv2.imread(str(img_path), 1)
  150. img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  151. srcimg = net.detect(img)
  152. save_path = str(result_path / img_path.name.replace(".png", ".jpg"))
  153. cv2.imwrite(save_path, srcimg)
  154. if __name__ == '__main__':
  155. parser = argparse.ArgumentParser()
  156. parser.add_argument(
  157. '--modelpath',
  158. type=str,
  159. default='onnx_file/picodet_s_320_lcnet_postprocessed.onnx',
  160. help="onnx filepath")
  161. parser.add_argument(
  162. '--classfile',
  163. type=str,
  164. default='coco_label.txt',
  165. help="classname filepath")
  166. parser.add_argument(
  167. '--confThreshold', default=0.5, type=float, help='class confidence')
  168. parser.add_argument(
  169. '--nmsThreshold', default=0.6, type=float, help='nms iou thresh')
  170. parser.add_argument(
  171. "--img_fold", dest="img_fold", type=str, default="./imgs")
  172. parser.add_argument(
  173. "--result_fold", dest="result_fold", type=str, default="results")
  174. args = parser.parse_args()
  175. net = PicoDet(
  176. args.modelpath,
  177. args.classfile,
  178. prob_threshold=args.confThreshold,
  179. iou_threshold=args.nmsThreshold)
  180. net.detect_folder(args.img_fold, args.result_fold)
  181. print(
  182. f'infer results in ./deploy/third_engine/demo_onnxruntime/{args.result_fold}'
  183. )