detect.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. # YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
  2. """
  3. Run YOLOv5 detection inference on images, videos, directories, globs, YouTube, webcam, streams, etc.
  4. Usage - sources:
  5. $ python detect.py --weights yolov5s.pt --source 0 # webcam
  6. img.jpg # image
  7. vid.mp4 # video
  8. screen # screenshot
  9. path/ # directory
  10. list.txt # list of images
  11. list.streams # list of streams
  12. 'path/*.jpg' # glob
  13. 'https://youtu.be/LNwODJXcvt4' # YouTube
  14. 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream
  15. Usage - formats:
  16. $ python detect.py --weights yolov5s.pt # PyTorch
  17. yolov5s.torchscript # TorchScript
  18. yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn
  19. yolov5s_openvino_model # OpenVINO
  20. yolov5s.engine # TensorRT
  21. yolov5s.mlmodel # CoreML (macOS-only)
  22. yolov5s_saved_model # TensorFlow SavedModel
  23. yolov5s.pb # TensorFlow GraphDef
  24. yolov5s.tflite # TensorFlow Lite
  25. yolov5s_edgetpu.tflite # TensorFlow Edge TPU
  26. yolov5s_paddle_model # PaddlePaddle
  27. """
  28. import argparse
  29. import csv
  30. import os
  31. import platform
  32. import sys
  33. from pathlib import Path
  34. import torch
  35. FILE = Path(__file__).resolve()
  36. ROOT = FILE.parents[0] # YOLOv5 root directory
  37. if str(ROOT) not in sys.path:
  38. sys.path.append(str(ROOT)) # add ROOT to PATH
  39. ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
  40. from ultralytics.utils.plotting import Annotator, colors, save_one_box
  41. from models.common import DetectMultiBackend
  42. from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams
  43. from utils.general import (
  44. LOGGER,
  45. Profile,
  46. check_file,
  47. check_img_size,
  48. check_imshow,
  49. colorstr,
  50. cv2,
  51. increment_path,
  52. non_max_suppression,
  53. print_args,
  54. scale_boxes,
  55. strip_optimizer,
  56. xyxy2xywh,
  57. )
  58. from utils.torch_utils import select_device, smart_inference_mode
  59. @smart_inference_mode()
  60. def run(
  61. weights=ROOT / "yolov5s.pt", # model path or triton URL
  62. source=ROOT / "data/images", # file/dir/URL/glob/screen/0(webcam)
  63. data=ROOT / "data/coco128.yaml", # dataset.yaml path
  64. imgsz=(640, 640), # inference size (height, width)
  65. conf_thres=0.25, # confidence threshold
  66. iou_thres=0.45, # NMS IOU threshold
  67. max_det=1000, # maximum detections per image
  68. device="", # cuda device, i.e. 0 or 0,1,2,3 or cpu
  69. view_img=False, # show results
  70. save_txt=False, # save results to *.txt
  71. save_csv=False, # save results in CSV format
  72. save_conf=False, # save confidences in --save-txt labels
  73. save_crop=False, # save cropped prediction boxes
  74. nosave=False, # do not save images/videos
  75. classes=None, # filter by class: --class 0, or --class 0 2 3
  76. agnostic_nms=False, # class-agnostic NMS
  77. augment=False, # augmented inference
  78. visualize=False, # visualize features
  79. update=False, # update all models
  80. project=ROOT / "runs/detect", # save results to project/name
  81. name="exp", # save results to project/name
  82. exist_ok=False, # existing project/name ok, do not increment
  83. line_thickness=3, # bounding box thickness (pixels)
  84. hide_labels=False, # hide labels
  85. hide_conf=False, # hide confidences
  86. half=False, # use FP16 half-precision inference
  87. dnn=False, # use OpenCV DNN for ONNX inference
  88. vid_stride=1, # video frame-rate stride
  89. ):
  90. source = str(source)
  91. save_img = not nosave and not source.endswith(".txt") # save inference images
  92. is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
  93. is_url = source.lower().startswith(("rtsp://", "rtmp://", "http://", "https://"))
  94. webcam = source.isnumeric() or source.endswith(".streams") or (is_url and not is_file)
  95. screenshot = source.lower().startswith("screen")
  96. if is_url and is_file:
  97. source = check_file(source) # download
  98. # Directories
  99. save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
  100. (save_dir / "labels" if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
  101. # Load model
  102. device = select_device(device)
  103. model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
  104. stride, names, pt = model.stride, model.names, model.pt
  105. imgsz = check_img_size(imgsz, s=stride) # check image size
  106. # Dataloader
  107. bs = 1 # batch_size
  108. if webcam:
  109. view_img = check_imshow(warn=True)
  110. dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
  111. bs = len(dataset)
  112. elif screenshot:
  113. dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt)
  114. else:
  115. dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
  116. vid_path, vid_writer = [None] * bs, [None] * bs
  117. # Run inference
  118. model.warmup(imgsz=(1 if pt or model.triton else bs, 3, *imgsz)) # warmup
  119. seen, windows, dt = 0, [], (Profile(device=device), Profile(device=device), Profile(device=device))
  120. for path, im, im0s, vid_cap, s in dataset:
  121. with dt[0]:
  122. im = torch.from_numpy(im).to(model.device)
  123. im = im.half() if model.fp16 else im.float() # uint8 to fp16/32
  124. im /= 255 # 0 - 255 to 0.0 - 1.0
  125. if len(im.shape) == 3:
  126. im = im[None] # expand for batch dim
  127. if model.xml and im.shape[0] > 1:
  128. ims = torch.chunk(im, im.shape[0], 0)
  129. # Inference
  130. with dt[1]:
  131. visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
  132. if model.xml and im.shape[0] > 1:
  133. pred = None
  134. for image in ims:
  135. if pred is None:
  136. pred = model(image, augment=augment, visualize=visualize).unsqueeze(0)
  137. else:
  138. pred = torch.cat((pred, model(image, augment=augment, visualize=visualize).unsqueeze(0)), dim=0)
  139. pred = [pred, None]
  140. else:
  141. pred = model(im, augment=augment, visualize=visualize)
  142. # NMS
  143. with dt[2]:
  144. pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
  145. # Second-stage classifier (optional)
  146. # pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)
  147. # Define the path for the CSV file
  148. csv_path = save_dir / "predictions.csv"
  149. # Create or append to the CSV file
  150. def write_to_csv(image_name, prediction, confidence):
  151. """Writes prediction data for an image to a CSV file, appending if the file exists."""
  152. data = {"Image Name": image_name, "Prediction": prediction, "Confidence": confidence}
  153. with open(csv_path, mode="a", newline="") as f:
  154. writer = csv.DictWriter(f, fieldnames=data.keys())
  155. if not csv_path.is_file():
  156. writer.writeheader()
  157. writer.writerow(data)
  158. # Process predictions
  159. for i, det in enumerate(pred): # per image
  160. seen += 1
  161. if webcam: # batch_size >= 1
  162. p, im0, frame = path[i], im0s[i].copy(), dataset.count
  163. s += f"{i}: "
  164. else:
  165. p, im0, frame = path, im0s.copy(), getattr(dataset, "frame", 0)
  166. p = Path(p) # to Path
  167. save_path = str(save_dir / p.name) # im.jpg
  168. txt_path = str(save_dir / "labels" / p.stem) + ("" if dataset.mode == "image" else f"_{frame}") # im.txt
  169. s += "%gx%g " % im.shape[2:] # print string
  170. gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
  171. imc = im0.copy() if save_crop else im0 # for save_crop
  172. annotator = Annotator(im0, line_width=line_thickness, example=str(names))
  173. if len(det):
  174. # Rescale boxes from img_size to im0 size
  175. det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round()
  176. # Print results
  177. for c in det[:, 5].unique():
  178. n = (det[:, 5] == c).sum() # detections per class
  179. s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
  180. # Write results
  181. for *xyxy, conf, cls in reversed(det):
  182. c = int(cls) # integer class
  183. label = names[c] if hide_conf else f"{names[c]}"
  184. confidence = float(conf)
  185. confidence_str = f"{confidence:.2f}"
  186. if save_csv:
  187. write_to_csv(p.name, label, confidence_str)
  188. if save_txt: # Write to file
  189. xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
  190. line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format
  191. with open(f"{txt_path}.txt", "a") as f:
  192. f.write(("%g " * len(line)).rstrip() % line + "\n")
  193. if save_img or save_crop or view_img: # Add bbox to image
  194. c = int(cls) # integer class
  195. label = None if hide_labels else (names[c] if hide_conf else f"{names[c]} {conf:.2f}")
  196. annotator.box_label(xyxy, label, color=colors(c, True))
  197. if save_crop:
  198. save_one_box(xyxy, imc, file=save_dir / "crops" / names[c] / f"{p.stem}.jpg", BGR=True)
  199. # Stream results
  200. im0 = annotator.result()
  201. if view_img:
  202. if platform.system() == "Linux" and p not in windows:
  203. windows.append(p)
  204. cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # allow window resize (Linux)
  205. cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
  206. cv2.imshow(str(p), im0)
  207. cv2.waitKey(1) # 1 millisecond
  208. # Save results (image with detections)
  209. if save_img:
  210. if dataset.mode == "image":
  211. cv2.imwrite(save_path, im0)
  212. else: # 'video' or 'stream'
  213. if vid_path[i] != save_path: # new video
  214. vid_path[i] = save_path
  215. if isinstance(vid_writer[i], cv2.VideoWriter):
  216. vid_writer[i].release() # release previous video writer
  217. if vid_cap: # video
  218. fps = vid_cap.get(cv2.CAP_PROP_FPS)
  219. w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  220. h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  221. else: # stream
  222. fps, w, h = 30, im0.shape[1], im0.shape[0]
  223. save_path = str(Path(save_path).with_suffix(".mp4")) # force *.mp4 suffix on results videos
  224. vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))
  225. vid_writer[i].write(im0)
  226. # Print time (inference-only)
  227. LOGGER.info(f"{s}{'' if len(det) else '(no detections), '}{dt[1].dt * 1E3:.1f}ms")
  228. # Print results
  229. t = tuple(x.t / seen * 1e3 for x in dt) # speeds per image
  230. LOGGER.info(f"Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}" % t)
  231. if save_txt or save_img:
  232. s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ""
  233. LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
  234. if update:
  235. strip_optimizer(weights[0]) # update model (to fix SourceChangeWarning)
  236. def parse_opt():
  237. """Parses command-line arguments for YOLOv5 detection, setting inference options and model configurations."""
  238. parser = argparse.ArgumentParser()
  239. parser.add_argument("--weights", nargs="+", type=str, default=ROOT / "yolov5s.pt", help="model path or triton URL")
  240. parser.add_argument("--source", type=str, default=ROOT / "data/images", help="file/dir/URL/glob/screen/0(webcam)")
  241. parser.add_argument("--data", type=str, default=ROOT / "data/coco128.yaml", help="(optional) dataset.yaml path")
  242. parser.add_argument("--imgsz", "--img", "--img-size", nargs="+", type=int, default=[640], help="inference size h,w")
  243. parser.add_argument("--conf-thres", type=float, default=0.25, help="confidence threshold")
  244. parser.add_argument("--iou-thres", type=float, default=0.45, help="NMS IoU threshold")
  245. parser.add_argument("--max-det", type=int, default=1000, help="maximum detections per image")
  246. parser.add_argument("--device", default="", help="cuda device, i.e. 0 or 0,1,2,3 or cpu")
  247. parser.add_argument("--view-img", action="store_true", help="show results")
  248. parser.add_argument("--save-txt", action="store_true", help="save results to *.txt")
  249. parser.add_argument("--save-csv", action="store_true", help="save results in CSV format")
  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. parser.add_argument("--vid-stride", type=int, default=1, help="video frame-rate stride")
  267. opt = parser.parse_args()
  268. opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
  269. print_args(vars(opt))
  270. return opt
  271. def main(opt):
  272. """Executes YOLOv5 model inference with given options, checking requirements before running the model."""
  273. check_requirements(ROOT / "requirements.txt", exclude=("tensorboard", "thop"))
  274. run(**vars(opt))
  275. if __name__ == "__main__":
  276. opt = parse_opt()
  277. main(opt)