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.

242 lines
12KB

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