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

205 行
10KB

  1. import argparse
  2. import time
  3. from pathlib import Path
  4. import cv2
  5. import torch
  6. import torch.backends.cudnn as cudnn
  7. from models.experimental import attempt_load
  8. from utils.datasets import LoadStreams, LoadImages
  9. from utils.general import check_img_size, check_requirements, check_imshow, non_max_suppression, apply_classifier, \
  10. scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path, save_one_box
  11. from utils.plots import colors, plot_one_box
  12. from utils.torch_utils import select_device, load_classifier, time_synchronized
  13. @torch.no_grad()
  14. def detect(weights='yolov5s.pt', # model.pt path(s)
  15. source='data/images', # file/dir/URL/glob, 0 for webcam
  16. imgsz=640, # inference size (pixels)
  17. conf_thres=0.25, # confidence threshold
  18. iou_thres=0.45, # NMS IOU threshold
  19. max_det=1000, # maximum detections per image
  20. device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
  21. view_img=False, # show results
  22. save_txt=False, # save results to *.txt
  23. save_conf=False, # save confidences in --save-txt labels
  24. save_crop=False, # save cropped prediction boxes
  25. nosave=False, # do not save images/videos
  26. classes=None, # filter by class: --class 0, or --class 0 2 3
  27. agnostic_nms=False, # class-agnostic NMS
  28. augment=False, # augmented inference
  29. update=False, # update all models
  30. project='runs/detect', # save results to project/name
  31. name='exp', # save results to project/name
  32. exist_ok=False, # existing project/name ok, do not increment
  33. line_thickness=3, # bounding box thickness (pixels)
  34. hide_labels=False, # hide labels
  35. hide_conf=False, # hide confidences
  36. half=False, # use FP16 half-precision inference
  37. ):
  38. save_img = not nosave and not source.endswith('.txt') # save inference images
  39. webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
  40. ('rtsp://', 'rtmp://', 'http://', 'https://'))
  41. # Directories
  42. save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
  43. (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
  44. # Initialize
  45. set_logging()
  46. device = select_device(device)
  47. half &= device.type != 'cpu' # half precision only supported on CUDA
  48. # Load model
  49. model = attempt_load(weights, map_location=device) # load FP32 model
  50. stride = int(model.stride.max()) # model stride
  51. imgsz = check_img_size(imgsz, s=stride) # check image size
  52. names = model.module.names if hasattr(model, 'module') else model.names # get class names
  53. if half:
  54. model.half() # to FP16
  55. # Second-stage classifier
  56. classify = False
  57. if classify:
  58. modelc = load_classifier(name='resnet50', n=2) # initialize
  59. modelc.load_state_dict(torch.load('resnet50.pt', map_location=device)['model']).to(device).eval()
  60. # Set Dataloader
  61. vid_path, vid_writer = None, None
  62. if webcam:
  63. view_img = check_imshow()
  64. cudnn.benchmark = True # set True to speed up constant image size inference
  65. dataset = LoadStreams(source, img_size=imgsz, stride=stride)
  66. else:
  67. dataset = LoadImages(source, img_size=imgsz, stride=stride)
  68. # Run inference
  69. if device.type != 'cpu':
  70. model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once
  71. t0 = time.time()
  72. for path, img, im0s, vid_cap in dataset:
  73. img = torch.from_numpy(img).to(device)
  74. img = img.half() if half else img.float() # uint8 to fp16/32
  75. img /= 255.0 # 0 - 255 to 0.0 - 1.0
  76. if img.ndimension() == 3:
  77. img = img.unsqueeze(0)
  78. # Inference
  79. t1 = time_synchronized()
  80. pred = model(img, augment=augment)[0]
  81. # Apply NMS
  82. pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
  83. t2 = time_synchronized()
  84. # Apply Classifier
  85. if classify:
  86. pred = apply_classifier(pred, modelc, img, im0s)
  87. # Process detections
  88. for i, det in enumerate(pred): # detections per image
  89. if webcam: # batch_size >= 1
  90. p, s, im0, frame = path[i], f'{i}: ', im0s[i].copy(), dataset.count
  91. else:
  92. p, s, im0, frame = path, '', im0s.copy(), getattr(dataset, 'frame', 0)
  93. p = Path(p) # to Path
  94. save_path = str(save_dir / p.name) # img.jpg
  95. txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
  96. s += '%gx%g ' % img.shape[2:] # print string
  97. gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
  98. imc = im0.copy() if save_crop else im0 # for save_crop
  99. if len(det):
  100. # Rescale boxes from img_size to im0 size
  101. det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
  102. # Print results
  103. for c in det[:, -1].unique():
  104. n = (det[:, -1] == c).sum() # detections per class
  105. s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
  106. # Write results
  107. for *xyxy, conf, cls in reversed(det):
  108. if save_txt: # Write to file
  109. xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
  110. line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
  111. with open(txt_path + '.txt', 'a') as f:
  112. f.write(('%g ' * len(line)).rstrip() % line + '\n')
  113. if save_img or save_crop or view_img: # Add bbox to image
  114. c = int(cls) # integer class
  115. label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
  116. plot_one_box(xyxy, im0, label=label, color=colors(c, True), line_thickness=line_thickness)
  117. if save_crop:
  118. save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
  119. # Print time (inference + NMS)
  120. print(f'{s}Done. ({t2 - t1:.3f}s)')
  121. # Stream results
  122. if view_img:
  123. cv2.imshow(str(p), im0)
  124. cv2.waitKey(1) # 1 millisecond
  125. # Save results (image with detections)
  126. if save_img:
  127. if dataset.mode == 'image':
  128. cv2.imwrite(save_path, im0)
  129. else: # 'video' or 'stream'
  130. if vid_path != save_path: # new video
  131. vid_path = save_path
  132. if isinstance(vid_writer, cv2.VideoWriter):
  133. vid_writer.release() # release previous video writer
  134. if vid_cap: # video
  135. fps = vid_cap.get(cv2.CAP_PROP_FPS)
  136. w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  137. h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  138. else: # stream
  139. fps, w, h = 30, im0.shape[1], im0.shape[0]
  140. save_path += '.mp4'
  141. vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
  142. vid_writer.write(im0)
  143. if save_txt or save_img:
  144. s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
  145. print(f"Results saved to {save_dir}{s}")
  146. if update:
  147. strip_optimizer(weights) # update model (to fix SourceChangeWarning)
  148. print(f'Done. ({time.time() - t0:.3f}s)')
  149. if __name__ == '__main__':
  150. parser = argparse.ArgumentParser()
  151. parser.add_argument('--weights', nargs='+', type=str, default='yolov5s.pt', help='model.pt path(s)')
  152. parser.add_argument('--source', type=str, default='data/images', help='file/dir/URL/glob, 0 for webcam')
  153. parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='inference size (pixels)')
  154. parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')
  155. parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
  156. parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
  157. parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  158. parser.add_argument('--view-img', action='store_true', help='show results')
  159. parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
  160. parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
  161. parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
  162. parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
  163. parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
  164. parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
  165. parser.add_argument('--augment', action='store_true', help='augmented inference')
  166. parser.add_argument('--update', action='store_true', help='update all models')
  167. parser.add_argument('--project', default='runs/detect', help='save results to project/name')
  168. parser.add_argument('--name', default='exp', help='save results to project/name')
  169. parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
  170. parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
  171. parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
  172. parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
  173. parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
  174. opt = parser.parse_args()
  175. print(opt)
  176. check_requirements(exclude=('tensorboard', 'thop'))
  177. detect(**vars(opt))