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.

159 lines
6.9KB

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