您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

157 行
6.9KB

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