Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

183 linhas
7.7KB

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