Reference for ultralytics/cfg/__init__.py
Note
This file is available at https://github.com/ultralytics/ultralytics/blob/main/ultralytics/cfg/__init__.py. If you spot a problem please help fix it by contributing a Pull Request 🛠️. Thank you 🙏!
ultralytics.cfg.cfg2dict
cfg2dict(cfg: Union[str, Path, Dict, SimpleNamespace]) -> Dict
Converts a configuration object to a dictionary.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cfg
|
str | Path | Dict | SimpleNamespace
|
Configuration object to be converted. Can be a file path, a string, a dictionary, or a SimpleNamespace object. |
required |
Returns:
Type | Description |
---|---|
dict
|
Configuration object in dictionary format. |
Examples:
Convert a YAML file path to a dictionary:
>>> config_dict = cfg2dict("config.yaml")
Convert a SimpleNamespace to a dictionary:
>>> from types import SimpleNamespace
>>> config_sn = SimpleNamespace(param1="value1", param2="value2")
>>> config_dict = cfg2dict(config_sn)
Pass through an already existing dictionary:
>>> config_dict = cfg2dict({"param1": "value1", "param2": "value2"})
Notes
- If cfg is a path or string, it's loaded as YAML and converted to a dictionary.
- If cfg is a SimpleNamespace object, it's converted to a dictionary using vars().
- If cfg is already a dictionary, it's returned unchanged.
Source code in ultralytics/cfg/__init__.py
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 |
|
ultralytics.cfg.get_cfg
get_cfg(
cfg: Union[str, Path, Dict, SimpleNamespace] = DEFAULT_CFG_DICT,
overrides: Dict = None,
) -> SimpleNamespace
Load and merge configuration data from a file or dictionary, with optional overrides.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cfg
|
str | Path | Dict | SimpleNamespace
|
Configuration data source. Can be a file path, dictionary, or SimpleNamespace object. |
DEFAULT_CFG_DICT
|
overrides
|
Dict | None
|
Dictionary containing key-value pairs to override the base configuration. |
None
|
Returns:
Type | Description |
---|---|
SimpleNamespace
|
Namespace containing the merged configuration arguments. |
Examples:
>>> from ultralytics.cfg import get_cfg
>>> config = get_cfg() # Load default configuration
>>> config_with_overrides = get_cfg("path/to/config.yaml", overrides={"epochs": 50, "batch_size": 16})
Notes
- If both
cfg
andoverrides
are provided, the values inoverrides
will take precedence. - Special handling ensures alignment and correctness of the configuration, such as converting numeric
project
andname
to strings and validating configuration keys and values. - The function performs type and value checks on the configuration data.
Source code in ultralytics/cfg/__init__.py
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 |
|
ultralytics.cfg.check_cfg
check_cfg(cfg: Dict, hard: bool = True) -> None
Checks configuration argument types and values for the Ultralytics library.
This function validates the types and values of configuration arguments, ensuring correctness and converting
them if necessary. It checks for specific key types defined in global variables such as CFG_FLOAT_KEYS
,
CFG_FRACTION_KEYS
, CFG_INT_KEYS
, and CFG_BOOL_KEYS
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
cfg
|
dict
|
Configuration dictionary to validate. |
required |
hard
|
bool
|
If True, raises exceptions for invalid types and values; if False, attempts to convert them. |
True
|
Examples:
>>> config = {
... "epochs": 50, # valid integer
... "lr0": 0.01, # valid float
... "momentum": 1.2, # invalid float (out of 0.0-1.0 range)
... "save": "true", # invalid bool
... }
>>> check_cfg(config, hard=False)
>>> print(config)
{'epochs': 50, 'lr0': 0.01, 'momentum': 1.2, 'save': False} # corrected 'save' key
Notes
- The function modifies the input dictionary in-place.
- None values are ignored as they may be from optional arguments.
- Fraction keys are checked to be within the range [0.0, 1.0].
Source code in ultralytics/cfg/__init__.py
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 |
|
ultralytics.cfg.get_save_dir
get_save_dir(args: SimpleNamespace, name: str = None) -> Path
Returns the directory path for saving outputs, derived from arguments or default settings.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
args
|
SimpleNamespace
|
Namespace object containing configurations such as 'project', 'name', 'task', 'mode', and 'save_dir'. |
required |
name
|
str | None
|
Optional name for the output directory. If not provided, it defaults to 'args.name' or the 'args.mode'. |
None
|
Returns:
Type | Description |
---|---|
Path
|
Directory path where outputs should be saved. |
Examples:
>>> from types import SimpleNamespace
>>> args = SimpleNamespace(project="my_project", task="detect", mode="train", exist_ok=True)
>>> save_dir = get_save_dir(args)
>>> print(save_dir)
my_project/detect/train
Source code in ultralytics/cfg/__init__.py
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 |
|
ultralytics.cfg._handle_deprecation
_handle_deprecation(custom: Dict) -> Dict
Handles deprecated configuration keys by mapping them to current equivalents with deprecation warnings.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
custom
|
dict
|
Configuration dictionary potentially containing deprecated keys. |
required |
Examples:
>>> custom_config = {"boxes": True, "hide_labels": "False", "line_thickness": 2}
>>> _handle_deprecation(custom_config)
>>> print(custom_config)
{'show_boxes': True, 'show_labels': True, 'line_width': 2}
Notes
This function modifies the input dictionary in-place, replacing deprecated keys with their current equivalents. It also handles value conversions where necessary, such as inverting boolean values for 'hide_labels' and 'hide_conf'.
Source code in ultralytics/cfg/__init__.py
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 |
|
ultralytics.cfg.check_dict_alignment
check_dict_alignment(base: Dict, custom: Dict, e: Exception = None) -> None
Checks alignment between custom and base configuration dictionaries, handling deprecated keys and providing error messages for mismatched keys.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
base
|
dict
|
The base configuration dictionary containing valid keys. |
required |
custom
|
dict
|
The custom configuration dictionary to be checked for alignment. |
required |
e
|
Exception | None
|
Optional error instance passed by the calling function. |
None
|
Raises:
Type | Description |
---|---|
SystemExit
|
If mismatched keys are found between the custom and base dictionaries. |
Examples:
>>> base_cfg = {"epochs": 50, "lr0": 0.01, "batch_size": 16}
>>> custom_cfg = {"epoch": 100, "lr": 0.02, "batch_size": 32}
>>> try:
... check_dict_alignment(base_cfg, custom_cfg)
... except SystemExit:
... print("Mismatched keys found")
Notes
- Suggests corrections for mismatched keys based on similarity to valid keys.
- Automatically replaces deprecated keys in the custom configuration with updated equivalents.
- Prints detailed error messages for each mismatched key to help users correct their configurations.
Source code in ultralytics/cfg/__init__.py
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 |
|
ultralytics.cfg.merge_equals_args
merge_equals_args(args: List[str]) -> List[str]
Merges arguments around isolated '=' in a list of strings and joins fragments with brackets.
This function handles the following cases
- ['arg', '=', 'val'] becomes ['arg=val']
- ['arg=', 'val'] becomes ['arg=val']
- ['arg', '=val'] becomes ['arg=val']
- Joins fragments with brackets, e.g., ['imgsz=[3,', '640,', '640]'] becomes ['imgsz=[3,640,640]']
Parameters:
Name | Type | Description | Default |
---|---|---|---|
args
|
List[str]
|
A list of strings where each element represents an argument or fragment. |
required |
Returns:
Type | Description |
---|---|
List[str]
|
A list of strings where the arguments around isolated '=' are merged and fragments with brackets are joined. |
Examples:
>>> args = ["arg1", "=", "value", "arg2=", "value2", "arg3", "=value3", "imgsz=[3,", "640,", "640]"]
>>> merge_equals_args(args)
['arg1=value', 'arg2=value2', 'arg3=value3', 'imgsz=[3,640,640]']
Source code in ultralytics/cfg/__init__.py
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 |
|
ultralytics.cfg.handle_yolo_hub
handle_yolo_hub(args: List[str]) -> None
Handles Ultralytics HUB command-line interface (CLI) commands for authentication.
This function processes Ultralytics HUB CLI commands such as login and logout. It should be called when executing a script with arguments related to HUB authentication.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
args
|
List[str]
|
A list of command line arguments. The first argument should be either 'login' or 'logout'. For 'login', an optional second argument can be the API key. |
required |
Examples:
$ yolo login YOUR_API_KEY
Notes
- The function imports the 'hub' module from ultralytics to perform login and logout operations.
- For the 'login' command, if no API key is provided, an empty string is passed to the login function.
- The 'logout' command does not require any additional arguments.
Source code in ultralytics/cfg/__init__.py
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 |
|
ultralytics.cfg.handle_yolo_settings
handle_yolo_settings(args: List[str]) -> None
Handles YOLO settings command-line interface (CLI) commands.
This function processes YOLO settings CLI commands such as reset and updating individual settings. It should be called when executing a script with arguments related to YOLO settings management.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
args
|
List[str]
|
A list of command line arguments for YOLO settings management. |
required |
Examples:
>>> handle_yolo_settings(["reset"]) # Reset YOLO settings
>>> handle_yolo_settings(["default_cfg_path=yolo11n.yaml"]) # Update a specific setting
Notes
- If no arguments are provided, the function will display the current settings.
- The 'reset' command will delete the existing settings file and create new default settings.
- Other arguments are treated as key-value pairs to update specific settings.
- The function will check for alignment between the provided settings and the existing ones.
- After processing, the updated settings will be displayed.
- For more information on handling YOLO settings, visit: https://docs.ultralytics.com/quickstart/#ultralytics-settings
Source code in ultralytics/cfg/__init__.py
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 |
|
ultralytics.cfg.handle_yolo_solutions
handle_yolo_solutions(args: List[str]) -> None
Processes YOLO solutions arguments and runs the specified computer vision solutions pipeline.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
args
|
List[str]
|
Command-line arguments for configuring and running the Ultralytics YOLO solutions: https://docs.ultralytics.com/solutions/, It can include solution name, source, and other configuration parameters. |
required |
Examples:
Run people counting solution with default settings:
>>> handle_yolo_solutions(["count"])
Run analytics with custom configuration:
>>> handle_yolo_solutions(["analytics", "conf=0.25", "source=path/to/video.mp4"])
Run inference with custom configuration, requires Streamlit version 1.29.0 or higher.
>>> handle_yolo_solutions(["inference", "model=yolo11n.pt"])
Notes
- Default configurations are merged from DEFAULT_SOL_DICT and DEFAULT_CFG_DICT
- Arguments can be provided in the format 'key=value' or as boolean flags
- Available solutions are defined in SOLUTION_MAP with their respective classes and methods
- If an invalid solution is provided, defaults to 'count' solution
- Output videos are saved in 'runs/solution/{solution_name}' directory
- For 'analytics' solution, frame numbers are tracked for generating analytical graphs
- Video processing can be interrupted by pressing 'q'
- Processes video frames sequentially and saves output in .avi format
- If no source is specified, downloads and uses a default sample video
- The inference solution will be launched using the 'streamlit run' command.
- The Streamlit app file is located in the Ultralytics package directory.
Source code in ultralytics/cfg/__init__.py
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 |
|
ultralytics.cfg.parse_key_value_pair
parse_key_value_pair(pair: str = 'key=value') -> tuple
Parses a key-value pair string into separate key and value components.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pair
|
str
|
A string containing a key-value pair in the format "key=value". |
'key=value'
|
Returns:
Name | Type | Description |
---|---|---|
key |
str
|
The parsed key. |
value |
str
|
The parsed value. |
Raises:
Type | Description |
---|---|
AssertionError
|
If the value is missing or empty. |
Examples:
>>> key, value = parse_key_value_pair("model=yolo11n.pt")
>>> print(f"Key: {key}, Value: {value}")
Key: model, Value: yolo11n.pt
>>> key, value = parse_key_value_pair("epochs=100")
>>> print(f"Key: {key}, Value: {value}")
Key: epochs, Value: 100
Notes
- The function splits the input string on the first '=' character.
- Leading and trailing whitespace is removed from both key and value.
- An assertion error is raised if the value is empty after stripping.
Source code in ultralytics/cfg/__init__.py
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 |
|
ultralytics.cfg.smart_value
smart_value(v: str) -> Any
Converts a string representation of a value to its appropriate Python type.
This function attempts to convert a given string into a Python object of the most appropriate type. It handles conversions to None, bool, int, float, and other types that can be evaluated safely.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
v
|
str
|
The string representation of the value to be converted. |
required |
Returns:
Type | Description |
---|---|
Any
|
The converted value. The type can be None, bool, int, float, or the original string if no conversion is applicable. |
Examples:
>>> smart_value("42")
42
>>> smart_value("3.14")
3.14
>>> smart_value("True")
True
>>> smart_value("None")
None
>>> smart_value("some_string")
'some_string'
Notes
- The function uses a case-insensitive comparison for boolean and None values.
- For other types, it attempts to use Python's eval() function, which can be unsafe if used on untrusted input.
- If no conversion is possible, the original string is returned.
Source code in ultralytics/cfg/__init__.py
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 |
|
ultralytics.cfg.entrypoint
entrypoint(debug: str = '') -> None
Ultralytics entrypoint function for parsing and executing command-line arguments.
This function serves as the main entry point for the Ultralytics CLI, parsing command-line arguments and executing the corresponding tasks such as training, validation, prediction, exporting models, and more.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
debug
|
str
|
Space-separated string of command-line arguments for debugging purposes. |
''
|
Examples:
Train a detection model for 10 epochs with an initial learning_rate of 0.01:
>>> entrypoint("train data=coco8.yaml model=yolo11n.pt epochs=10 lr0=0.01")
Predict a YouTube video using a pretrained segmentation model at image size 320:
>>> entrypoint("predict model=yolo11n-seg.pt source='https://youtu.be/LNwODJXcvt4' imgsz=320")
Validate a pretrained detection model at batch-size 1 and image size 640:
>>> entrypoint("val model=yolo11n.pt data=coco8.yaml batch=1 imgsz=640")
Notes
- If no arguments are passed, the function will display the usage help message.
- For a list of all available commands and their arguments, see the provided help messages and the Ultralytics documentation at https://docs.ultralytics.com.
Source code in ultralytics/cfg/__init__.py
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 |
|
ultralytics.cfg.copy_default_cfg
copy_default_cfg() -> None
Copies the default configuration file and creates a new one with '_copy' appended to its name.
This function duplicates the existing default configuration file (DEFAULT_CFG_PATH) and saves it with '_copy' appended to its name in the current working directory. It provides a convenient way to create a custom configuration file based on the default settings.
Examples:
>>> copy_default_cfg()
# Output: default.yaml copied to /path/to/current/directory/default_copy.yaml
# Example YOLO command with this new custom cfg:
# yolo cfg='/path/to/current/directory/default_copy.yaml' imgsz=320 batch=8
Notes
- The new configuration file is created in the current working directory.
- After copying, the function prints a message with the new file's location and an example YOLO command demonstrating how to use the new configuration file.
- This function is useful for users who want to modify the default configuration without altering the original file.
Source code in ultralytics/cfg/__init__.py
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 |
|