dgenerate-ultralytics-headless 8.3.134__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dgenerate_ultralytics_headless-8.3.134.dist-info/METADATA +400 -0
- dgenerate_ultralytics_headless-8.3.134.dist-info/RECORD +272 -0
- dgenerate_ultralytics_headless-8.3.134.dist-info/WHEEL +5 -0
- dgenerate_ultralytics_headless-8.3.134.dist-info/entry_points.txt +3 -0
- dgenerate_ultralytics_headless-8.3.134.dist-info/licenses/LICENSE +661 -0
- dgenerate_ultralytics_headless-8.3.134.dist-info/top_level.txt +1 -0
- tests/__init__.py +22 -0
- tests/conftest.py +83 -0
- tests/test_cli.py +138 -0
- tests/test_cuda.py +215 -0
- tests/test_engine.py +131 -0
- tests/test_exports.py +236 -0
- tests/test_integrations.py +154 -0
- tests/test_python.py +694 -0
- tests/test_solutions.py +187 -0
- ultralytics/__init__.py +30 -0
- ultralytics/assets/bus.jpg +0 -0
- ultralytics/assets/zidane.jpg +0 -0
- ultralytics/cfg/__init__.py +1023 -0
- ultralytics/cfg/datasets/Argoverse.yaml +77 -0
- ultralytics/cfg/datasets/DOTAv1.5.yaml +37 -0
- ultralytics/cfg/datasets/DOTAv1.yaml +36 -0
- ultralytics/cfg/datasets/GlobalWheat2020.yaml +68 -0
- ultralytics/cfg/datasets/HomeObjects-3K.yaml +33 -0
- ultralytics/cfg/datasets/ImageNet.yaml +2025 -0
- ultralytics/cfg/datasets/Objects365.yaml +443 -0
- ultralytics/cfg/datasets/SKU-110K.yaml +58 -0
- ultralytics/cfg/datasets/VOC.yaml +106 -0
- ultralytics/cfg/datasets/VisDrone.yaml +77 -0
- ultralytics/cfg/datasets/african-wildlife.yaml +25 -0
- ultralytics/cfg/datasets/brain-tumor.yaml +23 -0
- ultralytics/cfg/datasets/carparts-seg.yaml +44 -0
- ultralytics/cfg/datasets/coco-pose.yaml +42 -0
- ultralytics/cfg/datasets/coco.yaml +118 -0
- ultralytics/cfg/datasets/coco128-seg.yaml +101 -0
- ultralytics/cfg/datasets/coco128.yaml +101 -0
- ultralytics/cfg/datasets/coco8-multispectral.yaml +104 -0
- ultralytics/cfg/datasets/coco8-pose.yaml +26 -0
- ultralytics/cfg/datasets/coco8-seg.yaml +101 -0
- ultralytics/cfg/datasets/coco8.yaml +101 -0
- ultralytics/cfg/datasets/crack-seg.yaml +22 -0
- ultralytics/cfg/datasets/dog-pose.yaml +24 -0
- ultralytics/cfg/datasets/dota8-multispectral.yaml +38 -0
- ultralytics/cfg/datasets/dota8.yaml +35 -0
- ultralytics/cfg/datasets/hand-keypoints.yaml +26 -0
- ultralytics/cfg/datasets/lvis.yaml +1240 -0
- ultralytics/cfg/datasets/medical-pills.yaml +22 -0
- ultralytics/cfg/datasets/open-images-v7.yaml +666 -0
- ultralytics/cfg/datasets/package-seg.yaml +22 -0
- ultralytics/cfg/datasets/signature.yaml +21 -0
- ultralytics/cfg/datasets/tiger-pose.yaml +25 -0
- ultralytics/cfg/datasets/xView.yaml +155 -0
- ultralytics/cfg/default.yaml +127 -0
- ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml +17 -0
- ultralytics/cfg/models/11/yolo11-cls.yaml +33 -0
- ultralytics/cfg/models/11/yolo11-obb.yaml +50 -0
- ultralytics/cfg/models/11/yolo11-pose.yaml +51 -0
- ultralytics/cfg/models/11/yolo11-seg.yaml +50 -0
- ultralytics/cfg/models/11/yolo11.yaml +50 -0
- ultralytics/cfg/models/11/yoloe-11-seg.yaml +48 -0
- ultralytics/cfg/models/11/yoloe-11.yaml +48 -0
- ultralytics/cfg/models/12/yolo12-cls.yaml +32 -0
- ultralytics/cfg/models/12/yolo12-obb.yaml +48 -0
- ultralytics/cfg/models/12/yolo12-pose.yaml +49 -0
- ultralytics/cfg/models/12/yolo12-seg.yaml +48 -0
- ultralytics/cfg/models/12/yolo12.yaml +48 -0
- ultralytics/cfg/models/rt-detr/rtdetr-l.yaml +53 -0
- ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml +45 -0
- ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml +45 -0
- ultralytics/cfg/models/rt-detr/rtdetr-x.yaml +57 -0
- ultralytics/cfg/models/v10/yolov10b.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10l.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10m.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10n.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10s.yaml +45 -0
- ultralytics/cfg/models/v10/yolov10x.yaml +45 -0
- ultralytics/cfg/models/v3/yolov3-spp.yaml +49 -0
- ultralytics/cfg/models/v3/yolov3-tiny.yaml +40 -0
- ultralytics/cfg/models/v3/yolov3.yaml +49 -0
- ultralytics/cfg/models/v5/yolov5-p6.yaml +62 -0
- ultralytics/cfg/models/v5/yolov5.yaml +51 -0
- ultralytics/cfg/models/v6/yolov6.yaml +56 -0
- ultralytics/cfg/models/v8/yoloe-v8-seg.yaml +45 -0
- ultralytics/cfg/models/v8/yoloe-v8.yaml +45 -0
- ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +28 -0
- ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +28 -0
- ultralytics/cfg/models/v8/yolov8-cls.yaml +32 -0
- ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +58 -0
- ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +60 -0
- ultralytics/cfg/models/v8/yolov8-ghost.yaml +50 -0
- ultralytics/cfg/models/v8/yolov8-obb.yaml +49 -0
- ultralytics/cfg/models/v8/yolov8-p2.yaml +57 -0
- ultralytics/cfg/models/v8/yolov8-p6.yaml +59 -0
- ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +60 -0
- ultralytics/cfg/models/v8/yolov8-pose.yaml +50 -0
- ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +49 -0
- ultralytics/cfg/models/v8/yolov8-seg-p6.yaml +59 -0
- ultralytics/cfg/models/v8/yolov8-seg.yaml +49 -0
- ultralytics/cfg/models/v8/yolov8-world.yaml +51 -0
- ultralytics/cfg/models/v8/yolov8-worldv2.yaml +49 -0
- ultralytics/cfg/models/v8/yolov8.yaml +49 -0
- ultralytics/cfg/models/v9/yolov9c-seg.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9c.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9e-seg.yaml +64 -0
- ultralytics/cfg/models/v9/yolov9e.yaml +64 -0
- ultralytics/cfg/models/v9/yolov9m.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9s.yaml +41 -0
- ultralytics/cfg/models/v9/yolov9t.yaml +41 -0
- ultralytics/cfg/trackers/botsort.yaml +22 -0
- ultralytics/cfg/trackers/bytetrack.yaml +14 -0
- ultralytics/data/__init__.py +26 -0
- ultralytics/data/annotator.py +66 -0
- ultralytics/data/augment.py +2945 -0
- ultralytics/data/base.py +438 -0
- ultralytics/data/build.py +258 -0
- ultralytics/data/converter.py +754 -0
- ultralytics/data/dataset.py +834 -0
- ultralytics/data/loaders.py +676 -0
- ultralytics/data/scripts/download_weights.sh +18 -0
- ultralytics/data/scripts/get_coco.sh +61 -0
- ultralytics/data/scripts/get_coco128.sh +18 -0
- ultralytics/data/scripts/get_imagenet.sh +52 -0
- ultralytics/data/split.py +125 -0
- ultralytics/data/split_dota.py +325 -0
- ultralytics/data/utils.py +777 -0
- ultralytics/engine/__init__.py +1 -0
- ultralytics/engine/exporter.py +1519 -0
- ultralytics/engine/model.py +1156 -0
- ultralytics/engine/predictor.py +502 -0
- ultralytics/engine/results.py +1840 -0
- ultralytics/engine/trainer.py +853 -0
- ultralytics/engine/tuner.py +243 -0
- ultralytics/engine/validator.py +377 -0
- ultralytics/hub/__init__.py +168 -0
- ultralytics/hub/auth.py +137 -0
- ultralytics/hub/google/__init__.py +176 -0
- ultralytics/hub/session.py +446 -0
- ultralytics/hub/utils.py +248 -0
- ultralytics/models/__init__.py +9 -0
- ultralytics/models/fastsam/__init__.py +7 -0
- ultralytics/models/fastsam/model.py +61 -0
- ultralytics/models/fastsam/predict.py +181 -0
- ultralytics/models/fastsam/utils.py +24 -0
- ultralytics/models/fastsam/val.py +40 -0
- ultralytics/models/nas/__init__.py +7 -0
- ultralytics/models/nas/model.py +102 -0
- ultralytics/models/nas/predict.py +58 -0
- ultralytics/models/nas/val.py +39 -0
- ultralytics/models/rtdetr/__init__.py +7 -0
- ultralytics/models/rtdetr/model.py +63 -0
- ultralytics/models/rtdetr/predict.py +84 -0
- ultralytics/models/rtdetr/train.py +85 -0
- ultralytics/models/rtdetr/val.py +191 -0
- ultralytics/models/sam/__init__.py +6 -0
- ultralytics/models/sam/amg.py +260 -0
- ultralytics/models/sam/build.py +358 -0
- ultralytics/models/sam/model.py +170 -0
- ultralytics/models/sam/modules/__init__.py +1 -0
- ultralytics/models/sam/modules/blocks.py +1129 -0
- ultralytics/models/sam/modules/decoders.py +515 -0
- ultralytics/models/sam/modules/encoders.py +854 -0
- ultralytics/models/sam/modules/memory_attention.py +299 -0
- ultralytics/models/sam/modules/sam.py +1006 -0
- ultralytics/models/sam/modules/tiny_encoder.py +1002 -0
- ultralytics/models/sam/modules/transformer.py +351 -0
- ultralytics/models/sam/modules/utils.py +394 -0
- ultralytics/models/sam/predict.py +1605 -0
- ultralytics/models/utils/__init__.py +1 -0
- ultralytics/models/utils/loss.py +455 -0
- ultralytics/models/utils/ops.py +268 -0
- ultralytics/models/yolo/__init__.py +7 -0
- ultralytics/models/yolo/classify/__init__.py +7 -0
- ultralytics/models/yolo/classify/predict.py +88 -0
- ultralytics/models/yolo/classify/train.py +233 -0
- ultralytics/models/yolo/classify/val.py +215 -0
- ultralytics/models/yolo/detect/__init__.py +7 -0
- ultralytics/models/yolo/detect/predict.py +124 -0
- ultralytics/models/yolo/detect/train.py +217 -0
- ultralytics/models/yolo/detect/val.py +451 -0
- ultralytics/models/yolo/model.py +354 -0
- ultralytics/models/yolo/obb/__init__.py +7 -0
- ultralytics/models/yolo/obb/predict.py +66 -0
- ultralytics/models/yolo/obb/train.py +81 -0
- ultralytics/models/yolo/obb/val.py +283 -0
- ultralytics/models/yolo/pose/__init__.py +7 -0
- ultralytics/models/yolo/pose/predict.py +79 -0
- ultralytics/models/yolo/pose/train.py +154 -0
- ultralytics/models/yolo/pose/val.py +394 -0
- ultralytics/models/yolo/segment/__init__.py +7 -0
- ultralytics/models/yolo/segment/predict.py +113 -0
- ultralytics/models/yolo/segment/train.py +123 -0
- ultralytics/models/yolo/segment/val.py +428 -0
- ultralytics/models/yolo/world/__init__.py +5 -0
- ultralytics/models/yolo/world/train.py +119 -0
- ultralytics/models/yolo/world/train_world.py +176 -0
- ultralytics/models/yolo/yoloe/__init__.py +22 -0
- ultralytics/models/yolo/yoloe/predict.py +169 -0
- ultralytics/models/yolo/yoloe/train.py +298 -0
- ultralytics/models/yolo/yoloe/train_seg.py +124 -0
- ultralytics/models/yolo/yoloe/val.py +191 -0
- ultralytics/nn/__init__.py +29 -0
- ultralytics/nn/autobackend.py +842 -0
- ultralytics/nn/modules/__init__.py +182 -0
- ultralytics/nn/modules/activation.py +53 -0
- ultralytics/nn/modules/block.py +1966 -0
- ultralytics/nn/modules/conv.py +712 -0
- ultralytics/nn/modules/head.py +880 -0
- ultralytics/nn/modules/transformer.py +713 -0
- ultralytics/nn/modules/utils.py +164 -0
- ultralytics/nn/tasks.py +1627 -0
- ultralytics/nn/text_model.py +351 -0
- ultralytics/solutions/__init__.py +41 -0
- ultralytics/solutions/ai_gym.py +116 -0
- ultralytics/solutions/analytics.py +252 -0
- ultralytics/solutions/config.py +106 -0
- ultralytics/solutions/distance_calculation.py +124 -0
- ultralytics/solutions/heatmap.py +127 -0
- ultralytics/solutions/instance_segmentation.py +84 -0
- ultralytics/solutions/object_blurrer.py +90 -0
- ultralytics/solutions/object_counter.py +195 -0
- ultralytics/solutions/object_cropper.py +84 -0
- ultralytics/solutions/parking_management.py +273 -0
- ultralytics/solutions/queue_management.py +93 -0
- ultralytics/solutions/region_counter.py +120 -0
- ultralytics/solutions/security_alarm.py +154 -0
- ultralytics/solutions/similarity_search.py +172 -0
- ultralytics/solutions/solutions.py +724 -0
- ultralytics/solutions/speed_estimation.py +110 -0
- ultralytics/solutions/streamlit_inference.py +196 -0
- ultralytics/solutions/templates/similarity-search.html +160 -0
- ultralytics/solutions/trackzone.py +88 -0
- ultralytics/solutions/vision_eye.py +68 -0
- ultralytics/trackers/__init__.py +7 -0
- ultralytics/trackers/basetrack.py +124 -0
- ultralytics/trackers/bot_sort.py +260 -0
- ultralytics/trackers/byte_tracker.py +480 -0
- ultralytics/trackers/track.py +125 -0
- ultralytics/trackers/utils/__init__.py +1 -0
- ultralytics/trackers/utils/gmc.py +376 -0
- ultralytics/trackers/utils/kalman_filter.py +493 -0
- ultralytics/trackers/utils/matching.py +157 -0
- ultralytics/utils/__init__.py +1435 -0
- ultralytics/utils/autobatch.py +106 -0
- ultralytics/utils/autodevice.py +174 -0
- ultralytics/utils/benchmarks.py +695 -0
- ultralytics/utils/callbacks/__init__.py +5 -0
- ultralytics/utils/callbacks/base.py +234 -0
- ultralytics/utils/callbacks/clearml.py +153 -0
- ultralytics/utils/callbacks/comet.py +552 -0
- ultralytics/utils/callbacks/dvc.py +205 -0
- ultralytics/utils/callbacks/hub.py +108 -0
- ultralytics/utils/callbacks/mlflow.py +138 -0
- ultralytics/utils/callbacks/neptune.py +140 -0
- ultralytics/utils/callbacks/raytune.py +43 -0
- ultralytics/utils/callbacks/tensorboard.py +132 -0
- ultralytics/utils/callbacks/wb.py +185 -0
- ultralytics/utils/checks.py +897 -0
- ultralytics/utils/dist.py +119 -0
- ultralytics/utils/downloads.py +499 -0
- ultralytics/utils/errors.py +43 -0
- ultralytics/utils/export.py +219 -0
- ultralytics/utils/files.py +221 -0
- ultralytics/utils/instance.py +499 -0
- ultralytics/utils/loss.py +813 -0
- ultralytics/utils/metrics.py +1356 -0
- ultralytics/utils/ops.py +885 -0
- ultralytics/utils/patches.py +143 -0
- ultralytics/utils/plotting.py +1011 -0
- ultralytics/utils/tal.py +416 -0
- ultralytics/utils/torch_utils.py +990 -0
- ultralytics/utils/triton.py +116 -0
- ultralytics/utils/tuner.py +159 -0
@@ -0,0 +1,1023 @@
|
|
1
|
+
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
2
|
+
|
3
|
+
import shutil
|
4
|
+
import subprocess
|
5
|
+
import sys
|
6
|
+
from pathlib import Path
|
7
|
+
from types import SimpleNamespace
|
8
|
+
from typing import Any, Dict, List, Union
|
9
|
+
|
10
|
+
import cv2
|
11
|
+
|
12
|
+
from ultralytics import __version__
|
13
|
+
from ultralytics.utils import (
|
14
|
+
ASSETS,
|
15
|
+
DEFAULT_CFG,
|
16
|
+
DEFAULT_CFG_DICT,
|
17
|
+
DEFAULT_CFG_PATH,
|
18
|
+
IS_VSCODE,
|
19
|
+
LOGGER,
|
20
|
+
RANK,
|
21
|
+
ROOT,
|
22
|
+
RUNS_DIR,
|
23
|
+
SETTINGS,
|
24
|
+
SETTINGS_FILE,
|
25
|
+
TESTS_RUNNING,
|
26
|
+
YAML,
|
27
|
+
IterableSimpleNamespace,
|
28
|
+
checks,
|
29
|
+
colorstr,
|
30
|
+
deprecation_warn,
|
31
|
+
vscode_msg,
|
32
|
+
)
|
33
|
+
|
34
|
+
# Define valid solutions
|
35
|
+
SOLUTION_MAP = {
|
36
|
+
"count": "ObjectCounter",
|
37
|
+
"crop": "ObjectCropper",
|
38
|
+
"blur": "ObjectBlurrer",
|
39
|
+
"workout": "AIGym",
|
40
|
+
"heatmap": "Heatmap",
|
41
|
+
"isegment": "InstanceSegmentation",
|
42
|
+
"visioneye": "VisionEye",
|
43
|
+
"speed": "SpeedEstimator",
|
44
|
+
"queue": "QueueManager",
|
45
|
+
"analytics": "Analytics",
|
46
|
+
"inference": "Inference",
|
47
|
+
"trackzone": "TrackZone",
|
48
|
+
"help": None,
|
49
|
+
}
|
50
|
+
|
51
|
+
# Define valid tasks and modes
|
52
|
+
MODES = frozenset({"train", "val", "predict", "export", "track", "benchmark"})
|
53
|
+
TASKS = frozenset({"detect", "segment", "classify", "pose", "obb"})
|
54
|
+
TASK2DATA = {
|
55
|
+
"detect": "coco8.yaml",
|
56
|
+
"segment": "coco8-seg.yaml",
|
57
|
+
"classify": "imagenet10",
|
58
|
+
"pose": "coco8-pose.yaml",
|
59
|
+
"obb": "dota8.yaml",
|
60
|
+
}
|
61
|
+
TASK2MODEL = {
|
62
|
+
"detect": "yolo11n.pt",
|
63
|
+
"segment": "yolo11n-seg.pt",
|
64
|
+
"classify": "yolo11n-cls.pt",
|
65
|
+
"pose": "yolo11n-pose.pt",
|
66
|
+
"obb": "yolo11n-obb.pt",
|
67
|
+
}
|
68
|
+
TASK2METRIC = {
|
69
|
+
"detect": "metrics/mAP50-95(B)",
|
70
|
+
"segment": "metrics/mAP50-95(M)",
|
71
|
+
"classify": "metrics/accuracy_top1",
|
72
|
+
"pose": "metrics/mAP50-95(P)",
|
73
|
+
"obb": "metrics/mAP50-95(B)",
|
74
|
+
}
|
75
|
+
MODELS = frozenset({TASK2MODEL[task] for task in TASKS})
|
76
|
+
|
77
|
+
ARGV = sys.argv or ["", ""] # sometimes sys.argv = []
|
78
|
+
SOLUTIONS_HELP_MSG = f"""
|
79
|
+
Arguments received: {str(["yolo"] + ARGV[1:])}. Ultralytics 'yolo solutions' usage overview:
|
80
|
+
|
81
|
+
yolo solutions SOLUTION ARGS
|
82
|
+
|
83
|
+
Where SOLUTION (optional) is one of {list(SOLUTION_MAP.keys())[:-1]}
|
84
|
+
ARGS (optional) are any number of custom 'arg=value' pairs like 'show_in=True' that override defaults
|
85
|
+
at https://docs.ultralytics.com/usage/cfg
|
86
|
+
|
87
|
+
1. Call object counting solution
|
88
|
+
yolo solutions count source="path/to/video.mp4" region="[(20, 400), (1080, 400), (1080, 360), (20, 360)]"
|
89
|
+
|
90
|
+
2. Call heatmaps solution
|
91
|
+
yolo solutions heatmap colormap=cv2.COLORMAP_PARULA model=yolo11n.pt
|
92
|
+
|
93
|
+
3. Call queue management solution
|
94
|
+
yolo solutions queue region="[(20, 400), (1080, 400), (1080, 360), (20, 360)]" model=yolo11n.pt
|
95
|
+
|
96
|
+
4. Call workouts monitoring solution for push-ups
|
97
|
+
yolo solutions workout model=yolo11n-pose.pt kpts=[6, 8, 10]
|
98
|
+
|
99
|
+
5. Generate analytical graphs
|
100
|
+
yolo solutions analytics analytics_type="pie"
|
101
|
+
|
102
|
+
6. Track objects within specific zones
|
103
|
+
yolo solutions trackzone source="path/to/video.mp4" region="[(150, 150), (1130, 150), (1130, 570), (150, 570)]"
|
104
|
+
|
105
|
+
7. Streamlit real-time webcam inference GUI
|
106
|
+
yolo streamlit-predict
|
107
|
+
"""
|
108
|
+
CLI_HELP_MSG = f"""
|
109
|
+
Arguments received: {str(["yolo"] + ARGV[1:])}. Ultralytics 'yolo' commands use the following syntax:
|
110
|
+
|
111
|
+
yolo TASK MODE ARGS
|
112
|
+
|
113
|
+
Where TASK (optional) is one of {TASKS}
|
114
|
+
MODE (required) is one of {MODES}
|
115
|
+
ARGS (optional) are any number of custom 'arg=value' pairs like 'imgsz=320' that override defaults.
|
116
|
+
See all ARGS at https://docs.ultralytics.com/usage/cfg or with 'yolo cfg'
|
117
|
+
|
118
|
+
1. Train a detection model for 10 epochs with an initial learning_rate of 0.01
|
119
|
+
yolo train data=coco8.yaml model=yolo11n.pt epochs=10 lr0=0.01
|
120
|
+
|
121
|
+
2. Predict a YouTube video using a pretrained segmentation model at image size 320:
|
122
|
+
yolo predict model=yolo11n-seg.pt source='https://youtu.be/LNwODJXcvt4' imgsz=320
|
123
|
+
|
124
|
+
3. Val a pretrained detection model at batch-size 1 and image size 640:
|
125
|
+
yolo val model=yolo11n.pt data=coco8.yaml batch=1 imgsz=640
|
126
|
+
|
127
|
+
4. Export a YOLO11n classification model to ONNX format at image size 224 by 128 (no TASK required)
|
128
|
+
yolo export model=yolo11n-cls.pt format=onnx imgsz=224,128
|
129
|
+
|
130
|
+
5. Ultralytics solutions usage
|
131
|
+
yolo solutions count or in {list(SOLUTION_MAP.keys())[1:-1]} source="path/to/video.mp4"
|
132
|
+
|
133
|
+
6. Run special commands:
|
134
|
+
yolo help
|
135
|
+
yolo checks
|
136
|
+
yolo version
|
137
|
+
yolo settings
|
138
|
+
yolo copy-cfg
|
139
|
+
yolo cfg
|
140
|
+
yolo solutions help
|
141
|
+
|
142
|
+
Docs: https://docs.ultralytics.com
|
143
|
+
Solutions: https://docs.ultralytics.com/solutions/
|
144
|
+
Community: https://community.ultralytics.com
|
145
|
+
GitHub: https://github.com/ultralytics/ultralytics
|
146
|
+
"""
|
147
|
+
|
148
|
+
# Define keys for arg type checks
|
149
|
+
CFG_FLOAT_KEYS = frozenset(
|
150
|
+
{ # integer or float arguments, i.e. x=2 and x=2.0
|
151
|
+
"warmup_epochs",
|
152
|
+
"box",
|
153
|
+
"cls",
|
154
|
+
"dfl",
|
155
|
+
"degrees",
|
156
|
+
"shear",
|
157
|
+
"time",
|
158
|
+
"workspace",
|
159
|
+
"batch",
|
160
|
+
}
|
161
|
+
)
|
162
|
+
CFG_FRACTION_KEYS = frozenset(
|
163
|
+
{ # fractional float arguments with 0.0<=values<=1.0
|
164
|
+
"dropout",
|
165
|
+
"lr0",
|
166
|
+
"lrf",
|
167
|
+
"momentum",
|
168
|
+
"weight_decay",
|
169
|
+
"warmup_momentum",
|
170
|
+
"warmup_bias_lr",
|
171
|
+
"hsv_h",
|
172
|
+
"hsv_s",
|
173
|
+
"hsv_v",
|
174
|
+
"translate",
|
175
|
+
"scale",
|
176
|
+
"perspective",
|
177
|
+
"flipud",
|
178
|
+
"fliplr",
|
179
|
+
"bgr",
|
180
|
+
"mosaic",
|
181
|
+
"mixup",
|
182
|
+
"cutmix",
|
183
|
+
"copy_paste",
|
184
|
+
"conf",
|
185
|
+
"iou",
|
186
|
+
"fraction",
|
187
|
+
}
|
188
|
+
)
|
189
|
+
CFG_INT_KEYS = frozenset(
|
190
|
+
{ # integer-only arguments
|
191
|
+
"epochs",
|
192
|
+
"patience",
|
193
|
+
"workers",
|
194
|
+
"seed",
|
195
|
+
"close_mosaic",
|
196
|
+
"mask_ratio",
|
197
|
+
"max_det",
|
198
|
+
"vid_stride",
|
199
|
+
"line_width",
|
200
|
+
"nbs",
|
201
|
+
"save_period",
|
202
|
+
}
|
203
|
+
)
|
204
|
+
CFG_BOOL_KEYS = frozenset(
|
205
|
+
{ # boolean-only arguments
|
206
|
+
"save",
|
207
|
+
"exist_ok",
|
208
|
+
"verbose",
|
209
|
+
"deterministic",
|
210
|
+
"single_cls",
|
211
|
+
"rect",
|
212
|
+
"cos_lr",
|
213
|
+
"overlap_mask",
|
214
|
+
"val",
|
215
|
+
"save_json",
|
216
|
+
"half",
|
217
|
+
"dnn",
|
218
|
+
"plots",
|
219
|
+
"show",
|
220
|
+
"save_txt",
|
221
|
+
"save_conf",
|
222
|
+
"save_crop",
|
223
|
+
"save_frames",
|
224
|
+
"show_labels",
|
225
|
+
"show_conf",
|
226
|
+
"visualize",
|
227
|
+
"augment",
|
228
|
+
"agnostic_nms",
|
229
|
+
"retina_masks",
|
230
|
+
"show_boxes",
|
231
|
+
"keras",
|
232
|
+
"optimize",
|
233
|
+
"int8",
|
234
|
+
"dynamic",
|
235
|
+
"simplify",
|
236
|
+
"nms",
|
237
|
+
"profile",
|
238
|
+
"multi_scale",
|
239
|
+
}
|
240
|
+
)
|
241
|
+
|
242
|
+
|
243
|
+
def cfg2dict(cfg: Union[str, Path, Dict, SimpleNamespace]) -> Dict:
|
244
|
+
"""
|
245
|
+
Converts a configuration object to a dictionary.
|
246
|
+
|
247
|
+
Args:
|
248
|
+
cfg (str | Path | Dict | SimpleNamespace): Configuration object to be converted. Can be a file path,
|
249
|
+
a string, a dictionary, or a SimpleNamespace object.
|
250
|
+
|
251
|
+
Returns:
|
252
|
+
(dict): Configuration object in dictionary format.
|
253
|
+
|
254
|
+
Examples:
|
255
|
+
Convert a YAML file path to a dictionary:
|
256
|
+
>>> config_dict = cfg2dict("config.yaml")
|
257
|
+
|
258
|
+
Convert a SimpleNamespace to a dictionary:
|
259
|
+
>>> from types import SimpleNamespace
|
260
|
+
>>> config_sn = SimpleNamespace(param1="value1", param2="value2")
|
261
|
+
>>> config_dict = cfg2dict(config_sn)
|
262
|
+
|
263
|
+
Pass through an already existing dictionary:
|
264
|
+
>>> config_dict = cfg2dict({"param1": "value1", "param2": "value2"})
|
265
|
+
|
266
|
+
Notes:
|
267
|
+
- If cfg is a path or string, it's loaded as YAML and converted to a dictionary.
|
268
|
+
- If cfg is a SimpleNamespace object, it's converted to a dictionary using vars().
|
269
|
+
- If cfg is already a dictionary, it's returned unchanged.
|
270
|
+
"""
|
271
|
+
if isinstance(cfg, (str, Path)):
|
272
|
+
cfg = YAML.load(cfg) # load dict
|
273
|
+
elif isinstance(cfg, SimpleNamespace):
|
274
|
+
cfg = vars(cfg) # convert to dict
|
275
|
+
return cfg
|
276
|
+
|
277
|
+
|
278
|
+
def get_cfg(cfg: Union[str, Path, Dict, SimpleNamespace] = DEFAULT_CFG_DICT, overrides: Dict = None) -> SimpleNamespace:
|
279
|
+
"""
|
280
|
+
Load and merge configuration data from a file or dictionary, with optional overrides.
|
281
|
+
|
282
|
+
Args:
|
283
|
+
cfg (str | Path | Dict | SimpleNamespace): Configuration data source. Can be a file path, dictionary, or
|
284
|
+
SimpleNamespace object.
|
285
|
+
overrides (Dict | None): Dictionary containing key-value pairs to override the base configuration.
|
286
|
+
|
287
|
+
Returns:
|
288
|
+
(SimpleNamespace): Namespace containing the merged configuration arguments.
|
289
|
+
|
290
|
+
Examples:
|
291
|
+
>>> from ultralytics.cfg import get_cfg
|
292
|
+
>>> config = get_cfg() # Load default configuration
|
293
|
+
>>> config_with_overrides = get_cfg("path/to/config.yaml", overrides={"epochs": 50, "batch_size": 16})
|
294
|
+
|
295
|
+
Notes:
|
296
|
+
- If both `cfg` and `overrides` are provided, the values in `overrides` will take precedence.
|
297
|
+
- Special handling ensures alignment and correctness of the configuration, such as converting numeric
|
298
|
+
`project` and `name` to strings and validating configuration keys and values.
|
299
|
+
- The function performs type and value checks on the configuration data.
|
300
|
+
"""
|
301
|
+
cfg = cfg2dict(cfg)
|
302
|
+
|
303
|
+
# Merge overrides
|
304
|
+
if overrides:
|
305
|
+
overrides = cfg2dict(overrides)
|
306
|
+
if "save_dir" not in cfg:
|
307
|
+
overrides.pop("save_dir", None) # special override keys to ignore
|
308
|
+
check_dict_alignment(cfg, overrides)
|
309
|
+
cfg = {**cfg, **overrides} # merge cfg and overrides dicts (prefer overrides)
|
310
|
+
|
311
|
+
# Special handling for numeric project/name
|
312
|
+
for k in "project", "name":
|
313
|
+
if k in cfg and isinstance(cfg[k], (int, float)):
|
314
|
+
cfg[k] = str(cfg[k])
|
315
|
+
if cfg.get("name") == "model": # assign model to 'name' arg
|
316
|
+
cfg["name"] = str(cfg.get("model", "")).split(".")[0]
|
317
|
+
LOGGER.warning(f"'name=model' automatically updated to 'name={cfg['name']}'.")
|
318
|
+
|
319
|
+
# Type and Value checks
|
320
|
+
check_cfg(cfg)
|
321
|
+
|
322
|
+
# Return instance
|
323
|
+
return IterableSimpleNamespace(**cfg)
|
324
|
+
|
325
|
+
|
326
|
+
def check_cfg(cfg: Dict, hard: bool = True) -> None:
|
327
|
+
"""
|
328
|
+
Checks configuration argument types and values for the Ultralytics library.
|
329
|
+
|
330
|
+
This function validates the types and values of configuration arguments, ensuring correctness and converting
|
331
|
+
them if necessary. It checks for specific key types defined in global variables such as `CFG_FLOAT_KEYS`,
|
332
|
+
`CFG_FRACTION_KEYS`, `CFG_INT_KEYS`, and `CFG_BOOL_KEYS`.
|
333
|
+
|
334
|
+
Args:
|
335
|
+
cfg (dict): Configuration dictionary to validate.
|
336
|
+
hard (bool): If True, raises exceptions for invalid types and values; if False, attempts to convert them.
|
337
|
+
|
338
|
+
Examples:
|
339
|
+
>>> config = {
|
340
|
+
... "epochs": 50, # valid integer
|
341
|
+
... "lr0": 0.01, # valid float
|
342
|
+
... "momentum": 1.2, # invalid float (out of 0.0-1.0 range)
|
343
|
+
... "save": "true", # invalid bool
|
344
|
+
... }
|
345
|
+
>>> check_cfg(config, hard=False)
|
346
|
+
>>> print(config)
|
347
|
+
{'epochs': 50, 'lr0': 0.01, 'momentum': 1.2, 'save': False} # corrected 'save' key
|
348
|
+
|
349
|
+
Notes:
|
350
|
+
- The function modifies the input dictionary in-place.
|
351
|
+
- None values are ignored as they may be from optional arguments.
|
352
|
+
- Fraction keys are checked to be within the range [0.0, 1.0].
|
353
|
+
"""
|
354
|
+
for k, v in cfg.items():
|
355
|
+
if v is not None: # None values may be from optional args
|
356
|
+
if k in CFG_FLOAT_KEYS and not isinstance(v, (int, float)):
|
357
|
+
if hard:
|
358
|
+
raise TypeError(
|
359
|
+
f"'{k}={v}' is of invalid type {type(v).__name__}. "
|
360
|
+
f"Valid '{k}' types are int (i.e. '{k}=0') or float (i.e. '{k}=0.5')"
|
361
|
+
)
|
362
|
+
cfg[k] = float(v)
|
363
|
+
elif k in CFG_FRACTION_KEYS:
|
364
|
+
if not isinstance(v, (int, float)):
|
365
|
+
if hard:
|
366
|
+
raise TypeError(
|
367
|
+
f"'{k}={v}' is of invalid type {type(v).__name__}. "
|
368
|
+
f"Valid '{k}' types are int (i.e. '{k}=0') or float (i.e. '{k}=0.5')"
|
369
|
+
)
|
370
|
+
cfg[k] = v = float(v)
|
371
|
+
if not (0.0 <= v <= 1.0):
|
372
|
+
raise ValueError(f"'{k}={v}' is an invalid value. Valid '{k}' values are between 0.0 and 1.0.")
|
373
|
+
elif k in CFG_INT_KEYS and not isinstance(v, int):
|
374
|
+
if hard:
|
375
|
+
raise TypeError(
|
376
|
+
f"'{k}={v}' is of invalid type {type(v).__name__}. '{k}' must be an int (i.e. '{k}=8')"
|
377
|
+
)
|
378
|
+
cfg[k] = int(v)
|
379
|
+
elif k in CFG_BOOL_KEYS and not isinstance(v, bool):
|
380
|
+
if hard:
|
381
|
+
raise TypeError(
|
382
|
+
f"'{k}={v}' is of invalid type {type(v).__name__}. "
|
383
|
+
f"'{k}' must be a bool (i.e. '{k}=True' or '{k}=False')"
|
384
|
+
)
|
385
|
+
cfg[k] = bool(v)
|
386
|
+
|
387
|
+
|
388
|
+
def get_save_dir(args: SimpleNamespace, name: str = None) -> Path:
|
389
|
+
"""
|
390
|
+
Returns the directory path for saving outputs, derived from arguments or default settings.
|
391
|
+
|
392
|
+
Args:
|
393
|
+
args (SimpleNamespace): Namespace object containing configurations such as 'project', 'name', 'task',
|
394
|
+
'mode', and 'save_dir'.
|
395
|
+
name (str | None): Optional name for the output directory. If not provided, it defaults to 'args.name'
|
396
|
+
or the 'args.mode'.
|
397
|
+
|
398
|
+
Returns:
|
399
|
+
(Path): Directory path where outputs should be saved.
|
400
|
+
|
401
|
+
Examples:
|
402
|
+
>>> from types import SimpleNamespace
|
403
|
+
>>> args = SimpleNamespace(project="my_project", task="detect", mode="train", exist_ok=True)
|
404
|
+
>>> save_dir = get_save_dir(args)
|
405
|
+
>>> print(save_dir)
|
406
|
+
my_project/detect/train
|
407
|
+
"""
|
408
|
+
if getattr(args, "save_dir", None):
|
409
|
+
save_dir = args.save_dir
|
410
|
+
else:
|
411
|
+
from ultralytics.utils.files import increment_path
|
412
|
+
|
413
|
+
project = args.project or (ROOT.parent / "tests/tmp/runs" if TESTS_RUNNING else RUNS_DIR) / args.task
|
414
|
+
name = name or args.name or f"{args.mode}"
|
415
|
+
save_dir = increment_path(Path(project) / name, exist_ok=args.exist_ok if RANK in {-1, 0} else True)
|
416
|
+
|
417
|
+
return Path(save_dir)
|
418
|
+
|
419
|
+
|
420
|
+
def _handle_deprecation(custom: Dict) -> Dict:
|
421
|
+
"""
|
422
|
+
Handles deprecated configuration keys by mapping them to current equivalents with deprecation warnings.
|
423
|
+
|
424
|
+
Args:
|
425
|
+
custom (dict): Configuration dictionary potentially containing deprecated keys.
|
426
|
+
|
427
|
+
Examples:
|
428
|
+
>>> custom_config = {"boxes": True, "hide_labels": "False", "line_thickness": 2}
|
429
|
+
>>> _handle_deprecation(custom_config)
|
430
|
+
>>> print(custom_config)
|
431
|
+
{'show_boxes': True, 'show_labels': True, 'line_width': 2}
|
432
|
+
|
433
|
+
Notes:
|
434
|
+
This function modifies the input dictionary in-place, replacing deprecated keys with their current
|
435
|
+
equivalents. It also handles value conversions where necessary, such as inverting boolean values for
|
436
|
+
'hide_labels' and 'hide_conf'.
|
437
|
+
"""
|
438
|
+
deprecated_mappings = {
|
439
|
+
"boxes": ("show_boxes", lambda v: v),
|
440
|
+
"hide_labels": ("show_labels", lambda v: not bool(v)),
|
441
|
+
"hide_conf": ("show_conf", lambda v: not bool(v)),
|
442
|
+
"line_thickness": ("line_width", lambda v: v),
|
443
|
+
}
|
444
|
+
removed_keys = {"label_smoothing", "save_hybrid", "crop_fraction"}
|
445
|
+
|
446
|
+
for old_key, (new_key, transform) in deprecated_mappings.items():
|
447
|
+
if old_key not in custom:
|
448
|
+
continue
|
449
|
+
deprecation_warn(old_key, new_key)
|
450
|
+
custom[new_key] = transform(custom.pop(old_key))
|
451
|
+
|
452
|
+
for key in removed_keys:
|
453
|
+
if key not in custom:
|
454
|
+
continue
|
455
|
+
deprecation_warn(key)
|
456
|
+
custom.pop(key)
|
457
|
+
|
458
|
+
return custom
|
459
|
+
|
460
|
+
|
461
|
+
def check_dict_alignment(base: Dict, custom: Dict, e: Exception = None) -> None:
|
462
|
+
"""
|
463
|
+
Checks alignment between custom and base configuration dictionaries, handling deprecated keys and providing error
|
464
|
+
messages for mismatched keys.
|
465
|
+
|
466
|
+
Args:
|
467
|
+
base (dict): The base configuration dictionary containing valid keys.
|
468
|
+
custom (dict): The custom configuration dictionary to be checked for alignment.
|
469
|
+
e (Exception | None): Optional error instance passed by the calling function.
|
470
|
+
|
471
|
+
Raises:
|
472
|
+
SystemExit: If mismatched keys are found between the custom and base dictionaries.
|
473
|
+
|
474
|
+
Examples:
|
475
|
+
>>> base_cfg = {"epochs": 50, "lr0": 0.01, "batch_size": 16}
|
476
|
+
>>> custom_cfg = {"epoch": 100, "lr": 0.02, "batch_size": 32}
|
477
|
+
>>> try:
|
478
|
+
... check_dict_alignment(base_cfg, custom_cfg)
|
479
|
+
... except SystemExit:
|
480
|
+
... print("Mismatched keys found")
|
481
|
+
|
482
|
+
Notes:
|
483
|
+
- Suggests corrections for mismatched keys based on similarity to valid keys.
|
484
|
+
- Automatically replaces deprecated keys in the custom configuration with updated equivalents.
|
485
|
+
- Prints detailed error messages for each mismatched key to help users correct their configurations.
|
486
|
+
"""
|
487
|
+
custom = _handle_deprecation(custom)
|
488
|
+
base_keys, custom_keys = (frozenset(x.keys()) for x in (base, custom))
|
489
|
+
if mismatched := [k for k in custom_keys if k not in base_keys]:
|
490
|
+
from difflib import get_close_matches
|
491
|
+
|
492
|
+
string = ""
|
493
|
+
for x in mismatched:
|
494
|
+
matches = get_close_matches(x, base_keys) # key list
|
495
|
+
matches = [f"{k}={base[k]}" if base.get(k) is not None else k for k in matches]
|
496
|
+
match_str = f"Similar arguments are i.e. {matches}." if matches else ""
|
497
|
+
string += f"'{colorstr('red', 'bold', x)}' is not a valid YOLO argument. {match_str}\n"
|
498
|
+
raise SyntaxError(string + CLI_HELP_MSG) from e
|
499
|
+
|
500
|
+
|
501
|
+
def merge_equals_args(args: List[str]) -> List[str]:
|
502
|
+
"""
|
503
|
+
Merges arguments around isolated '=' in a list of strings and joins fragments with brackets.
|
504
|
+
|
505
|
+
This function handles the following cases:
|
506
|
+
1. ['arg', '=', 'val'] becomes ['arg=val']
|
507
|
+
2. ['arg=', 'val'] becomes ['arg=val']
|
508
|
+
3. ['arg', '=val'] becomes ['arg=val']
|
509
|
+
4. Joins fragments with brackets, e.g., ['imgsz=[3,', '640,', '640]'] becomes ['imgsz=[3,640,640]']
|
510
|
+
|
511
|
+
Args:
|
512
|
+
args (List[str]): A list of strings where each element represents an argument or fragment.
|
513
|
+
|
514
|
+
Returns:
|
515
|
+
(List[str]): A list of strings where the arguments around isolated '=' are merged and fragments with brackets are joined.
|
516
|
+
|
517
|
+
Examples:
|
518
|
+
>>> args = ["arg1", "=", "value", "arg2=", "value2", "arg3", "=value3", "imgsz=[3,", "640,", "640]"]
|
519
|
+
>>> merge_equals_args(args)
|
520
|
+
['arg1=value', 'arg2=value2', 'arg3=value3', 'imgsz=[3,640,640]']
|
521
|
+
"""
|
522
|
+
new_args = []
|
523
|
+
current = ""
|
524
|
+
depth = 0
|
525
|
+
|
526
|
+
i = 0
|
527
|
+
while i < len(args):
|
528
|
+
arg = args[i]
|
529
|
+
|
530
|
+
# Handle equals sign merging
|
531
|
+
if arg == "=" and 0 < i < len(args) - 1: # merge ['arg', '=', 'val']
|
532
|
+
new_args[-1] += f"={args[i + 1]}"
|
533
|
+
i += 2
|
534
|
+
continue
|
535
|
+
elif arg.endswith("=") and i < len(args) - 1 and "=" not in args[i + 1]: # merge ['arg=', 'val']
|
536
|
+
new_args.append(f"{arg}{args[i + 1]}")
|
537
|
+
i += 2
|
538
|
+
continue
|
539
|
+
elif arg.startswith("=") and i > 0: # merge ['arg', '=val']
|
540
|
+
new_args[-1] += arg
|
541
|
+
i += 1
|
542
|
+
continue
|
543
|
+
|
544
|
+
# Handle bracket joining
|
545
|
+
depth += arg.count("[") - arg.count("]")
|
546
|
+
current += arg
|
547
|
+
if depth == 0:
|
548
|
+
new_args.append(current)
|
549
|
+
current = ""
|
550
|
+
|
551
|
+
i += 1
|
552
|
+
|
553
|
+
# Append any remaining current string
|
554
|
+
if current:
|
555
|
+
new_args.append(current)
|
556
|
+
|
557
|
+
return new_args
|
558
|
+
|
559
|
+
|
560
|
+
def handle_yolo_hub(args: List[str]) -> None:
|
561
|
+
"""
|
562
|
+
Handles Ultralytics HUB command-line interface (CLI) commands for authentication.
|
563
|
+
|
564
|
+
This function processes Ultralytics HUB CLI commands such as login and logout. It should be called when executing a
|
565
|
+
script with arguments related to HUB authentication.
|
566
|
+
|
567
|
+
Args:
|
568
|
+
args (List[str]): A list of command line arguments. The first argument should be either 'login'
|
569
|
+
or 'logout'. For 'login', an optional second argument can be the API key.
|
570
|
+
|
571
|
+
Examples:
|
572
|
+
$ yolo login YOUR_API_KEY
|
573
|
+
|
574
|
+
Notes:
|
575
|
+
- The function imports the 'hub' module from ultralytics to perform login and logout operations.
|
576
|
+
- For the 'login' command, if no API key is provided, an empty string is passed to the login function.
|
577
|
+
- The 'logout' command does not require any additional arguments.
|
578
|
+
"""
|
579
|
+
from ultralytics import hub
|
580
|
+
|
581
|
+
if args[0] == "login":
|
582
|
+
key = args[1] if len(args) > 1 else ""
|
583
|
+
# Log in to Ultralytics HUB using the provided API key
|
584
|
+
hub.login(key)
|
585
|
+
elif args[0] == "logout":
|
586
|
+
# Log out from Ultralytics HUB
|
587
|
+
hub.logout()
|
588
|
+
|
589
|
+
|
590
|
+
def handle_yolo_settings(args: List[str]) -> None:
|
591
|
+
"""
|
592
|
+
Handles YOLO settings command-line interface (CLI) commands.
|
593
|
+
|
594
|
+
This function processes YOLO settings CLI commands such as reset and updating individual settings. It should be
|
595
|
+
called when executing a script with arguments related to YOLO settings management.
|
596
|
+
|
597
|
+
Args:
|
598
|
+
args (List[str]): A list of command line arguments for YOLO settings management.
|
599
|
+
|
600
|
+
Examples:
|
601
|
+
>>> handle_yolo_settings(["reset"]) # Reset YOLO settings
|
602
|
+
>>> handle_yolo_settings(["default_cfg_path=yolo11n.yaml"]) # Update a specific setting
|
603
|
+
|
604
|
+
Notes:
|
605
|
+
- If no arguments are provided, the function will display the current settings.
|
606
|
+
- The 'reset' command will delete the existing settings file and create new default settings.
|
607
|
+
- Other arguments are treated as key-value pairs to update specific settings.
|
608
|
+
- The function will check for alignment between the provided settings and the existing ones.
|
609
|
+
- After processing, the updated settings will be displayed.
|
610
|
+
- For more information on handling YOLO settings, visit:
|
611
|
+
https://docs.ultralytics.com/quickstart/#ultralytics-settings
|
612
|
+
"""
|
613
|
+
url = "https://docs.ultralytics.com/quickstart/#ultralytics-settings" # help URL
|
614
|
+
try:
|
615
|
+
if any(args):
|
616
|
+
if args[0] == "reset":
|
617
|
+
SETTINGS_FILE.unlink() # delete the settings file
|
618
|
+
SETTINGS.reset() # create new settings
|
619
|
+
LOGGER.info("Settings reset successfully") # inform the user that settings have been reset
|
620
|
+
else: # save a new setting
|
621
|
+
new = dict(parse_key_value_pair(a) for a in args)
|
622
|
+
check_dict_alignment(SETTINGS, new)
|
623
|
+
SETTINGS.update(new)
|
624
|
+
|
625
|
+
LOGGER.info(SETTINGS) # print the current settings
|
626
|
+
LOGGER.info(f"💡 Learn more about Ultralytics Settings at {url}")
|
627
|
+
except Exception as e:
|
628
|
+
LOGGER.warning(f"settings error: '{e}'. Please see {url} for help.")
|
629
|
+
|
630
|
+
|
631
|
+
def handle_yolo_solutions(args: List[str]) -> None:
|
632
|
+
"""
|
633
|
+
Processes YOLO solutions arguments and runs the specified computer vision solutions pipeline.
|
634
|
+
|
635
|
+
Args:
|
636
|
+
args (List[str]): Command-line arguments for configuring and running the Ultralytics YOLO
|
637
|
+
solutions: https://docs.ultralytics.com/solutions/, It can include solution name, source,
|
638
|
+
and other configuration parameters.
|
639
|
+
|
640
|
+
Examples:
|
641
|
+
Run people counting solution with default settings:
|
642
|
+
>>> handle_yolo_solutions(["count"])
|
643
|
+
|
644
|
+
Run analytics with custom configuration:
|
645
|
+
>>> handle_yolo_solutions(["analytics", "conf=0.25", "source=path/to/video.mp4"])
|
646
|
+
|
647
|
+
Run inference with custom configuration, requires Streamlit version 1.29.0 or higher.
|
648
|
+
>>> handle_yolo_solutions(["inference", "model=yolo11n.pt"])
|
649
|
+
|
650
|
+
Notes:
|
651
|
+
- Arguments can be provided in the format 'key=value' or as boolean flags
|
652
|
+
- Available solutions are defined in SOLUTION_MAP with their respective classes and methods
|
653
|
+
- If an invalid solution is provided, defaults to 'count' solution
|
654
|
+
- Output videos are saved in 'runs/solution/{solution_name}' directory
|
655
|
+
- For 'analytics' solution, frame numbers are tracked for generating analytical graphs
|
656
|
+
- Video processing can be interrupted by pressing 'q'
|
657
|
+
- Processes video frames sequentially and saves output in .avi format
|
658
|
+
- If no source is specified, downloads and uses a default sample video
|
659
|
+
- The inference solution will be launched using the 'streamlit run' command.
|
660
|
+
- The Streamlit app file is located in the Ultralytics package directory.
|
661
|
+
"""
|
662
|
+
from ultralytics.solutions.config import SolutionConfig
|
663
|
+
|
664
|
+
full_args_dict = vars(SolutionConfig()) # arguments dictionary
|
665
|
+
overrides = {}
|
666
|
+
|
667
|
+
# check dictionary alignment
|
668
|
+
for arg in merge_equals_args(args):
|
669
|
+
arg = arg.lstrip("-").rstrip(",")
|
670
|
+
if "=" in arg:
|
671
|
+
try:
|
672
|
+
k, v = parse_key_value_pair(arg)
|
673
|
+
overrides[k] = v
|
674
|
+
except (NameError, SyntaxError, ValueError, AssertionError) as e:
|
675
|
+
check_dict_alignment(full_args_dict, {arg: ""}, e)
|
676
|
+
elif arg in full_args_dict and isinstance(full_args_dict.get(arg), bool):
|
677
|
+
overrides[arg] = True
|
678
|
+
check_dict_alignment(full_args_dict, overrides) # dict alignment
|
679
|
+
|
680
|
+
# Get solution name
|
681
|
+
if not args:
|
682
|
+
LOGGER.warning("No solution name provided. i.e `yolo solutions count`. Defaulting to 'count'.")
|
683
|
+
args = ["count"]
|
684
|
+
if args[0] == "help":
|
685
|
+
LOGGER.info(SOLUTIONS_HELP_MSG)
|
686
|
+
return # Early return for 'help' case
|
687
|
+
elif args[0] in SOLUTION_MAP:
|
688
|
+
solution_name = args.pop(0) # Extract the solution name directly
|
689
|
+
else:
|
690
|
+
LOGGER.warning(
|
691
|
+
f"❌ '{args[0]}' is not a valid solution. 💡 Defaulting to 'count'.\n"
|
692
|
+
f"🚀 Available solutions: {', '.join(list(SOLUTION_MAP.keys())[:-1])}\n"
|
693
|
+
)
|
694
|
+
solution_name = "count" # Default for invalid solution
|
695
|
+
|
696
|
+
if solution_name == "inference":
|
697
|
+
checks.check_requirements("streamlit>=1.29.0")
|
698
|
+
LOGGER.info("💡 Loading Ultralytics live inference app...")
|
699
|
+
subprocess.run(
|
700
|
+
[ # Run subprocess with Streamlit custom argument
|
701
|
+
"streamlit",
|
702
|
+
"run",
|
703
|
+
str(ROOT / "solutions/streamlit_inference.py"),
|
704
|
+
"--server.headless",
|
705
|
+
"true",
|
706
|
+
overrides.pop("model", "yolo11n.pt"),
|
707
|
+
]
|
708
|
+
)
|
709
|
+
else:
|
710
|
+
from ultralytics import solutions
|
711
|
+
|
712
|
+
solution = getattr(solutions, SOLUTION_MAP[solution_name])(is_cli=True, **overrides) # class i.e ObjectCounter
|
713
|
+
|
714
|
+
cap = cv2.VideoCapture(solution.CFG["source"]) # read the video file
|
715
|
+
if solution_name != "crop":
|
716
|
+
# extract width, height and fps of the video file, create save directory and initialize video writer
|
717
|
+
w, h, fps = (
|
718
|
+
int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS)
|
719
|
+
)
|
720
|
+
if solution_name == "analytics": # analytical graphs follow fixed shape for output i.e w=1920, h=1080
|
721
|
+
w, h = 1280, 720
|
722
|
+
save_dir = get_save_dir(SimpleNamespace(project="runs/solutions", name="exp", exist_ok=False))
|
723
|
+
save_dir.mkdir(parents=True) # create the output directory i.e. runs/solutions/exp
|
724
|
+
vw = cv2.VideoWriter(str(save_dir / f"{solution_name}.avi"), cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))
|
725
|
+
|
726
|
+
try: # Process video frames
|
727
|
+
f_n = 0 # frame number, required for analytical graphs
|
728
|
+
while cap.isOpened():
|
729
|
+
success, frame = cap.read()
|
730
|
+
if not success:
|
731
|
+
break
|
732
|
+
results = solution(frame, f_n := f_n + 1) if solution_name == "analytics" else solution(frame)
|
733
|
+
if solution_name != "crop":
|
734
|
+
vw.write(results.plot_im)
|
735
|
+
if cv2.waitKey(1) & 0xFF == ord("q"):
|
736
|
+
break
|
737
|
+
finally:
|
738
|
+
cap.release()
|
739
|
+
|
740
|
+
|
741
|
+
def parse_key_value_pair(pair: str = "key=value") -> tuple:
|
742
|
+
"""
|
743
|
+
Parses a key-value pair string into separate key and value components.
|
744
|
+
|
745
|
+
Args:
|
746
|
+
pair (str): A string containing a key-value pair in the format "key=value".
|
747
|
+
|
748
|
+
Returns:
|
749
|
+
key (str): The parsed key.
|
750
|
+
value (str): The parsed value.
|
751
|
+
|
752
|
+
Raises:
|
753
|
+
AssertionError: If the value is missing or empty.
|
754
|
+
|
755
|
+
Examples:
|
756
|
+
>>> key, value = parse_key_value_pair("model=yolo11n.pt")
|
757
|
+
>>> print(f"Key: {key}, Value: {value}")
|
758
|
+
Key: model, Value: yolo11n.pt
|
759
|
+
|
760
|
+
>>> key, value = parse_key_value_pair("epochs=100")
|
761
|
+
>>> print(f"Key: {key}, Value: {value}")
|
762
|
+
Key: epochs, Value: 100
|
763
|
+
|
764
|
+
Notes:
|
765
|
+
- The function splits the input string on the first '=' character.
|
766
|
+
- Leading and trailing whitespace is removed from both key and value.
|
767
|
+
- An assertion error is raised if the value is empty after stripping.
|
768
|
+
"""
|
769
|
+
k, v = pair.split("=", 1) # split on first '=' sign
|
770
|
+
k, v = k.strip(), v.strip() # remove spaces
|
771
|
+
assert v, f"missing '{k}' value"
|
772
|
+
return k, smart_value(v)
|
773
|
+
|
774
|
+
|
775
|
+
def smart_value(v: str) -> Any:
|
776
|
+
"""
|
777
|
+
Converts a string representation of a value to its appropriate Python type.
|
778
|
+
|
779
|
+
This function attempts to convert a given string into a Python object of the most appropriate type. It handles
|
780
|
+
conversions to None, bool, int, float, and other types that can be evaluated safely.
|
781
|
+
|
782
|
+
Args:
|
783
|
+
v (str): The string representation of the value to be converted.
|
784
|
+
|
785
|
+
Returns:
|
786
|
+
(Any): The converted value. The type can be None, bool, int, float, or the original string if no conversion
|
787
|
+
is applicable.
|
788
|
+
|
789
|
+
Examples:
|
790
|
+
>>> smart_value("42")
|
791
|
+
42
|
792
|
+
>>> smart_value("3.14")
|
793
|
+
3.14
|
794
|
+
>>> smart_value("True")
|
795
|
+
True
|
796
|
+
>>> smart_value("None")
|
797
|
+
None
|
798
|
+
>>> smart_value("some_string")
|
799
|
+
'some_string'
|
800
|
+
|
801
|
+
Notes:
|
802
|
+
- The function uses a case-insensitive comparison for boolean and None values.
|
803
|
+
- For other types, it attempts to use Python's eval() function, which can be unsafe if used on untrusted input.
|
804
|
+
- If no conversion is possible, the original string is returned.
|
805
|
+
"""
|
806
|
+
v_lower = v.lower()
|
807
|
+
if v_lower == "none":
|
808
|
+
return None
|
809
|
+
elif v_lower == "true":
|
810
|
+
return True
|
811
|
+
elif v_lower == "false":
|
812
|
+
return False
|
813
|
+
else:
|
814
|
+
try:
|
815
|
+
return eval(v)
|
816
|
+
except Exception:
|
817
|
+
return v
|
818
|
+
|
819
|
+
|
820
|
+
def entrypoint(debug: str = "") -> None:
|
821
|
+
"""
|
822
|
+
Ultralytics entrypoint function for parsing and executing command-line arguments.
|
823
|
+
|
824
|
+
This function serves as the main entry point for the Ultralytics CLI, parsing command-line arguments and
|
825
|
+
executing the corresponding tasks such as training, validation, prediction, exporting models, and more.
|
826
|
+
|
827
|
+
Args:
|
828
|
+
debug (str): Space-separated string of command-line arguments for debugging purposes.
|
829
|
+
|
830
|
+
Examples:
|
831
|
+
Train a detection model for 10 epochs with an initial learning_rate of 0.01:
|
832
|
+
>>> entrypoint("train data=coco8.yaml model=yolo11n.pt epochs=10 lr0=0.01")
|
833
|
+
|
834
|
+
Predict a YouTube video using a pretrained segmentation model at image size 320:
|
835
|
+
>>> entrypoint("predict model=yolo11n-seg.pt source='https://youtu.be/LNwODJXcvt4' imgsz=320")
|
836
|
+
|
837
|
+
Validate a pretrained detection model at batch-size 1 and image size 640:
|
838
|
+
>>> entrypoint("val model=yolo11n.pt data=coco8.yaml batch=1 imgsz=640")
|
839
|
+
|
840
|
+
Notes:
|
841
|
+
- If no arguments are passed, the function will display the usage help message.
|
842
|
+
- For a list of all available commands and their arguments, see the provided help messages and the
|
843
|
+
Ultralytics documentation at https://docs.ultralytics.com.
|
844
|
+
"""
|
845
|
+
args = (debug.split(" ") if debug else ARGV)[1:]
|
846
|
+
if not args: # no arguments passed
|
847
|
+
LOGGER.info(CLI_HELP_MSG)
|
848
|
+
return
|
849
|
+
|
850
|
+
special = {
|
851
|
+
"help": lambda: LOGGER.info(CLI_HELP_MSG),
|
852
|
+
"checks": checks.collect_system_info,
|
853
|
+
"version": lambda: LOGGER.info(__version__),
|
854
|
+
"settings": lambda: handle_yolo_settings(args[1:]),
|
855
|
+
"cfg": lambda: YAML.print(DEFAULT_CFG_PATH),
|
856
|
+
"hub": lambda: handle_yolo_hub(args[1:]),
|
857
|
+
"login": lambda: handle_yolo_hub(args),
|
858
|
+
"logout": lambda: handle_yolo_hub(args),
|
859
|
+
"copy-cfg": copy_default_cfg,
|
860
|
+
"solutions": lambda: handle_yolo_solutions(args[1:]),
|
861
|
+
}
|
862
|
+
full_args_dict = {**DEFAULT_CFG_DICT, **{k: None for k in TASKS}, **{k: None for k in MODES}, **special}
|
863
|
+
|
864
|
+
# Define common misuses of special commands, i.e. -h, -help, --help
|
865
|
+
special.update({k[0]: v for k, v in special.items()}) # singular
|
866
|
+
special.update({k[:-1]: v for k, v in special.items() if len(k) > 1 and k.endswith("s")}) # singular
|
867
|
+
special = {**special, **{f"-{k}": v for k, v in special.items()}, **{f"--{k}": v for k, v in special.items()}}
|
868
|
+
|
869
|
+
overrides = {} # basic overrides, i.e. imgsz=320
|
870
|
+
for a in merge_equals_args(args): # merge spaces around '=' sign
|
871
|
+
if a.startswith("--"):
|
872
|
+
LOGGER.warning(f"argument '{a}' does not require leading dashes '--', updating to '{a[2:]}'.")
|
873
|
+
a = a[2:]
|
874
|
+
if a.endswith(","):
|
875
|
+
LOGGER.warning(f"argument '{a}' does not require trailing comma ',', updating to '{a[:-1]}'.")
|
876
|
+
a = a[:-1]
|
877
|
+
if "=" in a:
|
878
|
+
try:
|
879
|
+
k, v = parse_key_value_pair(a)
|
880
|
+
if k == "cfg" and v is not None: # custom.yaml passed
|
881
|
+
LOGGER.info(f"Overriding {DEFAULT_CFG_PATH} with {v}")
|
882
|
+
overrides = {k: val for k, val in YAML.load(checks.check_yaml(v)).items() if k != "cfg"}
|
883
|
+
else:
|
884
|
+
overrides[k] = v
|
885
|
+
except (NameError, SyntaxError, ValueError, AssertionError) as e:
|
886
|
+
check_dict_alignment(full_args_dict, {a: ""}, e)
|
887
|
+
|
888
|
+
elif a in TASKS:
|
889
|
+
overrides["task"] = a
|
890
|
+
elif a in MODES:
|
891
|
+
overrides["mode"] = a
|
892
|
+
elif a.lower() in special:
|
893
|
+
special[a.lower()]()
|
894
|
+
return
|
895
|
+
elif a in DEFAULT_CFG_DICT and isinstance(DEFAULT_CFG_DICT[a], bool):
|
896
|
+
overrides[a] = True # auto-True for default bool args, i.e. 'yolo show' sets show=True
|
897
|
+
elif a in DEFAULT_CFG_DICT:
|
898
|
+
raise SyntaxError(
|
899
|
+
f"'{colorstr('red', 'bold', a)}' is a valid YOLO argument but is missing an '=' sign "
|
900
|
+
f"to set its value, i.e. try '{a}={DEFAULT_CFG_DICT[a]}'\n{CLI_HELP_MSG}"
|
901
|
+
)
|
902
|
+
else:
|
903
|
+
check_dict_alignment(full_args_dict, {a: ""})
|
904
|
+
|
905
|
+
# Check keys
|
906
|
+
check_dict_alignment(full_args_dict, overrides)
|
907
|
+
|
908
|
+
# Mode
|
909
|
+
mode = overrides.get("mode")
|
910
|
+
if mode is None:
|
911
|
+
mode = DEFAULT_CFG.mode or "predict"
|
912
|
+
LOGGER.warning(f"'mode' argument is missing. Valid modes are {MODES}. Using default 'mode={mode}'.")
|
913
|
+
elif mode not in MODES:
|
914
|
+
raise ValueError(f"Invalid 'mode={mode}'. Valid modes are {MODES}.\n{CLI_HELP_MSG}")
|
915
|
+
|
916
|
+
# Task
|
917
|
+
task = overrides.pop("task", None)
|
918
|
+
if task:
|
919
|
+
if task not in TASKS:
|
920
|
+
if task == "track":
|
921
|
+
LOGGER.warning(
|
922
|
+
"invalid 'task=track', setting 'task=detect' and 'mode=track'. Valid tasks are {TASKS}.\n{CLI_HELP_MSG}."
|
923
|
+
)
|
924
|
+
task, mode = "detect", "track"
|
925
|
+
else:
|
926
|
+
raise ValueError(f"Invalid 'task={task}'. Valid tasks are {TASKS}.\n{CLI_HELP_MSG}")
|
927
|
+
if "model" not in overrides:
|
928
|
+
overrides["model"] = TASK2MODEL[task]
|
929
|
+
|
930
|
+
# Model
|
931
|
+
model = overrides.pop("model", DEFAULT_CFG.model)
|
932
|
+
if model is None:
|
933
|
+
model = "yolo11n.pt"
|
934
|
+
LOGGER.warning(f"'model' argument is missing. Using default 'model={model}'.")
|
935
|
+
overrides["model"] = model
|
936
|
+
stem = Path(model).stem.lower()
|
937
|
+
if "rtdetr" in stem: # guess architecture
|
938
|
+
from ultralytics import RTDETR
|
939
|
+
|
940
|
+
model = RTDETR(model) # no task argument
|
941
|
+
elif "fastsam" in stem:
|
942
|
+
from ultralytics import FastSAM
|
943
|
+
|
944
|
+
model = FastSAM(model)
|
945
|
+
elif "sam_" in stem or "sam2_" in stem or "sam2.1_" in stem:
|
946
|
+
from ultralytics import SAM
|
947
|
+
|
948
|
+
model = SAM(model)
|
949
|
+
else:
|
950
|
+
from ultralytics import YOLO
|
951
|
+
|
952
|
+
model = YOLO(model, task=task)
|
953
|
+
if isinstance(overrides.get("pretrained"), str):
|
954
|
+
model.load(overrides["pretrained"])
|
955
|
+
|
956
|
+
# Task Update
|
957
|
+
if task != model.task:
|
958
|
+
if task:
|
959
|
+
LOGGER.warning(
|
960
|
+
f"conflicting 'task={task}' passed with 'task={model.task}' model. "
|
961
|
+
f"Ignoring 'task={task}' and updating to 'task={model.task}' to match model."
|
962
|
+
)
|
963
|
+
task = model.task
|
964
|
+
|
965
|
+
# Mode
|
966
|
+
if mode in {"predict", "track"} and "source" not in overrides:
|
967
|
+
overrides["source"] = (
|
968
|
+
"https://ultralytics.com/images/boats.jpg" if task == "obb" else DEFAULT_CFG.source or ASSETS
|
969
|
+
)
|
970
|
+
LOGGER.warning(f"'source' argument is missing. Using default 'source={overrides['source']}'.")
|
971
|
+
elif mode in {"train", "val"}:
|
972
|
+
if "data" not in overrides and "resume" not in overrides:
|
973
|
+
overrides["data"] = DEFAULT_CFG.data or TASK2DATA.get(task or DEFAULT_CFG.task, DEFAULT_CFG.data)
|
974
|
+
LOGGER.warning(f"'data' argument is missing. Using default 'data={overrides['data']}'.")
|
975
|
+
elif mode == "export":
|
976
|
+
if "format" not in overrides:
|
977
|
+
overrides["format"] = DEFAULT_CFG.format or "torchscript"
|
978
|
+
LOGGER.warning(f"'format' argument is missing. Using default 'format={overrides['format']}'.")
|
979
|
+
|
980
|
+
# Run command in python
|
981
|
+
getattr(model, mode)(**overrides) # default args from model
|
982
|
+
|
983
|
+
# Show help
|
984
|
+
LOGGER.info(f"💡 Learn more at https://docs.ultralytics.com/modes/{mode}")
|
985
|
+
|
986
|
+
# Recommend VS Code extension
|
987
|
+
if IS_VSCODE and SETTINGS.get("vscode_msg", True):
|
988
|
+
LOGGER.info(vscode_msg())
|
989
|
+
|
990
|
+
|
991
|
+
# Special modes --------------------------------------------------------------------------------------------------------
|
992
|
+
def copy_default_cfg() -> None:
|
993
|
+
"""
|
994
|
+
Copies the default configuration file and creates a new one with '_copy' appended to its name.
|
995
|
+
|
996
|
+
This function duplicates the existing default configuration file (DEFAULT_CFG_PATH) and saves it
|
997
|
+
with '_copy' appended to its name in the current working directory. It provides a convenient way
|
998
|
+
to create a custom configuration file based on the default settings.
|
999
|
+
|
1000
|
+
Examples:
|
1001
|
+
>>> copy_default_cfg()
|
1002
|
+
# Output: default.yaml copied to /path/to/current/directory/default_copy.yaml
|
1003
|
+
# Example YOLO command with this new custom cfg:
|
1004
|
+
# yolo cfg='/path/to/current/directory/default_copy.yaml' imgsz=320 batch=8
|
1005
|
+
|
1006
|
+
Notes:
|
1007
|
+
- The new configuration file is created in the current working directory.
|
1008
|
+
- After copying, the function prints a message with the new file's location and an example
|
1009
|
+
YOLO command demonstrating how to use the new configuration file.
|
1010
|
+
- This function is useful for users who want to modify the default configuration without
|
1011
|
+
altering the original file.
|
1012
|
+
"""
|
1013
|
+
new_file = Path.cwd() / DEFAULT_CFG_PATH.name.replace(".yaml", "_copy.yaml")
|
1014
|
+
shutil.copy2(DEFAULT_CFG_PATH, new_file)
|
1015
|
+
LOGGER.info(
|
1016
|
+
f"{DEFAULT_CFG_PATH} copied to {new_file}\n"
|
1017
|
+
f"Example YOLO command with this new custom cfg:\n yolo cfg='{new_file}' imgsz=320 batch=8"
|
1018
|
+
)
|
1019
|
+
|
1020
|
+
|
1021
|
+
if __name__ == "__main__":
|
1022
|
+
# Example: entrypoint(debug='yolo predict model=yolo11n.pt')
|
1023
|
+
entrypoint(debug="")
|