__init__

Inhalt

`def entrypoint(debug=""): """ 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. Args: 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. """ args = (debug.split(" ") if debug else ARGV)[1:] if not args: # no arguments passed LOGGER.info(CLI_HELP_MSG) return special = { "help": lambda: LOGGER.info(CLI_HELP_MSG), "checks": checks.collect_system_info, "version": lambda: LOGGER.info(version), "settings": lambda: handle_yolo_settings(args[1:]), "cfg": lambda: yaml_print(DEFAULT_CFG_PATH), "hub": lambda: handle_yolo_hub(args[1:]), "login": lambda: handle_yolo_hub(args), "logout": lambda: handle_yolo_hub(args), "copy-cfg": copy_default_cfg, "streamlit-predict": lambda: handle_streamlit_inference(), "solutions": lambda: handle_yolo_solutions(args[1:]), } full_args_dict = {**DEFAULT_CFG_DICT, **{k: None for k in TASKS}, **{k: None for k in MODES}, **special}

Define common misuses of special commands, i.e. -h, -help, --help

special.update({k[0]: v for k, v in special.items()}) # singular special.update({k[:-1]: v for k, v in special.items() if len(k) > 1 and k.endswith("s")}) # singular special = {**special, **{f"-{k}": v for k, v in special.items()}, **{f"--{k}": v for k, v in special.items()}} overrides = {} # basic overrides, i.e. imgsz=320 for a in merge_equals_args(args): # merge spaces around '=' sign if a.startswith("--"): LOGGER.warning(f"WARNING ⚠️ argument '{a}' does not require leading dashes '--', updating to '{a[2:]}'.") a = a[2:] if a.endswith(","): LOGGER.warning(f"WARNING ⚠️ argument '{a}' does not require trailing comma ',', updating to '{a[:-1]}'.") a = a[:-1] if "=" in a: try: k, v = parse_key_value_pair(a) if k == "cfg" and v is not None: # custom.yaml passed LOGGER.info(f"Overriding {DEFAULT_CFG_PATH} with {v}") overrides = {k: val for k, val in yaml_load(checks.check_yaml(v)).items() if k != "cfg"} else: overrides[k] = v except (NameError, SyntaxError, ValueError, AssertionError) as e: check_dict_alignment(full_args_dict, {a: ""}, e) elif a in TASKS: overrides["task"] = a elif a in MODES: overrides["mode"] = a elif a.lower() in special: speciala.lower() return elif a in DEFAULT_CFG_DICT and isinstance(DEFAULT_CFG_DICT[a], bool): overrides[a] = True # auto-True for default bool args, i.e. 'yolo show' sets show=True elif a in DEFAULT_CFG_DICT: raise SyntaxError( f"'{colorstr('red', 'bold', a)}' is a valid YOLO argument but is missing an '=' sign " f"to set its value, i.e. try '{a}={DEFAULT_CFG_DICT[a]}'\n{CLI_HELP_MSG}" ) else: check_dict_alignment(full_args_dict, {a: ""})

Check keys

check_dict_alignment(full_args_dict, overrides)

Mode

mode = overrides.get("mode") if mode is None: mode = DEFAULT_CFG.mode or "predict" LOGGER.warning(f"WARNING ⚠️ 'mode' argument is missing. Valid modes are {MODES}. Using default 'mode={mode}'.") elif mode not in MODES: raise ValueError(f"Invalid 'mode={mode}'. Valid modes are {MODES}.\n{CLI_HELP_MSG}")

Task

task = overrides.pop("task", None) if task: if task not in TASKS: raise ValueError(f"Invalid 'task={task}'. Valid tasks are {TASKS}.\n{CLI_HELP_MSG}") if "model" not in overrides: overrides["model"] = TASK2MODEL[task]

Model

model = overrides.pop("model", DEFAULT_CFG.model) if model is None: model = "yolo11n.pt" LOGGER.warning(f"WARNING ⚠️ 'model' argument is missing. Using default 'model={model}'.") overrides["model"] = model stem = Path(model).stem.lower() if "rtdetr" in stem: # guess architecture from ultralytics import RTDETR model = RTDETR(model) # no task argument elif "fastsam" in stem: from ultralytics import FastSAM model = FastSAM(model) elif "sam_" in stem or "sam2_" in stem or "sam2.1_" in stem: from ultralytics import SAM model = SAM(model) else: from ultralytics import YOLO model = YOLO(model, task=task) if isinstance(overrides.get("pretrained"), str): model.load(overrides["pretrained"])

Task Update

if task != model.task: if task: LOGGER.warning( f"WARNING ⚠️ conflicting 'task={task}' passed with 'task={model.task}' model. " f"Ignoring 'task={task}' and updating to 'task={model.task}' to match model." ) task = model.task

Mode

if mode in {"predict", "track"} and "source" not in overrides: overrides["source"] = ( "https://ultralytics.com/images/boats.jpg" if task == "obb" else DEFAULT_CFG.source or ASSETS ) LOGGER.warning(f"WARNING ⚠️ 'source' argument is missing. Using default 'source={overrides['source']}'.") elif mode in {"train", "val"}: if "data" not in overrides and "resume" not in overrides: overrides["data"] = DEFAULT_CFG.data or TASK2DATA.get(task or DEFAULT_CFG.task, DEFAULT_CFG.data) LOGGER.warning(f"WARNING ⚠️ 'data' argument is missing. Using default 'data={overrides['data']}'.") elif mode == "export": if "format" not in overrides: overrides["format"] = DEFAULT_CFG.format or "torchscript" LOGGER.warning(f"WARNING ⚠️ 'format' argument is missing. Using default 'format={overrides['format']}'.")

Run command in python

getattr(model, mode)(**overrides) # default args from model

Show help

LOGGER.info(f"💡 Learn more at https://docs.ultralytics.com/modes/{mode}")

Recommend VS Code extension

if IS_VSCODE and SETTINGS.get("vscode_msg", True): LOGGER.info(vscode_msg())`

Zusammenfassen
该文章介绍了Ultralytics的入口函数entrypoint,用于解析和执行命令行参数。该函数是Ultralytics CLI的主要入口,支持训练、验证、预测、导出模型等任务。函数接受一个调试参数,若无参数则显示使用帮助信息。文章详细列出了可用命令及其参数,并提供了示例,如训练检测模型、预测视频等。函数内部处理了参数的解析、验证和默认值设置,确保用户输入的参数有效。特别命令如帮助、版本、设置等也被处理。最后,函数根据解析的参数执行相应的模型操作,并提供进一步的文档链接和VS Code扩展推荐。