You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

169 line
7.1KB

  1. import argparse
  2. from utils.datasets import *
  3. from utils.utils import *
  4. ONNX_EXPORT = False
  5. def detect(save_img=False):
  6. out, source, weights, half, view_img, save_txt, imgsz = \
  7. opt.output, opt.source, opt.weights, opt.half, opt.view_img, opt.save_txt, opt.img_size
  8. webcam = source == '0' or source.startswith('rtsp') or source.startswith('http') or source.endswith('.txt')
  9. # Initialize
  10. device = torch_utils.select_device(opt.device)
  11. if os.path.exists(out):
  12. shutil.rmtree(out) # delete output folder
  13. os.makedirs(out) # make new output folder
  14. # Load model
  15. google_utils.attempt_download(weights)
  16. model = torch.load(weights, map_location=device)['model']
  17. # torch.save(torch.load(weights, map_location=device), weights) # update model if SourceChangeWarning
  18. # Second-stage classifier
  19. classify = False
  20. if classify:
  21. modelc = torch_utils.load_classifier(name='resnet101', n=2) # initialize
  22. modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']) # load weights
  23. modelc.to(device).eval()
  24. # Eval mode
  25. model.to(device).eval()
  26. # Fuse Conv2d + BatchNorm2d layers
  27. # model.fuse()
  28. # Half precision
  29. half = half and device.type != 'cpu' # half precision only supported on CUDA
  30. if half:
  31. model.half()
  32. # Set Dataloader
  33. vid_path, vid_writer = None, None
  34. if webcam:
  35. view_img = True
  36. torch.backends.cudnn.benchmark = True # set True to speed up constant image size inference
  37. dataset = LoadStreams(source, img_size=imgsz)
  38. else:
  39. save_img = True
  40. dataset = LoadImages(source, img_size=imgsz)
  41. # Get names and colors
  42. names = model.names if hasattr(model, 'names') else model.modules.names
  43. colors = [[random.randint(0, 255) for _ in range(3)] for _ in range(len(names))]
  44. # Run inference
  45. t0 = time.time()
  46. img = torch.zeros((1, 3, imgsz, imgsz), device=device) # init img
  47. _ = model(img.half() if half else img.float()) if device.type != 'cpu' else None # run once
  48. for path, img, im0s, vid_cap in dataset:
  49. img = torch.from_numpy(img).to(device)
  50. img = img.half() if half else img.float() # uint8 to fp16/32
  51. img /= 255.0 # 0 - 255 to 0.0 - 1.0
  52. if img.ndimension() == 3:
  53. img = img.unsqueeze(0)
  54. # Inference
  55. t1 = torch_utils.time_synchronized()
  56. pred = model(img, augment=opt.augment)[0]
  57. t2 = torch_utils.time_synchronized()
  58. # to float
  59. if half:
  60. pred = pred.float()
  61. # Apply NMS
  62. pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres,
  63. fast=True, classes=opt.classes, agnostic=opt.agnostic_nms)
  64. # Apply Classifier
  65. if classify:
  66. pred = apply_classifier(pred, modelc, img, im0s)
  67. # Process detections
  68. for i, det in enumerate(pred): # detections per image
  69. if webcam: # batch_size >= 1
  70. p, s, im0 = path[i], '%g: ' % i, im0s[i].copy()
  71. else:
  72. p, s, im0 = path, '', im0s
  73. save_path = str(Path(out) / Path(p).name)
  74. s += '%gx%g ' % img.shape[2:] # print string
  75. gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] #  normalization gain whwh
  76. if det is not None and len(det):
  77. # Rescale boxes from img_size to im0 size
  78. det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
  79. # Print results
  80. for c in det[:, -1].unique():
  81. n = (det[:, -1] == c).sum() # detections per class
  82. s += '%g %ss, ' % (n, names[int(c)]) # add to string
  83. # Write results
  84. for *xyxy, conf, cls in det:
  85. if save_txt: # Write to file
  86. xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
  87. with open(save_path[:save_path.rfind('.')] + '.txt', 'a') as file:
  88. file.write(('%g ' * 5 + '\n') % (cls, *xywh)) # label format
  89. if save_img or view_img: # Add bbox to image
  90. label = '%s %.2f' % (names[int(cls)], conf)
  91. plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3)
  92. # Print time (inference + NMS)
  93. print('%sDone. (%.3fs)' % (s, t2 - t1))
  94. # Stream results
  95. if view_img:
  96. cv2.imshow(p, im0)
  97. if cv2.waitKey(1) == ord('q'): # q to quit
  98. raise StopIteration
  99. # Save results (image with detections)
  100. if save_img:
  101. if dataset.mode == 'images':
  102. cv2.imwrite(save_path, im0)
  103. else:
  104. if vid_path != save_path: # new video
  105. vid_path = save_path
  106. if isinstance(vid_writer, cv2.VideoWriter):
  107. vid_writer.release() # release previous video writer
  108. fps = vid_cap.get(cv2.CAP_PROP_FPS)
  109. w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  110. h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  111. vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*opt.fourcc), fps, (w, h))
  112. vid_writer.write(im0)
  113. if save_txt or save_img:
  114. print('Results saved to %s' % os.getcwd() + os.sep + out)
  115. if platform == 'darwin': # MacOS
  116. os.system('open ' + save_path)
  117. print('Done. (%.3fs)' % (time.time() - t0))
  118. if __name__ == '__main__':
  119. parser = argparse.ArgumentParser()
  120. parser.add_argument('--weights', type=str, default='weights/yolov5s.pt', help='model.pt path')
  121. parser.add_argument('--source', type=str, default='inference/images', help='source') # file/folder, 0 for webcam
  122. parser.add_argument('--output', type=str, default='inference/output', help='output folder') # output folder
  123. parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
  124. parser.add_argument('--conf-thres', type=float, default=0.4, help='object confidence threshold')
  125. parser.add_argument('--iou-thres', type=float, default=0.5, help='IOU threshold for NMS')
  126. parser.add_argument('--fourcc', type=str, default='mp4v', help='output video codec (verify ffmpeg support)')
  127. parser.add_argument('--half', action='store_true', help='half precision FP16 inference')
  128. parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  129. parser.add_argument('--view-img', action='store_true', help='display results')
  130. parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
  131. parser.add_argument('--classes', nargs='+', type=int, help='filter by class')
  132. parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
  133. parser.add_argument('--augment', action='store_true', help='augmented inference')
  134. opt = parser.parse_args()
  135. print(opt)
  136. with torch.no_grad():
  137. detect()