Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

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