Preface
Organize some commonly used command line parameters from yolov8 official documents, official documents YOLOv8 Docs
The unified running format of the yolov8 command line is:
yolo TASK MODE ARGS
There are three main parts of parameter transfer:
- TASK (optional) is one of [detect, segment, classification]. If not passed explicitly, YOLOv8 will try to guess TASK from the model type.
- MODE (required) is one of [train, val, predict, export]
- ARGS (optional) is any number of custom arg=value pairs, such as imgsz=320, overriding the default value.
1. Training parameters
Training command line example:
# 从YAML中构建一个新模型,并从头开始训练
yolo detect train data=coco128.yaml model=yolov8n.yaml epochs=100 imgsz=640
# 从预先训练的*.pt模型开始训练
yolo detect train data=coco128.yaml model=yolov8n.pt epochs=100 imgsz=640
# 从YAML中构建一个新的模型,将预训练的权重传递给它,并开始训练
yolo detect train data=coco128.yaml model=yolov8n.yaml pretrained=yolov8n.pt epochs=100 imgsz=640
Corresponding python code example:
from ultralytics import YOLO
# Load a model
model = YOLO('yolov8n.yaml') # 从YAML中构建一个新模型
model = YOLO('yolov8n.pt') #加载预训练的模型(推荐用于训练)
model = YOLO('yolov8n.yaml').load('yolov8n.pt') # 从YAML构建并传递权重
# Train the model
model.train(data='coco128.yaml', epochs=100, imgsz=640)
Some of the more commonly used parameters:
key | explain |
---|---|
model | The passed in model.yaml file or model.pt file is used to build the network and initialize. The difference is that if only the yaml file is passed in, the parameters will be randomly initialized. |
data | Configuration yaml file of training data set |
epochs | Training rounds, default 100 |
patience | The number of rounds for early stop training and observation is 50 by default. If there is no accuracy improvement in 50 rounds, the model will stop training directly. |
batch | Training batch, default 16 |
imgs | Training image size, default 640 |
save | Save the training process and training weights, enabled by default |
save_period | During the training process, the training model is saved every x rounds, the default is -1 (not enabled) |
cache | Whether to use ram for data loading. Setting True will speed up training, but this parameter consumes very much memory and is generally set by servers. |
device | The device to run on, i.e. cuda device =0 or Device =0,1,2,3 or device=cpu |
workers | The number of threads to load data. Windows is generally 4, and the server can be larger. This parameter on Windows may cause thread errors. If you find that thread errors are reported, you can try to reduce this parameter. This parameter defaults to 8, and most of them need to be reduced. |
project | The name of the project folder, defaults to runs |
name | Used to save the training folder name, default exp, accumulated in sequence |
exist_ok | Whether to overwrite the existing save folder, default is False |
pretrained | Whether to load pre-trained weights, default is Flase |
optimizer | Optimizer selection, default SGD, optional [SGD, Adam, AdamW, RMSProP] |
verbose | Whether to print detailed output |
seed | Random seed, used to reproduce the model, default 0 |
deterministic | Set to True to ensure reproducibility of experiments |
single_cls | Train multi-category data into a single category and treat all data as a single category for training. The default is Flase. |
image_weights | Use weighted image selection for training, default is Flase |
rect | Use rectangle training, which is the same as rectangle inference. The default is False. |
cos_lr | Use cosine learning rate scheduling, default is Flase |
close_mosaic | Mosaic enhancement is disabled for the last x rounds, default 10 |
resume | Breakpoint training, default is Flase |
lr0 | Initialization learning rate, default 0.01 |
lrf | Final learning rate, default 0.01 |
label_smoothing | Label smoothing parameter, default 0.0 |
dropout | Use dropout regularization (classification only for training), default 0.0 |
Data augmentation parameters:
For more parameters, refer to: modes/train
2. Evaluation Parameters
Evaluate the command line code example:
yolo detect val model=yolov8n.pt # val 官方模型
yolo detect val model=path/to/best.pt # val 自己训练的模型
Corresponding python code:
from ultralytics import YOLO
# Load a model
model = YOLO('yolov8n.pt') #加载官方模型
model = YOLO('path/to/best.pt') # 加载自己训练的模型
# Validate the model
metrics = model.val() # no arguments needed, dataset and settings remembered
metrics.box.map # map50-95
metrics.box.map50 # map50
metrics.box.map75 # map75
metrics.box.maps # a list contains map50-95 of each category
Some of the more commonly used parameters:
key | explain |
---|---|
model | The path to the pt model file that needs to be evaluated |
data | Data set yaml file that needs to be evaluated |
imgs | Evaluate image inference size, default 640 |
batch | Evaluate inference batches, default 16 |
save_json | Whether to save the evaluation results as json output, the default is False |
save_hybrid | Whether to save mixed versions of labels (labels + extra predictions) |
conf | Model evaluation confidence threshold, default 0.001 |
iou | Model evaluation iou threshold, default 0.6 |
max_it | Maximum number of detected targets in a single image, default 300 |
half | Whether to use fp16 inference, default True |
device | The device to run on, i.e. cuda device =0 or Device =0,1,2,3 or device=cpu |
dnn | 是否使用use OpenCV DNN for ONNX inference,默认Flase |
rect | 是否使用矩形推理,默认False |
split | 数据集分割用于验证,即val、 test、train,默认val |
三、推理参数
推理命令行示例:
yolo detect predict model=yolov8n.pt source='https://ultralytics.com/images/bus.jpg' # predict with official model
yolo detect predict model=path/to/best.pt source='https://ultralytics.com/images/bus.jpg' # predict with custom model
对应python代码示例:
from ultralytics import YOLO
# Load a model
model = YOLO('yolov8n.pt') # load an official model
model = YOLO('path/to/best.pt') # load a custom model
# Predict with the model
results = model('https://ultralytics.com/images/bus.jpg') # predict on an image
# 目标检测后处理
boxes = results[0].boxes
boxes.xyxy # box with xyxy format, (N, 4)
boxes.xywh # box with xywh format, (N, 4)
boxes.xyxyn # box with xyxy format but normalized, (N, 4)
boxes.xywhn # box with xywh format but normalized, (N, 4)
boxes.conf # confidence score, (N, 1)
boxes.cls # cls, (N, 1)
boxes.data # raw bboxes tensor, (N, 6) or boxes.boxes .
# 实例分割后处理
masks = results[0].masks # Masks object
masks.segments # bounding coordinates of masks, List[segment] * N
masks.data # raw masks tensor, (N, H, W) or masks.masks
# 目标分类后处理
results = model(inputs)
results[0].probs # cls prob, (num_class, )
一些常用传参解释:
key | 解释 |
---|---|
source | 跟之前的yolov5一致,可以输入图片路径,图片文件夹路径,视频路径 |
save | 保存检测后输出的图像,默认False |
conf | 用于检测的对象置信阈值,默认0.25 |
iou | 用于nms的IOU阈值,默认0.7 |
half | FP16推理,默认False |
device | 要运行的设备,即cuda设备=0/1/2/3或设备=cpu |
show | 用于推理视频过程中展示推理结果,默认False |
save_txt | 是否把识别结果保存为txt,默认False |
save_conf | 保存带有置信度分数的结果 ,默认False |
save_crop | 保存带有结果的裁剪图像,默认False |
hide_label | 保存识别的图像时候是否隐藏label ,默认False |
hide_conf | 保存识别的图像时候是否隐藏置信度,默认False |
vid_stride | 视频检测中的跳帧帧数,默认1 |
classes | 展示特定类别的,根据类过滤结果,即class=0,或class=[0,2,3] |
line_thickness | 目标框中的线条粗细大小 ,默认3 |
visualize | 可视化模型特征 ,默认False |
augment | 是否使用数据增强,默认False |
agnostic_nms | 是否采用class-agnostic NMS,默认False |
retina_masks | 使用高分辨率分割掩码,默认False |
max_det | 单张图最大检测目标,默认300 |
box | 在分割人物中展示box信息,默认True |
yolov8支持各种输入源推理:
对于图片还支持以下保存格式的输入图片:
对于视频支持以下视频格式输入:
返回的result结果解析:
- Results.boxes: 目标检测返回的boxes信息
- Results.masks: 返回的分割mask坐标信息
- Results.probs: 分类输出的类概率
- Results.orig_img: 原始图像
- Results.path: 输入图像的路径
result可以使用如下方法在加载到cpu或者gpu设备中:
- results = results.cuda()
- results = results.cpu()
- results = results.to(“cpu”)
- results = results.numpy()
更多细节:modes/predict
四、模型导出
yolov8支持一键导出多种部署模型,支持如下格式的模型导出:
命令行运行示例:
yolo export model=yolov8n.pt format=onnx # export official model
yolo export model=path/to/best.pt format=onnx # export custom trained model
python代码示例:
from ultralytics import YOLO
# Load a model
model = YOLO('yolov8n.pt') # load an official model
model = YOLO('path/to/best.pt') # load a custom trained
# Export the model
model.export(format='onnx')
一些常用参数解释:
key | 解释 |
---|---|
format | 导出的格式,默认’torchscript’,可选如上支持的格式 onnx、engine、openvino等 |
imgsz | 导出时固定的图片推理大小,为标量或(h, w)列表,即(640,480) ,默认640 |
keras | 使用Keras导出TF SavedModel ,用于部署tensorflow模型,默认False |
optimize | 是否针对移动端对TorchScript进行优化 |
half | fp16量化导出,默认False |
int8 | int8量化导出,默认False |
dynamic | 针对ONNX/TF/TensorRT:动态推理,默认False |
simplify | onnx simplify简化,默认False |
opset | onnx的Opset版本(可选,默认为最新) |
workspace | TensorRT:工作空间大小(GB),默认4 |
nms | 导出CoreML,添加NMS |
更多参考:modes/export
五、跟踪参数
yolov8目前支持:BoT-SORT、ByteTrack两种目标跟踪,默认使用BoT-SORT
命令行使用示例:
yolo track model=yolov8n.pt source="https://youtu.be/Zgi9g1ksQHc" # official detection model
yolo track model=yolov8n-seg.pt source=... # official segmentation model
yolo track model=path/to/best.pt source=... # custom model
yolo track model=path/to/best.pt tracker="bytetrack.yaml" # bytetrack tracker
python代码使用示例:
from ultralytics import YOLO
# Load a model
model = YOLO('yolov8n.pt') # load an official detection model
model = YOLO('yolov8n-seg.pt') # load an official segmentation model
model = YOLO('path/to/best.pt') # load a custom model
# Track with the model
results = model.track(source="https://youtu.be/Zgi9g1ksQHc", show=True)
results = model.track(source="https://youtu.be/Zgi9g1ksQHc", show=True, tracker="bytetrack.yaml")
It supports both detection and segmentation models, and you only need to load the corresponding weights.
The parameters passed for tracking are the same as those used for inference. There are three main parameters: conf, iou, and show.
yolo track model=yolov8n.pt source="https://youtu.be/Zgi9g1ksQHc" conf=0.3, iou=0.5 show
# or
from ultralytics import YOLO
model = YOLO('yolov8n.pt')
results = model.track(source="https://youtu.be/Zgi9g1ksQHc", conf=0.3, iou=0.5, show=True)
You can also customize and modify the tracking configuration file. You need to modify the yaml file in ultralytics/tracker/cfg and modify the configuration you need (except for the tracker type). The same operation method:
yolo track model=yolov8n.pt source="https://youtu.be/Zgi9g1ksQHc" tracker='custom_tracker.yaml'
# or
from ultralytics import YOLO
model = YOLO('yolov8n.pt')
results = model.track(source="https://youtu.be/Zgi9g1ksQHc", tracker='custom_tracker.yaml')
6. Benchmark test parameters
Benchmark mode is used to analyze the speed and accuracy of YOLOv8's various export formats. Benchmarks provide information on the size of the export format, its mAP50-95 metric (for object detection and segmentation) or accuracy top5 metric (for classification), as well as on the performance of various export formats (such as ONNX, OpenVINO, TensorRT, etc.) , inference time per image in milliseconds. This information helps users choose the best export format for their specific use cases, based on their needs for speed and accuracy.
Command line code example:
yolo benchmark model=yolov8n.pt imgsz=640 half=False device=0
python code example:
from ultralytics.yolo.utils.benchmarks import benchmark
# Benchmark
benchmark(model='yolov8n.pt', imgsz=640, half=False, device=0)
Some common parameters for benchmark testing:
key | explain |
---|---|
model | Model file path, yoloV8v.pt, etc. |
imgs | Benchmark image size, default 640 |
half | Whether to enable fp16 for benchmark testing, default False |
device | On which devices are cuda tested device=0 or device=0,1,2,3 or device=cpu |
hard_fail | Stop continuing on error (bool) or val lower threshold (float), default False |
Benchmarks can support running tests on the following exported formats:
More reference: modes/benchmark
7. Other tasks
Segmentation reference: segment
Classification reference: classify