ultralytics 8.2.60__py3-none-any.whl → 8.2.62__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.
Potentially problematic release.
This version of ultralytics might be problematic. Click here for more details.
- ultralytics/__init__.py +1 -1
- ultralytics/cfg/__init__.py +274 -133
- ultralytics/data/annotator.py +16 -12
- ultralytics/data/augment.py +1478 -195
- ultralytics/data/dataset.py +2 -0
- ultralytics/data/explorer/explorer.py +4 -0
- ultralytics/data/explorer/gui/dash.py +41 -26
- ultralytics/data/loaders.py +1 -1
- ultralytics/engine/model.py +490 -177
- ultralytics/engine/results.py +1035 -256
- ultralytics/models/fastsam/predict.py +1 -3
- ultralytics/models/fastsam/prompt.py +2 -2
- ultralytics/models/nas/predict.py +1 -3
- ultralytics/models/rtdetr/predict.py +4 -6
- ultralytics/models/sam/predict.py +1 -3
- ultralytics/nn/modules/block.py +2 -0
- ultralytics/nn/modules/head.py +2 -0
- ultralytics/solutions/parking_management.py +4 -0
- ultralytics/solutions/streamlit_inference.py +5 -2
- ultralytics/utils/benchmarks.py +2 -0
- ultralytics/utils/loss.py +3 -5
- ultralytics/utils/metrics.py +2 -0
- ultralytics/utils/tal.py +2 -0
- ultralytics/utils/torch_utils.py +3 -0
- {ultralytics-8.2.60.dist-info → ultralytics-8.2.62.dist-info}/METADATA +1 -1
- {ultralytics-8.2.60.dist-info → ultralytics-8.2.62.dist-info}/RECORD +30 -30
- {ultralytics-8.2.60.dist-info → ultralytics-8.2.62.dist-info}/WHEEL +1 -1
- {ultralytics-8.2.60.dist-info → ultralytics-8.2.62.dist-info}/LICENSE +0 -0
- {ultralytics-8.2.60.dist-info → ultralytics-8.2.62.dist-info}/entry_points.txt +0 -0
- {ultralytics-8.2.60.dist-info → ultralytics-8.2.62.dist-info}/top_level.txt +0 -0
ultralytics/__init__.py
CHANGED
ultralytics/cfg/__init__.py
CHANGED
|
@@ -79,7 +79,7 @@ CLI_HELP_MSG = f"""
|
|
|
79
79
|
yolo export model=yolov8n-cls.pt format=onnx imgsz=224,128
|
|
80
80
|
|
|
81
81
|
5. Explore your datasets using semantic search and SQL with a simple GUI powered by Ultralytics Explorer API
|
|
82
|
-
yolo explorer
|
|
82
|
+
yolo explorer data=data.yaml model=yolov8n.pt
|
|
83
83
|
|
|
84
84
|
6. Streamlit real-time object detection on your webcam with Ultralytics YOLOv8
|
|
85
85
|
yolo streamlit-predict
|
|
@@ -187,34 +187,31 @@ CFG_BOOL_KEYS = { # boolean-only arguments
|
|
|
187
187
|
|
|
188
188
|
def cfg2dict(cfg):
|
|
189
189
|
"""
|
|
190
|
-
|
|
190
|
+
Converts a configuration object to a dictionary.
|
|
191
191
|
|
|
192
192
|
Args:
|
|
193
|
-
cfg (str | Path |
|
|
194
|
-
|
|
193
|
+
cfg (str | Path | Dict | SimpleNamespace): Configuration object to be converted. Can be a file path,
|
|
194
|
+
a string, a dictionary, or a SimpleNamespace object.
|
|
195
195
|
|
|
196
196
|
Returns:
|
|
197
|
-
(
|
|
197
|
+
(Dict): Configuration object in dictionary format.
|
|
198
198
|
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
from types import SimpleNamespace
|
|
199
|
+
Examples:
|
|
200
|
+
Convert a YAML file path to a dictionary:
|
|
201
|
+
>>> config_dict = cfg2dict('config.yaml')
|
|
203
202
|
|
|
204
|
-
|
|
205
|
-
|
|
203
|
+
Convert a SimpleNamespace to a dictionary:
|
|
204
|
+
>>> from types import SimpleNamespace
|
|
205
|
+
>>> config_sn = SimpleNamespace(param1='value1', param2='value2')
|
|
206
|
+
>>> config_dict = cfg2dict(config_sn)
|
|
206
207
|
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
config_dict = cfg2dict(config_sn)
|
|
210
|
-
|
|
211
|
-
# Example usage with a dictionary (returns the same dictionary)
|
|
212
|
-
config_dict = cfg2dict({'param1': 'value1', 'param2': 'value2'})
|
|
213
|
-
```
|
|
208
|
+
Pass through an already existing dictionary:
|
|
209
|
+
>>> config_dict = cfg2dict({'param1': 'value1', 'param2': 'value2'})
|
|
214
210
|
|
|
215
211
|
Notes:
|
|
216
|
-
- If
|
|
217
|
-
- If
|
|
212
|
+
- If cfg is a path or string, it's loaded as YAML and converted to a dictionary.
|
|
213
|
+
- If cfg is a SimpleNamespace object, it's converted to a dictionary using vars().
|
|
214
|
+
- If cfg is already a dictionary, it's returned unchanged.
|
|
218
215
|
"""
|
|
219
216
|
if isinstance(cfg, (str, Path)):
|
|
220
217
|
cfg = yaml_load(cfg) # load dict
|
|
@@ -228,33 +225,23 @@ def get_cfg(cfg: Union[str, Path, Dict, SimpleNamespace] = DEFAULT_CFG_DICT, ove
|
|
|
228
225
|
Load and merge configuration data from a file or dictionary, with optional overrides.
|
|
229
226
|
|
|
230
227
|
Args:
|
|
231
|
-
cfg (str | Path |
|
|
232
|
-
|
|
233
|
-
|
|
228
|
+
cfg (str | Path | Dict | SimpleNamespace): Configuration data source. Can be a file path, dictionary, or
|
|
229
|
+
SimpleNamespace object.
|
|
230
|
+
overrides (Dict | None): Dictionary containing key-value pairs to override the base configuration.
|
|
234
231
|
|
|
235
232
|
Returns:
|
|
236
|
-
(SimpleNamespace): Namespace containing the merged
|
|
233
|
+
(SimpleNamespace): Namespace containing the merged configuration arguments.
|
|
234
|
+
|
|
235
|
+
Examples:
|
|
236
|
+
>>> from ultralytics.cfg import get_cfg
|
|
237
|
+
>>> config = get_cfg() # Load default configuration
|
|
238
|
+
>>> config = get_cfg('path/to/config.yaml', overrides={'epochs': 50, 'batch_size': 16})
|
|
237
239
|
|
|
238
240
|
Notes:
|
|
239
241
|
- If both `cfg` and `overrides` are provided, the values in `overrides` will take precedence.
|
|
240
|
-
- Special handling ensures alignment and correctness of the configuration, such as converting numeric
|
|
241
|
-
and `name` to strings and validating
|
|
242
|
-
|
|
243
|
-
Example:
|
|
244
|
-
```python
|
|
245
|
-
from ultralytics.cfg import get_cfg
|
|
246
|
-
|
|
247
|
-
# Load default configuration
|
|
248
|
-
config = get_cfg()
|
|
249
|
-
|
|
250
|
-
# Load from a custom file with overrides
|
|
251
|
-
config = get_cfg('path/to/config.yaml', overrides={'epochs': 50, 'batch_size': 16})
|
|
252
|
-
```
|
|
253
|
-
|
|
254
|
-
Configuration dictionary merged with overrides:
|
|
255
|
-
```python
|
|
256
|
-
{'epochs': 50, 'batch_size': 16, ...}
|
|
257
|
-
```
|
|
242
|
+
- Special handling ensures alignment and correctness of the configuration, such as converting numeric
|
|
243
|
+
`project` and `name` to strings and validating configuration keys and values.
|
|
244
|
+
- The function performs type and value checks on the configuration data.
|
|
258
245
|
"""
|
|
259
246
|
cfg = cfg2dict(cfg)
|
|
260
247
|
|
|
@@ -282,7 +269,33 @@ def get_cfg(cfg: Union[str, Path, Dict, SimpleNamespace] = DEFAULT_CFG_DICT, ove
|
|
|
282
269
|
|
|
283
270
|
|
|
284
271
|
def check_cfg(cfg, hard=True):
|
|
285
|
-
"""
|
|
272
|
+
"""
|
|
273
|
+
Checks configuration argument types and values for the Ultralytics library.
|
|
274
|
+
|
|
275
|
+
This function validates the types and values of configuration arguments, ensuring correctness and converting
|
|
276
|
+
them if necessary. It checks for specific key types defined in global variables such as CFG_FLOAT_KEYS,
|
|
277
|
+
CFG_FRACTION_KEYS, CFG_INT_KEYS, and CFG_BOOL_KEYS.
|
|
278
|
+
|
|
279
|
+
Args:
|
|
280
|
+
cfg (Dict): Configuration dictionary to validate.
|
|
281
|
+
hard (bool): If True, raises exceptions for invalid types and values; if False, attempts to convert them.
|
|
282
|
+
|
|
283
|
+
Examples:
|
|
284
|
+
>>> config = {
|
|
285
|
+
... 'epochs': 50, # valid integer
|
|
286
|
+
... 'lr0': 0.01, # valid float
|
|
287
|
+
... 'momentum': 1.2, # invalid float (out of 0.0-1.0 range)
|
|
288
|
+
... 'save': 'true', # invalid bool
|
|
289
|
+
... }
|
|
290
|
+
>>> check_cfg(config, hard=False)
|
|
291
|
+
>>> print(config)
|
|
292
|
+
{'epochs': 50, 'lr0': 0.01, 'momentum': 1.2, 'save': False} # corrected 'save' key
|
|
293
|
+
|
|
294
|
+
Notes:
|
|
295
|
+
- The function modifies the input dictionary in-place.
|
|
296
|
+
- None values are ignored as they may be from optional arguments.
|
|
297
|
+
- Fraction keys are checked to be within the range [0.0, 1.0].
|
|
298
|
+
"""
|
|
286
299
|
for k, v in cfg.items():
|
|
287
300
|
if v is not None: # None values may be from optional args
|
|
288
301
|
if k in CFG_FLOAT_KEYS and not isinstance(v, (int, float)):
|
|
@@ -318,7 +331,25 @@ def check_cfg(cfg, hard=True):
|
|
|
318
331
|
|
|
319
332
|
|
|
320
333
|
def get_save_dir(args, name=None):
|
|
321
|
-
"""
|
|
334
|
+
"""
|
|
335
|
+
Returns the directory path for saving outputs, derived from arguments or default settings.
|
|
336
|
+
|
|
337
|
+
Args:
|
|
338
|
+
args (SimpleNamespace): Namespace object containing configurations such as 'project', 'name', 'task',
|
|
339
|
+
'mode', and 'save_dir'.
|
|
340
|
+
name (str | None): Optional name for the output directory. If not provided, it defaults to 'args.name'
|
|
341
|
+
or the 'args.mode'.
|
|
342
|
+
|
|
343
|
+
Returns:
|
|
344
|
+
(Path): Directory path where outputs should be saved.
|
|
345
|
+
|
|
346
|
+
Examples:
|
|
347
|
+
>>> from types import SimpleNamespace
|
|
348
|
+
>>> args = SimpleNamespace(project='my_project', task='detect', mode='train', exist_ok=True)
|
|
349
|
+
>>> save_dir = get_save_dir(args)
|
|
350
|
+
>>> print(save_dir)
|
|
351
|
+
my_project/detect/train
|
|
352
|
+
"""
|
|
322
353
|
|
|
323
354
|
if getattr(args, "save_dir", None):
|
|
324
355
|
save_dir = args.save_dir
|
|
@@ -333,7 +364,23 @@ def get_save_dir(args, name=None):
|
|
|
333
364
|
|
|
334
365
|
|
|
335
366
|
def _handle_deprecation(custom):
|
|
336
|
-
"""
|
|
367
|
+
"""
|
|
368
|
+
Handles deprecated configuration keys by mapping them to current equivalents with deprecation warnings.
|
|
369
|
+
|
|
370
|
+
Args:
|
|
371
|
+
custom (Dict): Configuration dictionary potentially containing deprecated keys.
|
|
372
|
+
|
|
373
|
+
Examples:
|
|
374
|
+
>>> custom_config = {"boxes": True, "hide_labels": "False", "line_thickness": 2}
|
|
375
|
+
>>> _handle_deprecation(custom_config)
|
|
376
|
+
>>> print(custom_config)
|
|
377
|
+
{'show_boxes': True, 'show_labels': True, 'line_width': 2}
|
|
378
|
+
|
|
379
|
+
Notes:
|
|
380
|
+
This function modifies the input dictionary in-place, replacing deprecated keys with their current
|
|
381
|
+
equivalents. It also handles value conversions where necessary, such as inverting boolean values for
|
|
382
|
+
'hide_labels' and 'hide_conf'.
|
|
383
|
+
"""
|
|
337
384
|
|
|
338
385
|
for key in custom.copy().keys():
|
|
339
386
|
if key == "boxes":
|
|
@@ -354,35 +401,29 @@ def _handle_deprecation(custom):
|
|
|
354
401
|
|
|
355
402
|
def check_dict_alignment(base: Dict, custom: Dict, e=None):
|
|
356
403
|
"""
|
|
357
|
-
|
|
358
|
-
|
|
404
|
+
Checks alignment between custom and base configuration dictionaries, handling deprecated keys and providing error
|
|
405
|
+
messages for mismatched keys.
|
|
359
406
|
|
|
360
407
|
Args:
|
|
361
|
-
base (
|
|
362
|
-
custom (
|
|
363
|
-
e (Exception
|
|
408
|
+
base (Dict): The base configuration dictionary containing valid keys.
|
|
409
|
+
custom (Dict): The custom configuration dictionary to be checked for alignment.
|
|
410
|
+
e (Exception | None): Optional error instance passed by the calling function.
|
|
364
411
|
|
|
365
412
|
Raises:
|
|
366
|
-
SystemExit:
|
|
413
|
+
SystemExit: If mismatched keys are found between the custom and base dictionaries.
|
|
414
|
+
|
|
415
|
+
Examples:
|
|
416
|
+
>>> base_cfg = {'epochs': 50, 'lr0': 0.01, 'batch_size': 16}
|
|
417
|
+
>>> custom_cfg = {'epoch': 100, 'lr': 0.02, 'batch_size': 32}
|
|
418
|
+
>>> try:
|
|
419
|
+
... check_dict_alignment(base_cfg, custom_cfg)
|
|
420
|
+
... except SystemExit:
|
|
421
|
+
... print("Mismatched keys found")
|
|
367
422
|
|
|
368
423
|
Notes:
|
|
369
|
-
-
|
|
370
|
-
|
|
371
|
-
-
|
|
372
|
-
equivalents.
|
|
373
|
-
- A detailed error message is printed for each mismatched key, helping users to quickly identify and correct
|
|
374
|
-
their custom configurations.
|
|
375
|
-
|
|
376
|
-
Example:
|
|
377
|
-
```python
|
|
378
|
-
base_cfg = {'epochs': 50, 'lr0': 0.01, 'batch_size': 16}
|
|
379
|
-
custom_cfg = {'epoch': 100, 'lr': 0.02, 'batch_size': 32}
|
|
380
|
-
|
|
381
|
-
try:
|
|
382
|
-
check_dict_alignment(base_cfg, custom_cfg)
|
|
383
|
-
except SystemExit:
|
|
384
|
-
# Handle the error or correct the configuration
|
|
385
|
-
```
|
|
424
|
+
- Suggests corrections for mismatched keys based on similarity to valid keys.
|
|
425
|
+
- Automatically replaces deprecated keys in the custom configuration with updated equivalents.
|
|
426
|
+
- Prints detailed error messages for each mismatched key to help users correct their configurations.
|
|
386
427
|
"""
|
|
387
428
|
custom = _handle_deprecation(custom)
|
|
388
429
|
base_keys, custom_keys = (set(x.keys()) for x in (base, custom))
|
|
@@ -401,30 +442,21 @@ def check_dict_alignment(base: Dict, custom: Dict, e=None):
|
|
|
401
442
|
|
|
402
443
|
def merge_equals_args(args: List[str]) -> List[str]:
|
|
403
444
|
"""
|
|
404
|
-
Merges arguments around isolated '='
|
|
405
|
-
|
|
445
|
+
Merges arguments around isolated '=' in a list of strings, handling three cases:
|
|
446
|
+
1. ['arg', '=', 'val'] becomes ['arg=val'],
|
|
447
|
+
2. ['arg=', 'val'] becomes ['arg=val'],
|
|
448
|
+
3. ['arg', '=val'] becomes ['arg=val'].
|
|
406
449
|
|
|
407
450
|
Args:
|
|
408
|
-
args (List[str]): A list of strings where each element
|
|
451
|
+
args (List[str]): A list of strings where each element represents an argument.
|
|
409
452
|
|
|
410
453
|
Returns:
|
|
411
454
|
(List[str]): A list of strings where the arguments around isolated '=' are merged.
|
|
412
455
|
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
new_args = merge_equals_args(args)
|
|
418
|
-
print(new_args) # Output: ["arg1=value"]
|
|
419
|
-
|
|
420
|
-
args = ["arg1=", "value"]
|
|
421
|
-
new_args = merge_equals_args(args)
|
|
422
|
-
print(new_args) # Output: ["arg1=value"]
|
|
423
|
-
|
|
424
|
-
args = ["arg1", "=value"]
|
|
425
|
-
new_args = merge_equals_args(args)
|
|
426
|
-
print(new_args) # Output: ["arg1=value"]
|
|
427
|
-
```
|
|
456
|
+
Examples:
|
|
457
|
+
>>> args = ["arg1", "=", "value", "arg2=", "value2", "arg3", "=value3"]
|
|
458
|
+
>>> merge_equals_args(args)
|
|
459
|
+
['arg1=value', 'arg2=value2', 'arg3=value3']
|
|
428
460
|
"""
|
|
429
461
|
new_args = []
|
|
430
462
|
for i, arg in enumerate(args):
|
|
@@ -443,21 +475,24 @@ def merge_equals_args(args: List[str]) -> List[str]:
|
|
|
443
475
|
|
|
444
476
|
def handle_yolo_hub(args: List[str]) -> None:
|
|
445
477
|
"""
|
|
446
|
-
|
|
478
|
+
Handles Ultralytics HUB command-line interface (CLI) commands for authentication.
|
|
447
479
|
|
|
448
|
-
This function processes Ultralytics HUB CLI commands such as login and logout. It should be called when executing
|
|
449
|
-
|
|
480
|
+
This function processes Ultralytics HUB CLI commands such as login and logout. It should be called when executing a
|
|
481
|
+
script with arguments related to HUB authentication.
|
|
450
482
|
|
|
451
483
|
Args:
|
|
452
|
-
args (List[str]): A list of command line arguments.
|
|
484
|
+
args (List[str]): A list of command line arguments. The first argument should be either 'login'
|
|
485
|
+
or 'logout'. For 'login', an optional second argument can be the API key.
|
|
453
486
|
|
|
454
|
-
|
|
455
|
-
None
|
|
456
|
-
|
|
457
|
-
Example:
|
|
487
|
+
Examples:
|
|
458
488
|
```bash
|
|
459
489
|
yolo hub login YOUR_API_KEY
|
|
460
490
|
```
|
|
491
|
+
|
|
492
|
+
Notes:
|
|
493
|
+
- The function imports the 'hub' module from ultralytics to perform login and logout operations.
|
|
494
|
+
- For the 'login' command, if no API key is provided, an empty string is passed to the login function.
|
|
495
|
+
- The 'logout' command does not require any additional arguments.
|
|
461
496
|
"""
|
|
462
497
|
from ultralytics import hub
|
|
463
498
|
|
|
@@ -472,25 +507,26 @@ def handle_yolo_hub(args: List[str]) -> None:
|
|
|
472
507
|
|
|
473
508
|
def handle_yolo_settings(args: List[str]) -> None:
|
|
474
509
|
"""
|
|
475
|
-
|
|
510
|
+
Handles YOLO settings command-line interface (CLI) commands.
|
|
476
511
|
|
|
477
|
-
This function processes YOLO settings CLI commands such as reset. It should be
|
|
478
|
-
arguments related to YOLO settings management.
|
|
512
|
+
This function processes YOLO settings CLI commands such as reset and updating individual settings. It should be
|
|
513
|
+
called when executing a script with arguments related to YOLO settings management.
|
|
479
514
|
|
|
480
515
|
Args:
|
|
481
516
|
args (List[str]): A list of command line arguments for YOLO settings management.
|
|
482
517
|
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
Example:
|
|
487
|
-
```bash
|
|
488
|
-
yolo settings reset
|
|
489
|
-
```
|
|
518
|
+
Examples:
|
|
519
|
+
>>> handle_yolo_settings(["reset"]) # Reset YOLO settings
|
|
520
|
+
>>> handle_yolo_settings(["default_cfg_path=yolov8n.yaml"]) # Update a specific setting
|
|
490
521
|
|
|
491
522
|
Notes:
|
|
492
|
-
|
|
493
|
-
|
|
523
|
+
- If no arguments are provided, the function will display the current settings.
|
|
524
|
+
- The 'reset' command will delete the existing settings file and create new default settings.
|
|
525
|
+
- Other arguments are treated as key-value pairs to update specific settings.
|
|
526
|
+
- The function will check for alignment between the provided settings and the existing ones.
|
|
527
|
+
- After processing, the updated settings will be displayed.
|
|
528
|
+
- For more information on handling YOLO settings, visit:
|
|
529
|
+
https://docs.ultralytics.com/quickstart/#ultralytics-settings
|
|
494
530
|
"""
|
|
495
531
|
url = "https://docs.ultralytics.com/quickstart/#ultralytics-settings" # help URL
|
|
496
532
|
try:
|
|
@@ -510,22 +546,84 @@ def handle_yolo_settings(args: List[str]) -> None:
|
|
|
510
546
|
LOGGER.warning(f"WARNING ⚠️ settings error: '{e}'. Please see {url} for help.")
|
|
511
547
|
|
|
512
548
|
|
|
513
|
-
def handle_explorer():
|
|
514
|
-
"""
|
|
549
|
+
def handle_explorer(args: List[str]):
|
|
550
|
+
"""
|
|
551
|
+
This function launches a graphical user interface that provides tools for interacting with and analyzing datasets
|
|
552
|
+
using the Ultralytics Explorer API. It checks for the required 'streamlit' package and informs the user that the
|
|
553
|
+
Explorer dashboard is loading.
|
|
554
|
+
|
|
555
|
+
Args:
|
|
556
|
+
args (List[str]): A list of optional command line arguments.
|
|
557
|
+
|
|
558
|
+
Examples:
|
|
559
|
+
```bash
|
|
560
|
+
yolo explorer data=data.yaml model=yolov8n.pt
|
|
561
|
+
```
|
|
562
|
+
|
|
563
|
+
Notes:
|
|
564
|
+
- Requires 'streamlit' package version 1.29.0 or higher.
|
|
565
|
+
- The function does not take any arguments or return any values.
|
|
566
|
+
- It is typically called from the command line interface using the 'yolo explorer' command.
|
|
567
|
+
"""
|
|
515
568
|
checks.check_requirements("streamlit>=1.29.0")
|
|
516
569
|
LOGGER.info("💡 Loading Explorer dashboard...")
|
|
517
|
-
|
|
570
|
+
cmd = ["streamlit", "run", ROOT / "data/explorer/gui/dash.py", "--server.maxMessageSize", "2048"]
|
|
571
|
+
new = dict(parse_key_value_pair(a) for a in args)
|
|
572
|
+
check_dict_alignment(base={k: DEFAULT_CFG_DICT[k] for k in ["model", "data"]}, custom=new)
|
|
573
|
+
for k, v in new.items():
|
|
574
|
+
cmd += [k, v]
|
|
575
|
+
subprocess.run(cmd)
|
|
518
576
|
|
|
519
577
|
|
|
520
578
|
def handle_streamlit_inference():
|
|
521
|
-
"""
|
|
579
|
+
"""
|
|
580
|
+
Open the Ultralytics Live Inference Streamlit app for real-time object detection.
|
|
581
|
+
|
|
582
|
+
This function initializes and runs a Streamlit application designed for performing live object detection using
|
|
583
|
+
Ultralytics models. It checks for the required Streamlit package and launches the app.
|
|
584
|
+
|
|
585
|
+
Examples:
|
|
586
|
+
>>> handle_streamlit_inference()
|
|
587
|
+
|
|
588
|
+
Notes:
|
|
589
|
+
- Requires Streamlit version 1.29.0 or higher.
|
|
590
|
+
- The app is launched using the 'streamlit run' command.
|
|
591
|
+
- The Streamlit app file is located in the Ultralytics package directory.
|
|
592
|
+
"""
|
|
522
593
|
checks.check_requirements("streamlit>=1.29.0")
|
|
523
594
|
LOGGER.info("💡 Loading Ultralytics Live Inference app...")
|
|
524
595
|
subprocess.run(["streamlit", "run", ROOT / "solutions/streamlit_inference.py", "--server.headless", "true"])
|
|
525
596
|
|
|
526
597
|
|
|
527
|
-
def parse_key_value_pair(pair):
|
|
528
|
-
"""
|
|
598
|
+
def parse_key_value_pair(pair: str = "key=value"):
|
|
599
|
+
"""
|
|
600
|
+
Parses a key-value pair string into separate key and value components.
|
|
601
|
+
|
|
602
|
+
Args:
|
|
603
|
+
pair (str): A string containing a key-value pair in the format "key=value".
|
|
604
|
+
|
|
605
|
+
Returns:
|
|
606
|
+
(tuple): A tuple containing two elements:
|
|
607
|
+
- key (str): The parsed key.
|
|
608
|
+
- value (str): The parsed value.
|
|
609
|
+
|
|
610
|
+
Raises:
|
|
611
|
+
AssertionError: If the value is missing or empty.
|
|
612
|
+
|
|
613
|
+
Examples:
|
|
614
|
+
>>> key, value = parse_key_value_pair("model=yolov8n.pt")
|
|
615
|
+
>>> print(f"Key: {key}, Value: {value}")
|
|
616
|
+
Key: model, Value: yolov8n.pt
|
|
617
|
+
|
|
618
|
+
>>> key, value = parse_key_value_pair("epochs=100")
|
|
619
|
+
>>> print(f"Key: {key}, Value: {value}")
|
|
620
|
+
Key: epochs, Value: 100
|
|
621
|
+
|
|
622
|
+
Notes:
|
|
623
|
+
- The function splits the input string on the first '=' character.
|
|
624
|
+
- Leading and trailing whitespace is removed from both key and value.
|
|
625
|
+
- An assertion error is raised if the value is empty after stripping.
|
|
626
|
+
"""
|
|
529
627
|
k, v = pair.split("=", 1) # split on first '=' sign
|
|
530
628
|
k, v = k.strip(), v.strip() # remove spaces
|
|
531
629
|
assert v, f"missing '{k}' value"
|
|
@@ -533,7 +631,36 @@ def parse_key_value_pair(pair):
|
|
|
533
631
|
|
|
534
632
|
|
|
535
633
|
def smart_value(v):
|
|
536
|
-
"""
|
|
634
|
+
"""
|
|
635
|
+
Converts a string representation of a value to its appropriate Python type.
|
|
636
|
+
|
|
637
|
+
This function attempts to convert a given string into a Python object of the most appropriate type. It handles
|
|
638
|
+
conversions to None, bool, int, float, and other types that can be evaluated safely.
|
|
639
|
+
|
|
640
|
+
Args:
|
|
641
|
+
v (str): The string representation of the value to be converted.
|
|
642
|
+
|
|
643
|
+
Returns:
|
|
644
|
+
(Any): The converted value. The type can be None, bool, int, float, or the original string if no conversion
|
|
645
|
+
is applicable.
|
|
646
|
+
|
|
647
|
+
Examples:
|
|
648
|
+
>>> smart_value("42")
|
|
649
|
+
42
|
|
650
|
+
>>> smart_value("3.14")
|
|
651
|
+
3.14
|
|
652
|
+
>>> smart_value("True")
|
|
653
|
+
True
|
|
654
|
+
>>> smart_value("None")
|
|
655
|
+
None
|
|
656
|
+
>>> smart_value("some_string")
|
|
657
|
+
'some_string'
|
|
658
|
+
|
|
659
|
+
Notes:
|
|
660
|
+
- The function uses a case-insensitive comparison for boolean and None values.
|
|
661
|
+
- For other types, it attempts to use Python's eval() function, which can be unsafe if used on untrusted input.
|
|
662
|
+
- If no conversion is possible, the original string is returned.
|
|
663
|
+
"""
|
|
537
664
|
v_lower = v.lower()
|
|
538
665
|
if v_lower == "none":
|
|
539
666
|
return None
|
|
@@ -551,31 +678,26 @@ def entrypoint(debug=""):
|
|
|
551
678
|
"""
|
|
552
679
|
Ultralytics entrypoint function for parsing and executing command-line arguments.
|
|
553
680
|
|
|
554
|
-
This function serves as the main entry point for the Ultralytics CLI, parsing
|
|
681
|
+
This function serves as the main entry point for the Ultralytics CLI, parsing command-line arguments and
|
|
555
682
|
executing the corresponding tasks such as training, validation, prediction, exporting models, and more.
|
|
556
683
|
|
|
557
684
|
Args:
|
|
558
|
-
debug (str
|
|
685
|
+
debug (str): Space-separated string of command-line arguments for debugging purposes.
|
|
559
686
|
|
|
560
|
-
|
|
561
|
-
|
|
687
|
+
Examples:
|
|
688
|
+
Train a detection model for 10 epochs with an initial learning_rate of 0.01:
|
|
689
|
+
>>> entrypoint("train data=coco8.yaml model=yolov8n.pt epochs=10 lr0=0.01")
|
|
562
690
|
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
documentation at https://docs.ultralytics.com.
|
|
566
|
-
- If no arguments are passed, the function will display the usage help message.
|
|
567
|
-
|
|
568
|
-
Example:
|
|
569
|
-
```python
|
|
570
|
-
# Train a detection model for 10 epochs with an initial learning_rate of 0.01
|
|
571
|
-
entrypoint("train data=coco8.yaml model=yolov8n.pt epochs=10 lr0=0.01")
|
|
691
|
+
Predict a YouTube video using a pretrained segmentation model at image size 320:
|
|
692
|
+
>>> entrypoint("predict model=yolov8n-seg.pt source='https://youtu.be/LNwODJXcvt4' imgsz=320")
|
|
572
693
|
|
|
573
|
-
|
|
574
|
-
entrypoint("
|
|
694
|
+
Validate a pretrained detection model at batch-size 1 and image size 640:
|
|
695
|
+
>>> entrypoint("val model=yolov8n.pt data=coco8.yaml batch=1 imgsz=640")
|
|
575
696
|
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
697
|
+
Notes:
|
|
698
|
+
- If no arguments are passed, the function will display the usage help message.
|
|
699
|
+
- For a list of all available commands and their arguments, see the provided help messages and the
|
|
700
|
+
Ultralytics documentation at https://docs.ultralytics.com.
|
|
579
701
|
"""
|
|
580
702
|
args = (debug.split(" ") if debug else ARGV)[1:]
|
|
581
703
|
if not args: # no arguments passed
|
|
@@ -591,7 +713,7 @@ def entrypoint(debug=""):
|
|
|
591
713
|
"hub": lambda: handle_yolo_hub(args[1:]),
|
|
592
714
|
"login": lambda: handle_yolo_hub(args),
|
|
593
715
|
"copy-cfg": copy_default_cfg,
|
|
594
|
-
"explorer": lambda: handle_explorer(),
|
|
716
|
+
"explorer": lambda: handle_explorer(args[1:]),
|
|
595
717
|
"streamlit-predict": lambda: handle_streamlit_inference(),
|
|
596
718
|
}
|
|
597
719
|
full_args_dict = {**DEFAULT_CFG_DICT, **{k: None for k in TASKS}, **{k: None for k in MODES}, **special}
|
|
@@ -713,7 +835,26 @@ def entrypoint(debug=""):
|
|
|
713
835
|
|
|
714
836
|
# Special modes --------------------------------------------------------------------------------------------------------
|
|
715
837
|
def copy_default_cfg():
|
|
716
|
-
"""
|
|
838
|
+
"""
|
|
839
|
+
Copies the default configuration file and creates a new one with '_copy' appended to its name.
|
|
840
|
+
|
|
841
|
+
This function duplicates the existing default configuration file (DEFAULT_CFG_PATH) and saves it
|
|
842
|
+
with '_copy' appended to its name in the current working directory. It provides a convenient way
|
|
843
|
+
to create a custom configuration file based on the default settings.
|
|
844
|
+
|
|
845
|
+
Examples:
|
|
846
|
+
>>> copy_default_cfg()
|
|
847
|
+
# Output: default.yaml copied to /path/to/current/directory/default_copy.yaml
|
|
848
|
+
# Example YOLO command with this new custom cfg:
|
|
849
|
+
# yolo cfg='/path/to/current/directory/default_copy.yaml' imgsz=320 batch=8
|
|
850
|
+
|
|
851
|
+
Notes:
|
|
852
|
+
- The new configuration file is created in the current working directory.
|
|
853
|
+
- After copying, the function prints a message with the new file's location and an example
|
|
854
|
+
YOLO command demonstrating how to use the new configuration file.
|
|
855
|
+
- This function is useful for users who want to modify the default configuration without
|
|
856
|
+
altering the original file.
|
|
857
|
+
"""
|
|
717
858
|
new_file = Path.cwd() / DEFAULT_CFG_PATH.name.replace(".yaml", "_copy.yaml")
|
|
718
859
|
shutil.copy2(DEFAULT_CFG_PATH, new_file)
|
|
719
860
|
LOGGER.info(
|
ultralytics/data/annotator.py
CHANGED
|
@@ -9,20 +9,24 @@ def auto_annotate(data, det_model="yolov8x.pt", sam_model="sam_b.pt", device="",
|
|
|
9
9
|
"""
|
|
10
10
|
Automatically annotates images using a YOLO object detection model and a SAM segmentation model.
|
|
11
11
|
|
|
12
|
+
This function processes images in a specified directory, detects objects using a YOLO model, and then generates
|
|
13
|
+
segmentation masks using a SAM model. The resulting annotations are saved as text files.
|
|
14
|
+
|
|
12
15
|
Args:
|
|
13
16
|
data (str): Path to a folder containing images to be annotated.
|
|
14
|
-
det_model (str
|
|
15
|
-
sam_model (str
|
|
16
|
-
device (str
|
|
17
|
-
output_dir (str | None
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
17
|
+
det_model (str): Path or name of the pre-trained YOLO detection model.
|
|
18
|
+
sam_model (str): Path or name of the pre-trained SAM segmentation model.
|
|
19
|
+
device (str): Device to run the models on (e.g., 'cpu', 'cuda', '0').
|
|
20
|
+
output_dir (str | None): Directory to save the annotated results. If None, a default directory is created.
|
|
21
|
+
|
|
22
|
+
Examples:
|
|
23
|
+
>>> from ultralytics.data.annotator import auto_annotate
|
|
24
|
+
>>> auto_annotate(data='ultralytics/assets', det_model='yolov8n.pt', sam_model='mobile_sam.pt')
|
|
25
|
+
|
|
26
|
+
Notes:
|
|
27
|
+
- The function creates a new directory for output if not specified.
|
|
28
|
+
- Annotation results are saved as text files with the same names as the input images.
|
|
29
|
+
- Each line in the output text file represents a detected object with its class ID and segmentation points.
|
|
26
30
|
"""
|
|
27
31
|
det_model = YOLO(det_model)
|
|
28
32
|
sam_model = SAM(sam_model)
|