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.

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