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.

315 lines
16KB

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