TensorRT转化代码
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

240 lines
12KB

  1. """Run inference with a YOLOv5 model on images, videos, directories, streams
  2. Usage:
  3. $ python path/to/detect.py --source path/to/img.jpg --weights yolov5s.pt --img 640
  4. """
  5. import argparse
  6. import sys
  7. import time
  8. from pathlib import Path
  9. import cv2
  10. import torch
  11. import torch.backends.cudnn as cudnn
  12. FILE = Path(__file__).absolute()
  13. sys.path.append(FILE.parents[0].as_posix()) # add yolov5/ to path
  14. from models.experimental import attempt_load
  15. from utils.datasets import LoadStreams, LoadImages
  16. from utils.general import check_img_size, check_requirements, check_imshow, colorstr, non_max_suppression, \
  17. apply_classifier, scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path, save_one_box
  18. from utils.plots import colors, plot_one_box
  19. from utils.torch_utils import select_device, load_classifier, time_sync
  20. @torch.no_grad()
  21. def run(weights='yolov5s.pt', # model.pt path(s)
  22. source='data/images', # file/dir/URL/glob, 0 for webcam
  23. imgsz=640, # inference size (pixels)
  24. conf_thres=0.25, # confidence threshold
  25. iou_thres=0.45, # NMS IOU threshold
  26. max_det=1000, # maximum detections per image
  27. device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
  28. view_img=False, # show results
  29. save_txt=False, # save results to *.txt
  30. save_conf=False, # save confidences in --save-txt labels
  31. save_crop=False, # save cropped prediction boxes
  32. nosave=False, # do not save images/videos
  33. classes=None, # filter by class: --class 0, or --class 0 2 3
  34. agnostic_nms=False, # class-agnostic NMS
  35. augment=False, # augmented inference
  36. visualize=False, # visualize features
  37. update=False, # update all models
  38. project='runs/detect', # save results to project/name
  39. name='exp', # save results to project/name
  40. exist_ok=False, # existing project/name ok, do not increment
  41. line_thickness=3, # bounding box thickness (pixels)
  42. hide_labels=False, # hide labels
  43. hide_conf=False, # hide confidences
  44. half=False, # use FP16 half-precision inference
  45. ):
  46. save_img = not nosave and not source.endswith('.txt') # save inference images
  47. webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
  48. ('rtsp://', 'rtmp://', 'http://', 'https://'))
  49. # Directories
  50. save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
  51. (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
  52. # Initialize
  53. set_logging()
  54. device = select_device(device)
  55. half &= device.type != 'cpu' # half precision only supported on CUDA
  56. # Load model
  57. w = weights[0] if isinstance(weights, list) else weights
  58. classify, pt, onnx = False, w.endswith('.pt'), w.endswith('.onnx') # inference type
  59. stride, names = 64, [f'class{i}' for i in range(1000)] # assign defaults
  60. if pt:
  61. model = attempt_load(weights, map_location=device) # load FP32 model
  62. stride = int(model.stride.max()) # model stride
  63. names = model.module.names if hasattr(model, 'module') else model.names # get class names
  64. if half:
  65. model.half() # to FP16
  66. if classify: # second-stage classifier
  67. modelc = load_classifier(name='resnet50', n=2) # initialize
  68. modelc.load_state_dict(torch.load('resnet50.pt', map_location=device)['model']).to(device).eval()
  69. elif onnx:
  70. check_requirements(('onnx', 'onnxruntime'))
  71. import onnxruntime
  72. session = onnxruntime.InferenceSession(w, None)
  73. imgsz = check_img_size(imgsz, s=stride) # check image size
  74. # Dataloader
  75. if webcam:
  76. view_img = check_imshow()
  77. cudnn.benchmark = True # set True to speed up constant image size inference
  78. dataset = LoadStreams(source, img_size=imgsz, stride=stride)
  79. bs = len(dataset) # batch_size
  80. else:
  81. dataset = LoadImages(source, img_size=imgsz, stride=stride)
  82. bs = 1 # batch_size
  83. vid_path, vid_writer = [None] * bs, [None] * bs
  84. # Run inference
  85. if pt and device.type != 'cpu':
  86. model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once
  87. t0 = time.time()
  88. for path, img, im0s, vid_cap in dataset:
  89. if pt:
  90. img = torch.from_numpy(img).to(device)
  91. img = img.half() if half else img.float() # uint8 to fp16/32
  92. elif onnx:
  93. img = img.astype('float32')
  94. img /= 255.0 # 0 - 255 to 0.0 - 1.0
  95. if len(img.shape) == 3:
  96. img = img[None] # expand for batch dim
  97. # Inference
  98. t1 = time_sync()
  99. if pt:
  100. visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
  101. pred = model(img, augment=augment, visualize=visualize)[0]
  102. elif onnx:
  103. pred = torch.tensor(session.run([session.get_outputs()[0].name], {session.get_inputs()[0].name: img}))
  104. # NMS
  105. pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
  106. t2 = time_sync()
  107. # Second-stage classifier (optional)
  108. if classify:
  109. pred = apply_classifier(pred, modelc, img, im0s)
  110. # Process predictions
  111. for i, det in enumerate(pred): # detections per image
  112. if webcam: # batch_size >= 1
  113. p, s, im0, frame = path[i], f'{i}: ', im0s[i].copy(), dataset.count
  114. else:
  115. p, s, im0, frame = path, '', im0s.copy(), getattr(dataset, 'frame', 0)
  116. p = Path(p) # to Path
  117. save_path = str(save_dir / p.name) # img.jpg
  118. txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
  119. s += '%gx%g ' % img.shape[2:] # print string
  120. gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
  121. imc = im0.copy() if save_crop else im0 # for save_crop
  122. if len(det):
  123. # Rescale boxes from img_size to im0 size
  124. det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
  125. # Print results
  126. for c in det[:, -1].unique():
  127. n = (det[:, -1] == c).sum() # detections per class
  128. s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
  129. # Write results
  130. for *xyxy, conf, cls in reversed(det):
  131. if save_txt: # Write to file
  132. xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
  133. line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
  134. with open(txt_path + '.txt', 'a') as f:
  135. f.write(('%g ' * len(line)).rstrip() % line + '\n')
  136. if save_img or save_crop or view_img: # Add bbox to image
  137. c = int(cls) # integer class
  138. label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
  139. plot_one_box(xyxy, im0, label=label, color=colors(c, True), line_thickness=line_thickness)
  140. if save_crop:
  141. save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
  142. # Print time (inference + NMS)
  143. print(f'{s}Done. ({t2 - t1:.3f}s)')
  144. # Stream results
  145. if view_img:
  146. cv2.imshow(str(p), im0)
  147. cv2.waitKey(1) # 1 millisecond
  148. # Save results (image with detections)
  149. if save_img:
  150. if dataset.mode == 'image':
  151. cv2.imwrite(save_path, im0)
  152. else: # 'video' or 'stream'
  153. if vid_path[i] != save_path: # new video
  154. vid_path[i] = save_path
  155. if isinstance(vid_writer[i], cv2.VideoWriter):
  156. vid_writer[i].release() # release previous video writer
  157. if vid_cap: # video
  158. fps = vid_cap.get(cv2.CAP_PROP_FPS)
  159. w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  160. h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  161. else: # stream
  162. fps, w, h = 30, im0.shape[1], im0.shape[0]
  163. save_path += '.mp4'
  164. vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
  165. vid_writer[i].write(im0)
  166. if save_txt or save_img:
  167. s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
  168. print(f"Results saved to {colorstr('bold', save_dir)}{s}")
  169. if update:
  170. strip_optimizer(weights) # update model (to fix SourceChangeWarning)
  171. print(f'Done. ({time.time() - t0:.3f}s)')
  172. def parse_opt():
  173. parser = argparse.ArgumentParser()
  174. parser.add_argument('--weights', nargs='+', type=str, default='weights/smogfire_20230105.pt', help='model.pt path(s)')
  175. #parser.add_argument('--source', type=str, default='image', help='file/dir/URL/glob, 0 for webcam')
  176. parser.add_argument('--source', type=str, default='/home/thsw/WJ/nyh_submission/0_smogfire/image_for_test', help='file/dir/URL/glob, 0 for webcam')
  177. parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='inference size (pixels)')
  178. parser.add_argument('--conf-thres', type=float, default=0.5, help='confidence threshold')
  179. parser.add_argument('--iou-thres', type=float, default=0.7, help='NMS IoU threshold')
  180. parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
  181. parser.add_argument('--device', default='0,1', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  182. parser.add_argument('--view-img', action='store_true', help='show results')
  183. parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
  184. parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
  185. parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
  186. parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
  187. parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
  188. parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
  189. parser.add_argument('--augment', action='store_true', help='augmented inference')
  190. parser.add_argument('--visualize', action='store_true', help='visualize features')
  191. parser.add_argument('--update', action='store_true', help='update all models')
  192. parser.add_argument('--project', default='runs/detect', help='save results to project/name')
  193. parser.add_argument('--name', default='exp', help='save results to project/name')
  194. parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
  195. parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
  196. parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
  197. parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
  198. parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
  199. opt = parser.parse_args()
  200. return opt
  201. def main(opt):
  202. print(colorstr('detect: ') + ', '.join(f'{k}={v}' for k, v in vars(opt).items()))
  203. check_requirements(exclude=('tensorboard', 'thop'))
  204. run(**vars(opt))
  205. if __name__ == "__main__":
  206. opt = parse_opt()
  207. main(opt)