Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

#13643 Fix deprecation warning for `pkg_resources` dependency by changing to `packaging`

Merged
Ghost merged 1 commits into Ultralytics:master from ultralytics:fix-pkg-resource-dep
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
  1. # Ultralytics ๐Ÿš€ AGPL-3.0 License - https://ultralytics.com/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.mlpackage # 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. check_requirements,
  50. colorstr,
  51. cv2,
  52. increment_path,
  53. non_max_suppression,
  54. print_args,
  55. scale_boxes,
  56. strip_optimizer,
  57. xyxy2xywh,
  58. )
  59. from utils.torch_utils import select_device, smart_inference_mode
  60. @smart_inference_mode()
  61. def run(
  62. weights=ROOT / "yolov5s.pt", # model path or triton URL
  63. source=ROOT / "data/images", # file/dir/URL/glob/screen/0(webcam)
  64. data=ROOT / "data/coco128.yaml", # dataset.yaml path
  65. imgsz=(640, 640), # inference size (height, width)
  66. conf_thres=0.25, # confidence threshold
  67. iou_thres=0.45, # NMS IOU threshold
  68. max_det=1000, # maximum detections per image
  69. device="", # cuda device, i.e. 0 or 0,1,2,3 or cpu
  70. view_img=False, # show results
  71. save_txt=False, # save results to *.txt
  72. save_format=0, # save boxes coordinates in YOLO format or Pascal-VOC format (0 for YOLO and 1 for Pascal-VOC)
  73. save_csv=False, # save results in CSV format
  74. save_conf=False, # save confidences in --save-txt labels
  75. save_crop=False, # save cropped prediction boxes
  76. nosave=False, # do not save images/videos
  77. classes=None, # filter by class: --class 0, or --class 0 2 3
  78. agnostic_nms=False, # class-agnostic NMS
  79. augment=False, # augmented inference
  80. visualize=False, # visualize features
  81. update=False, # update all models
  82. project=ROOT / "runs/detect", # save results to project/name
  83. name="exp", # save results to project/name
  84. exist_ok=False, # existing project/name ok, do not increment
  85. line_thickness=3, # bounding box thickness (pixels)
  86. hide_labels=False, # hide labels
  87. hide_conf=False, # hide confidences
  88. half=False, # use FP16 half-precision inference
  89. dnn=False, # use OpenCV DNN for ONNX inference
  90. vid_stride=1, # video frame-rate stride
  91. ):
  92. """
  93. Runs YOLOv5 detection inference on various sources like images, videos, directories, streams, etc.
  94. Args:
  95. weights (str | Path): Path to the model weights file or a Triton URL. Default is 'yolov5s.pt'.
  96. source (str | Path): Input source, which can be a file, directory, URL, glob pattern, screen capture, or webcam
  97. index. Default is 'data/images'.
  98. data (str | Path): Path to the dataset YAML file. Default is 'data/coco128.yaml'.
  99. imgsz (tuple[int, int]): Inference image size as a tuple (height, width). Default is (640, 640).
  100. conf_thres (float): Confidence threshold for detections. Default is 0.25.
  101. iou_thres (float): Intersection Over Union (IOU) threshold for non-max suppression. Default is 0.45.
  102. max_det (int): Maximum number of detections per image. Default is 1000.
  103. device (str): CUDA device identifier (e.g., '0' or '0,1,2,3') or 'cpu'. Default is an empty string, which uses the
  104. best available device.
  105. view_img (bool): If True, display inference results using OpenCV. Default is False.
  106. save_txt (bool): If True, save results in a text file. Default is False.
  107. save_csv (bool): If True, save results in a CSV file. Default is False.
  108. save_conf (bool): If True, include confidence scores in the saved results. Default is False.
  109. save_crop (bool): If True, save cropped prediction boxes. Default is False.
  110. nosave (bool): If True, do not save inference images or videos. Default is False.
  111. classes (list[int]): List of class indices to filter detections by. Default is None.
  112. agnostic_nms (bool): If True, perform class-agnostic non-max suppression. Default is False.
  113. augment (bool): If True, use augmented inference. Default is False.
  114. visualize (bool): If True, visualize feature maps. Default is False.
  115. update (bool): If True, update all models' weights. Default is False.
  116. project (str | Path): Directory to save results. Default is 'runs/detect'.
  117. name (str): Name of the current experiment; used to create a subdirectory within 'project'. Default is 'exp'.
  118. exist_ok (bool): If True, existing directories with the same name are reused instead of being incremented. Default is
  119. False.
  120. line_thickness (int): Thickness of bounding box lines in pixels. Default is 3.
  121. hide_labels (bool): If True, do not display labels on bounding boxes. Default is False.
  122. hide_conf (bool): If True, do not display confidence scores on bounding boxes. Default is False.
  123. half (bool): If True, use FP16 half-precision inference. Default is False.
  124. dnn (bool): If True, use OpenCV DNN backend for ONNX inference. Default is False.
  125. vid_stride (int): Stride for processing video frames, to skip frames between processing. Default is 1.
  126. Returns:
  127. None
  128. Examples:
  129. ```python
  130. from ultralytics import run
  131. # Run inference on an image
  132. run(source='data/images/example.jpg', weights='yolov5s.pt', device='0')
  133. # Run inference on a video with specific confidence threshold
  134. run(source='data/videos/example.mp4', weights='yolov5s.pt', conf_thres=0.4, device='0')
  135. ```
  136. """
  137. source = str(source)
  138. save_img = not nosave and not source.endswith(".txt") # save inference images
  139. is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
  140. is_url = source.lower().startswith(("rtsp://", "rtmp://", "http://", "https://"))
  141. webcam = source.isnumeric() or source.endswith(".streams") or (is_url and not is_file)
  142. screenshot = source.lower().startswith("screen")
  143. if is_url and is_file:
  144. source = check_file(source) # download
  145. # Directories
  146. save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
  147. (save_dir / "labels" if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
  148. # Load model
  149. device = select_device(device)
  150. model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
  151. stride, names, pt = model.stride, model.names, model.pt
  152. imgsz = check_img_size(imgsz, s=stride) # check image size
  153. # Dataloader
  154. bs = 1 # batch_size
  155. if webcam:
  156. view_img = check_imshow(warn=True)
  157. dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
  158. bs = len(dataset)
  159. elif screenshot:
  160. dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt)
  161. else:
  162. dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
  163. vid_path, vid_writer = [None] * bs, [None] * bs
  164. # Run inference
  165. model.warmup(imgsz=(1 if pt or model.triton else bs, 3, *imgsz)) # warmup
  166. seen, windows, dt = 0, [], (Profile(device=device), Profile(device=device), Profile(device=device))
  167. for path, im, im0s, vid_cap, s in dataset:
  168. with dt[0]:
  169. im = torch.from_numpy(im).to(model.device)
  170. im = im.half() if model.fp16 else im.float() # uint8 to fp16/32
  171. im /= 255 # 0 - 255 to 0.0 - 1.0
  172. if len(im.shape) == 3:
  173. im = im[None] # expand for batch dim
  174. if model.xml and im.shape[0] > 1:
  175. ims = torch.chunk(im, im.shape[0], 0)
  176. # Inference
  177. with dt[1]:
  178. visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
  179. if model.xml and im.shape[0] > 1:
  180. pred = None
  181. for image in ims:
  182. if pred is None:
  183. pred = model(image, augment=augment, visualize=visualize).unsqueeze(0)
  184. else:
  185. pred = torch.cat((pred, model(image, augment=augment, visualize=visualize).unsqueeze(0)), dim=0)
  186. pred = [pred, None]
  187. else:
  188. pred = model(im, augment=augment, visualize=visualize)
  189. # NMS
  190. with dt[2]:
  191. pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
  192. # Second-stage classifier (optional)
  193. # pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)
  194. # Define the path for the CSV file
  195. csv_path = save_dir / "predictions.csv"
  196. # Create or append to the CSV file
  197. def write_to_csv(image_name, prediction, confidence):
  198. """Writes prediction data for an image to a CSV file, appending if the file exists."""
  199. data = {"Image Name": image_name, "Prediction": prediction, "Confidence": confidence}
  200. file_exists = os.path.isfile(csv_path)
  201. with open(csv_path, mode="a", newline="") as f:
  202. writer = csv.DictWriter(f, fieldnames=data.keys())
  203. if not file_exists:
  204. writer.writeheader()
  205. writer.writerow(data)
  206. # Process predictions
  207. for i, det in enumerate(pred): # per image
  208. seen += 1
  209. if webcam: # batch_size >= 1
  210. p, im0, frame = path[i], im0s[i].copy(), dataset.count
  211. s += f"{i}: "
  212. else:
  213. p, im0, frame = path, im0s.copy(), getattr(dataset, "frame", 0)
  214. p = Path(p) # to Path
  215. save_path = str(save_dir / p.name) # im.jpg
  216. txt_path = str(save_dir / "labels" / p.stem) + ("" if dataset.mode == "image" else f"_{frame}") # im.txt
  217. s += "{:g}x{:g} ".format(*im.shape[2:]) # print string
  218. gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
  219. imc = im0.copy() if save_crop else im0 # for save_crop
  220. annotator = Annotator(im0, line_width=line_thickness, example=str(names))
  221. if len(det):
  222. # Rescale boxes from img_size to im0 size
  223. det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round()
  224. # Print results
  225. for c in det[:, 5].unique():
  226. n = (det[:, 5] == c).sum() # detections per class
  227. s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
  228. # Write results
  229. for *xyxy, conf, cls in reversed(det):
  230. c = int(cls) # integer class
  231. label = names[c] if hide_conf else f"{names[c]}"
  232. confidence = float(conf)
  233. confidence_str = f"{confidence:.2f}"
  234. if save_csv:
  235. write_to_csv(p.name, label, confidence_str)
  236. if save_txt: # Write to file
  237. if save_format == 0:
  238. coords = (
  239. (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()
  240. ) # normalized xywh
  241. else:
  242. coords = (torch.tensor(xyxy).view(1, 4) / gn).view(-1).tolist() # xyxy
  243. line = (cls, *coords, conf) if save_conf else (cls, *coords) # label format
  244. with open(f"{txt_path}.txt", "a") as f:
  245. f.write(("%g " * len(line)).rstrip() % line + "\n")
  246. if save_img or save_crop or view_img: # Add bbox to image
  247. c = int(cls) # integer class
  248. label = None if hide_labels else (names[c] if hide_conf else f"{names[c]} {conf:.2f}")
  249. annotator.box_label(xyxy, label, color=colors(c, True))
  250. if save_crop:
  251. save_one_box(xyxy, imc, file=save_dir / "crops" / names[c] / f"{p.stem}.jpg", BGR=True)
  252. # Stream results
  253. im0 = annotator.result()
  254. if view_img:
  255. if platform.system() == "Linux" and p not in windows:
  256. windows.append(p)
  257. cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # allow window resize (Linux)
  258. cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
  259. cv2.imshow(str(p), im0)
  260. cv2.waitKey(1) # 1 millisecond
  261. # Save results (image with detections)
  262. if save_img:
  263. if dataset.mode == "image":
  264. cv2.imwrite(save_path, im0)
  265. else: # 'video' or 'stream'
  266. if vid_path[i] != save_path: # new video
  267. vid_path[i] = save_path
  268. if isinstance(vid_writer[i], cv2.VideoWriter):
  269. vid_writer[i].release() # release previous video writer
  270. if vid_cap: # video
  271. fps = vid_cap.get(cv2.CAP_PROP_FPS)
  272. w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  273. h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  274. else: # stream
  275. fps, w, h = 30, im0.shape[1], im0.shape[0]
  276. save_path = str(Path(save_path).with_suffix(".mp4")) # force *.mp4 suffix on results videos
  277. vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))
  278. vid_writer[i].write(im0)
  279. # Print time (inference-only)
  280. LOGGER.info(f"{s}{'' if len(det) else '(no detections), '}{dt[1].dt * 1e3:.1f}ms")
  281. # Print results
  282. t = tuple(x.t / seen * 1e3 for x in dt) # speeds per image
  283. LOGGER.info(f"Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}" % t)
  284. if save_txt or save_img:
  285. s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ""
  286. LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
  287. if update:
  288. strip_optimizer(weights[0]) # update model (to fix SourceChangeWarning)
  289. def parse_opt():
  290. """
  291. Parse command-line arguments for YOLOv5 detection, allowing custom inference options and model configurations.
  292. Args:
  293. --weights (str | list[str], optional): Model path or Triton URL. Defaults to ROOT / 'yolov5s.pt'.
  294. --source (str, optional): File/dir/URL/glob/screen/0(webcam). Defaults to ROOT / 'data/images'.
  295. --data (str, optional): Dataset YAML path. Provides dataset configuration information.
  296. --imgsz (list[int], optional): Inference size (height, width). Defaults to [640].
  297. --conf-thres (float, optional): Confidence threshold. Defaults to 0.25.
  298. --iou-thres (float, optional): NMS IoU threshold. Defaults to 0.45.
  299. --max-det (int, optional): Maximum number of detections per image. Defaults to 1000.
  300. --device (str, optional): CUDA device, i.e., '0' or '0,1,2,3' or 'cpu'. Defaults to "".
  301. --view-img (bool, optional): Flag to display results. Defaults to False.
  302. --save-txt (bool, optional): Flag to save results to *.txt files. Defaults to False.
  303. --save-csv (bool, optional): Flag to save results in CSV format. Defaults to False.
  304. --save-conf (bool, optional): Flag to save confidences in labels saved via --save-txt. Defaults to False.
  305. --save-crop (bool, optional): Flag to save cropped prediction boxes. Defaults to False.
  306. --nosave (bool, optional): Flag to prevent saving images/videos. Defaults to False.
  307. --classes (list[int], optional): List of classes to filter results by, e.g., '--classes 0 2 3'. Defaults to None.
  308. --agnostic-nms (bool, optional): Flag for class-agnostic NMS. Defaults to False.
  309. --augment (bool, optional): Flag for augmented inference. Defaults to False.
  310. --visualize (bool, optional): Flag for visualizing features. Defaults to False.
  311. --update (bool, optional): Flag to update all models in the model directory. Defaults to False.
  312. --project (str, optional): Directory to save results. Defaults to ROOT / 'runs/detect'.
  313. --name (str, optional): Sub-directory name for saving results within --project. Defaults to 'exp'.
  314. --exist-ok (bool, optional): Flag to allow overwriting if the project/name already exists. Defaults to False.
  315. --line-thickness (int, optional): Thickness (in pixels) of bounding boxes. Defaults to 3.
  316. --hide-labels (bool, optional): Flag to hide labels in the output. Defaults to False.
  317. --hide-conf (bool, optional): Flag to hide confidences in the output. Defaults to False.
  318. --half (bool, optional): Flag to use FP16 half-precision inference. Defaults to False.
  319. --dnn (bool, optional): Flag to use OpenCV DNN for ONNX inference. Defaults to False.
  320. --vid-stride (int, optional): Video frame-rate stride, determining the number of frames to skip in between
  321. consecutive frames. Defaults to 1.
  322. Returns:
  323. argparse.Namespace: Parsed command-line arguments as an argparse.Namespace object.
  324. Example:
  325. ```python
  326. from ultralytics import YOLOv5
  327. args = YOLOv5.parse_opt()
  328. ```
  329. """
  330. parser = argparse.ArgumentParser()
  331. parser.add_argument("--weights", nargs="+", type=str, default=ROOT / "yolov5s.pt", help="model path or triton URL")
  332. parser.add_argument("--source", type=str, default=ROOT / "data/images", help="file/dir/URL/glob/screen/0(webcam)")
  333. parser.add_argument("--data", type=str, default=ROOT / "data/coco128.yaml", help="(optional) dataset.yaml path")
  334. parser.add_argument("--imgsz", "--img", "--img-size", nargs="+", type=int, default=[640], help="inference size h,w")
  335. parser.add_argument("--conf-thres", type=float, default=0.25, help="confidence threshold")
  336. parser.add_argument("--iou-thres", type=float, default=0.45, help="NMS IoU threshold")
  337. parser.add_argument("--max-det", type=int, default=1000, help="maximum detections per image")
  338. parser.add_argument("--device", default="", help="cuda device, i.e. 0 or 0,1,2,3 or cpu")
  339. parser.add_argument("--view-img", action="store_true", help="show results")
  340. parser.add_argument("--save-txt", action="store_true", help="save results to *.txt")
  341. parser.add_argument(
  342. "--save-format",
  343. type=int,
  344. default=0,
  345. help="whether to save boxes coordinates in YOLO format or Pascal-VOC format when save-txt is True, 0 for YOLO and 1 for Pascal-VOC",
  346. )
  347. parser.add_argument("--save-csv", action="store_true", help="save results in CSV format")
  348. parser.add_argument("--save-conf", action="store_true", help="save confidences in --save-txt labels")
  349. parser.add_argument("--save-crop", action="store_true", help="save cropped prediction boxes")
  350. parser.add_argument("--nosave", action="store_true", help="do not save images/videos")
  351. parser.add_argument("--classes", nargs="+", type=int, help="filter by class: --classes 0, or --classes 0 2 3")
  352. parser.add_argument("--agnostic-nms", action="store_true", help="class-agnostic NMS")
  353. parser.add_argument("--augment", action="store_true", help="augmented inference")
  354. parser.add_argument("--visualize", action="store_true", help="visualize features")
  355. parser.add_argument("--update", action="store_true", help="update all models")
  356. parser.add_argument("--project", default=ROOT / "runs/detect", help="save results to project/name")
  357. parser.add_argument("--name", default="exp", help="save results to project/name")
  358. parser.add_argument("--exist-ok", action="store_true", help="existing project/name ok, do not increment")
  359. parser.add_argument("--line-thickness", default=3, type=int, help="bounding box thickness (pixels)")
  360. parser.add_argument("--hide-labels", default=False, action="store_true", help="hide labels")
  361. parser.add_argument("--hide-conf", default=False, action="store_true", help="hide confidences")
  362. parser.add_argument("--half", action="store_true", help="use FP16 half-precision inference")
  363. parser.add_argument("--dnn", action="store_true", help="use OpenCV DNN for ONNX inference")
  364. parser.add_argument("--vid-stride", type=int, default=1, help="video frame-rate stride")
  365. opt = parser.parse_args()
  366. opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
  367. print_args(vars(opt))
  368. return opt
  369. def main(opt):
  370. """
  371. Executes YOLOv5 model inference based on provided command-line arguments, validating dependencies before running.
  372. Args:
  373. opt (argparse.Namespace): Command-line arguments for YOLOv5 detection. See function `parse_opt` for details.
  374. Returns:
  375. None
  376. Note:
  377. This function performs essential pre-execution checks and initiates the YOLOv5 detection process based on user-specified
  378. options. Refer to the usage guide and examples for more information about different sources and formats at:
  379. https://github.com/ultralytics/ultralytics
  380. Example usage:
  381. ```python
  382. if __name__ == "__main__":
  383. opt = parse_opt()
  384. main(opt)
  385. ```
  386. """
  387. check_requirements(ROOT / "requirements.txt", exclude=("tensorboard", "thop"))
  388. run(**vars(opt))
  389. if __name__ == "__main__":
  390. opt = parse_opt()
  391. main(opt)
Discard
Tip!

Press p or to see the previous file or, n or to see the next file