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.

307 lines
15KB

  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 os
  9. import sys
  10. from pathlib import Path
  11. import cv2
  12. import numpy as np
  13. import torch
  14. import torch.backends.cudnn as cudnn
  15. FILE = Path(__file__).resolve()
  16. ROOT = FILE.parents[0] # YOLOv5 root directory
  17. if str(ROOT) not in sys.path:
  18. sys.path.append(str(ROOT)) # add ROOT to PATH
  19. ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
  20. from models.experimental import attempt_load
  21. from utils.datasets import LoadImages, LoadStreams
  22. from utils.general import apply_classifier, check_img_size, check_imshow, check_requirements, check_suffix, colorstr, \
  23. increment_path, non_max_suppression, print_args, save_one_box, scale_coords, strip_optimizer, xyxy2xywh, LOGGER
  24. from utils.plots import Annotator, colors
  25. from utils.torch_utils import load_classifier, select_device, time_sync
  26. @torch.no_grad()
  27. def run(weights=ROOT / 'yolov5s.pt', # model.pt path(s)
  28. source=ROOT / 'data/images', # file/dir/URL/glob, 0 for webcam
  29. imgsz=640, # inference size (pixels)
  30. conf_thres=0.25, # confidence threshold
  31. iou_thres=0.45, # NMS IOU threshold
  32. max_det=1000, # maximum detections per image
  33. device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
  34. view_img=False, # show results
  35. save_txt=False, # save results to *.txt
  36. save_conf=False, # save confidences in --save-txt labels
  37. save_crop=False, # save cropped prediction boxes
  38. nosave=False, # do not save images/videos
  39. classes=None, # filter by class: --class 0, or --class 0 2 3
  40. agnostic_nms=False, # class-agnostic NMS
  41. augment=False, # augmented inference
  42. visualize=False, # visualize features
  43. update=False, # update all models
  44. project=ROOT / 'runs/detect', # save results to project/name
  45. name='exp', # save results to project/name
  46. exist_ok=False, # existing project/name ok, do not increment
  47. line_thickness=3, # bounding box thickness (pixels)
  48. hide_labels=False, # hide labels
  49. hide_conf=False, # hide confidences
  50. half=False, # use FP16 half-precision inference
  51. dnn=False, # use OpenCV DNN for ONNX inference
  52. ):
  53. source = str(source)
  54. save_img = not nosave and not source.endswith('.txt') # save inference images
  55. webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
  56. ('rtsp://', 'rtmp://', 'http://', 'https://'))
  57. # Directories
  58. save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
  59. (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
  60. # Initialize
  61. device = select_device(device)
  62. half &= device.type != 'cpu' # half precision only supported on CUDA
  63. # Load model
  64. w = str(weights[0] if isinstance(weights, list) else weights)
  65. classify, suffix, suffixes = False, Path(w).suffix.lower(), ['.pt', '.onnx', '.tflite', '.pb', '']
  66. check_suffix(w, suffixes) # check weights have acceptable suffix
  67. pt, onnx, tflite, pb, saved_model = (suffix == x for x in suffixes) # backend booleans
  68. stride, names = 64, [f'class{i}' for i in range(1000)] # assign defaults
  69. if pt:
  70. model = torch.jit.load(w) if 'torchscript' in w else attempt_load(weights, map_location=device)
  71. stride = int(model.stride.max()) # model stride
  72. names = model.module.names if hasattr(model, 'module') else model.names # get class names
  73. if half:
  74. model.half() # to FP16
  75. if classify: # second-stage classifier
  76. modelc = load_classifier(name='resnet50', n=2) # initialize
  77. modelc.load_state_dict(torch.load('resnet50.pt', map_location=device)['model']).to(device).eval()
  78. elif onnx:
  79. if dnn:
  80. check_requirements(('opencv-python>=4.5.4',))
  81. net = cv2.dnn.readNetFromONNX(w)
  82. else:
  83. check_requirements(('onnx', 'onnxruntime-gpu' if torch.has_cuda else 'onnxruntime'))
  84. import onnxruntime
  85. session = onnxruntime.InferenceSession(w, None)
  86. else: # TensorFlow models
  87. check_requirements(('tensorflow>=2.4.1',))
  88. import tensorflow as tf
  89. if pb: # https://www.tensorflow.org/guide/migrate#a_graphpb_or_graphpbtxt
  90. def wrap_frozen_graph(gd, inputs, outputs):
  91. x = tf.compat.v1.wrap_function(lambda: tf.compat.v1.import_graph_def(gd, name=""), []) # wrapped import
  92. return x.prune(tf.nest.map_structure(x.graph.as_graph_element, inputs),
  93. tf.nest.map_structure(x.graph.as_graph_element, outputs))
  94. graph_def = tf.Graph().as_graph_def()
  95. graph_def.ParseFromString(open(w, 'rb').read())
  96. frozen_func = wrap_frozen_graph(gd=graph_def, inputs="x:0", outputs="Identity:0")
  97. elif saved_model:
  98. model = tf.keras.models.load_model(w)
  99. elif tflite:
  100. interpreter = tf.lite.Interpreter(model_path=w) # load TFLite model
  101. interpreter.allocate_tensors() # allocate
  102. input_details = interpreter.get_input_details() # inputs
  103. output_details = interpreter.get_output_details() # outputs
  104. int8 = input_details[0]['dtype'] == np.uint8 # is TFLite quantized uint8 model
  105. imgsz = check_img_size(imgsz, s=stride) # check image size
  106. # Dataloader
  107. if webcam:
  108. view_img = check_imshow()
  109. cudnn.benchmark = True # set True to speed up constant image size inference
  110. dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt)
  111. bs = len(dataset) # batch_size
  112. else:
  113. dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt)
  114. bs = 1 # batch_size
  115. vid_path, vid_writer = [None] * bs, [None] * bs
  116. # Run inference
  117. if pt and device.type != 'cpu':
  118. model(torch.zeros(1, 3, *imgsz).to(device).type_as(next(model.parameters()))) # run once
  119. dt, seen = [0.0, 0.0, 0.0], 0
  120. for path, img, im0s, vid_cap, s in dataset:
  121. t1 = time_sync()
  122. if onnx:
  123. img = img.astype('float32')
  124. else:
  125. img = torch.from_numpy(img).to(device)
  126. img = img.half() if half else img.float() # uint8 to fp16/32
  127. img /= 255.0 # 0 - 255 to 0.0 - 1.0
  128. if len(img.shape) == 3:
  129. img = img[None] # expand for batch dim
  130. t2 = time_sync()
  131. dt[0] += t2 - t1
  132. # Inference
  133. if pt:
  134. visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
  135. pred = model(img, augment=augment, visualize=visualize)[0]
  136. elif onnx:
  137. if dnn:
  138. net.setInput(img)
  139. pred = torch.tensor(net.forward())
  140. else:
  141. pred = torch.tensor(session.run([session.get_outputs()[0].name], {session.get_inputs()[0].name: img}))
  142. else: # tensorflow model (tflite, pb, saved_model)
  143. imn = img.permute(0, 2, 3, 1).cpu().numpy() # image in numpy
  144. if pb:
  145. pred = frozen_func(x=tf.constant(imn)).numpy()
  146. elif saved_model:
  147. pred = model(imn, training=False).numpy()
  148. elif tflite:
  149. if int8:
  150. scale, zero_point = input_details[0]['quantization']
  151. imn = (imn / scale + zero_point).astype(np.uint8) # de-scale
  152. interpreter.set_tensor(input_details[0]['index'], imn)
  153. interpreter.invoke()
  154. pred = interpreter.get_tensor(output_details[0]['index'])
  155. if int8:
  156. scale, zero_point = output_details[0]['quantization']
  157. pred = (pred.astype(np.float32) - zero_point) * scale # re-scale
  158. pred[..., 0] *= imgsz[1] # x
  159. pred[..., 1] *= imgsz[0] # y
  160. pred[..., 2] *= imgsz[1] # w
  161. pred[..., 3] *= imgsz[0] # h
  162. pred = torch.tensor(pred)
  163. t3 = time_sync()
  164. dt[1] += t3 - t2
  165. # NMS
  166. pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
  167. dt[2] += time_sync() - t3
  168. # Second-stage classifier (optional)
  169. if classify:
  170. pred = apply_classifier(pred, modelc, img, im0s)
  171. # Process predictions
  172. for i, det in enumerate(pred): # per image
  173. seen += 1
  174. if webcam: # batch_size >= 1
  175. p, im0, frame = path[i], im0s[i].copy(), dataset.count
  176. s += f'{i}: '
  177. else:
  178. p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)
  179. p = Path(p) # to Path
  180. save_path = str(save_dir / p.name) # img.jpg
  181. txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}') # img.txt
  182. s += '%gx%g ' % img.shape[2:] # print string
  183. gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
  184. imc = im0.copy() if save_crop else im0 # for save_crop
  185. annotator = Annotator(im0, line_width=line_thickness, example=str(names))
  186. if len(det):
  187. # Rescale boxes from img_size to im0 size
  188. det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
  189. # Print results
  190. for c in det[:, -1].unique():
  191. n = (det[:, -1] == c).sum() # detections per class
  192. s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
  193. # Write results
  194. for *xyxy, conf, cls in reversed(det):
  195. if save_txt: # Write to file
  196. xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
  197. line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
  198. with open(txt_path + '.txt', 'a') as f:
  199. f.write(('%g ' * len(line)).rstrip() % line + '\n')
  200. if save_img or save_crop or view_img: # Add bbox to image
  201. c = int(cls) # integer class
  202. label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
  203. annotator.box_label(xyxy, label, color=colors(c, True))
  204. if save_crop:
  205. save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)
  206. # Print time (inference-only)
  207. LOGGER.info(f'{s}Done. ({t3 - t2:.3f}s)')
  208. # Stream results
  209. im0 = annotator.result()
  210. if view_img:
  211. cv2.imshow(str(p), im0)
  212. cv2.waitKey(1) # 1 millisecond
  213. # Save results (image with detections)
  214. if save_img:
  215. if dataset.mode == 'image':
  216. cv2.imwrite(save_path, im0)
  217. else: # 'video' or 'stream'
  218. if vid_path[i] != save_path: # new video
  219. vid_path[i] = save_path
  220. if isinstance(vid_writer[i], cv2.VideoWriter):
  221. vid_writer[i].release() # release previous video writer
  222. if vid_cap: # video
  223. fps = vid_cap.get(cv2.CAP_PROP_FPS)
  224. w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  225. h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  226. else: # stream
  227. fps, w, h = 30, im0.shape[1], im0.shape[0]
  228. save_path += '.mp4'
  229. vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
  230. vid_writer[i].write(im0)
  231. # Print results
  232. t = tuple(x / seen * 1E3 for x in dt) # speeds per image
  233. LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)
  234. if save_txt or save_img:
  235. s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
  236. LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
  237. if update:
  238. strip_optimizer(weights) # update model (to fix SourceChangeWarning)
  239. def parse_opt():
  240. parser = argparse.ArgumentParser()
  241. parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model path(s)')
  242. parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob, 0 for webcam')
  243. parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')
  244. parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')
  245. parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
  246. parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
  247. parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  248. parser.add_argument('--view-img', action='store_true', help='show results')
  249. parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
  250. parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
  251. parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
  252. parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
  253. parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3')
  254. parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
  255. parser.add_argument('--augment', action='store_true', help='augmented inference')
  256. parser.add_argument('--visualize', action='store_true', help='visualize features')
  257. parser.add_argument('--update', action='store_true', help='update all models')
  258. parser.add_argument('--project', default=ROOT / 'runs/detect', help='save results to project/name')
  259. parser.add_argument('--name', default='exp', help='save results to project/name')
  260. parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
  261. parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
  262. parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
  263. parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
  264. parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
  265. parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
  266. opt = parser.parse_args()
  267. opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
  268. print_args(FILE.stem, opt)
  269. return opt
  270. def main(opt):
  271. check_requirements(exclude=('tensorboard', 'thop'))
  272. run(**vars(opt))
  273. if __name__ == "__main__":
  274. opt = parse_opt()
  275. main(opt)