### Install YOLOv8 via Pip Source: https://github.com/akanametov/yolo-face/blob/dev/docs/quickstart.md Recommended method for installing the latest stable release of YOLOv8. No additional setup is required. ```bash pip install ultralytics ``` -------------------------------- ### Install Ultralytics YOLOv8 Source: https://github.com/akanametov/yolo-face/blob/dev/README.md Clone the repository and install the required packages using pip. Navigate to the code folder after installation. ```shell git clone https://github.com/akanametov/yolo-face pip install ultralytics cd yolo-face ``` -------------------------------- ### Install YOLOv8 via Git Clone Source: https://github.com/akanametov/yolo-face/blob/dev/docs/quickstart.md Use this method to install the most up-to-date version for development. Requires cloning the repository and installing in editable mode. ```bash git clone https://github.com/ultralytics/ultralytics cd ultralytics pip install -e '.[dev]' ``` -------------------------------- ### YOLO CLI Syntax and Examples Source: https://github.com/akanametov/yolo-face/blob/dev/docs/quickstart.md Demonstrates the general syntax for using the YOLO CLI for various tasks like training, validation, prediction, and export. Includes examples for single and multi-GPU training. ```bash yolo task=detect mode=train model=yolov8n.yaml args... classify predict yolov8n-cls.yaml args... segment val yolov8n-seg.yaml args... export yolov8n.pt format=onnx args... ``` ```bash yolo detect train model=yolov8n.pt data=coco128.yaml device=0 ``` ```bash yolo detect train model=yolov8n.pt data=coco128.yaml device='0,1,2,3' ``` -------------------------------- ### Python Docstring Example (Google Style) Source: https://github.com/akanametov/yolo-face/blob/dev/CONTRIBUTING.md Example of a Python docstring following the Google style guide, including sections for arguments, return values, and exceptions. ```python """ What the function does - performs nms on given detection predictions Args: arg1: The description of the 1st argument arg2: The description of the 2nd argument Returns: What the function returns. Empty if nothing is returned Raises: Exception Class: When and why this exception can be raised by the function. """ ``` -------------------------------- ### Install Ultralytics YOLOv8 Source: https://github.com/akanametov/yolo-face/blob/dev/examples/tutorial.ipynb Install the ultralytics package using pip. This is the recommended method for most users. It also runs checks to ensure your environment is set up correctly. ```python # Pip install method (recommended) %pip install ultralytics import ultralytics ultralytics.checks() ``` -------------------------------- ### Install Ultralytics for Model Conversion Source: https://github.com/akanametov/yolo-face/blob/dev/README.md Install the ultralytics package to enable model conversion to ONNX format. This is a prerequisite for the conversion script. ```shell # Install ultralytics pip install ultralytics ``` -------------------------------- ### YOLOv8 Detection Trainer Example Source: https://github.com/akanametov/yolo-face/blob/dev/docs/python.md Demonstrates initializing and using DetectionTrainer, DetectionValidator, and DetectionPredictor. Shows how to train a model, validate it, make predictions, and resume training from a checkpoint. ```python from ultralytics.yolo import v8 import DetectionTrainer, DetectionValidator, DetectionPredictor # trainer trainer = DetectionTrainer(overrides={}) trainer.train() trained_model = trainer.best # Validator val = DetectionValidator(args=...) val(model=trained_model) # predictor pred = DetectionPredictor(overrides={}) pred(source=SOURCE, model=trained_model) # resume from last weight overrides["resume"] = trainer.last trainer = detect.DetectionTrainer(overrides=overrides) ``` -------------------------------- ### Update requirements.txt Example Source: https://github.com/akanametov/yolo-face/blob/dev/CONTRIBUTING.md Illustrates the process of updating a dependency in the requirements.txt file as part of a pull request. ```text matplotlib version from 3.2.2 to 3.3 ``` -------------------------------- ### YOLOv8 Python Usage Examples Source: https://github.com/akanametov/yolo-face/blob/dev/docs/quickstart.md Provides examples of how to use the YOLOv8 Python interface to load models, train, validate, predict, and export models. Supports loading from YAML or pre-trained weights. ```python from ultralytics import YOLO # Load a model model = YOLO("yolov8n.yaml") # build a new model from scratch model = YOLO("yolov8n.pt") # load a pretrained model (recommended for training) # Use the model results = model.train(data="coco128.yaml", epochs=3) # train the model results = model.val() # evaluate model performance on the validation set results = model("https://ultralytics.com/images/bus.jpg") # predict on an image success = model.export(format="onnx") # export the model to ONNX format ``` -------------------------------- ### Initialize and Train DetectionTrainer Source: https://github.com/akanametov/yolo-face/blob/dev/docs/engine.md Instantiate the YOLOv8 DetectionTrainer with custom overrides and start the training process. Access the best trained model after completion. ```python from ultralytics.yolo.v8.detect import DetectionTrainer trainer = DetectionTrainer(overrides={...}) trainer.train() trained_model = trainer.best # get best model ``` -------------------------------- ### Navigate to Repository Directory Source: https://github.com/akanametov/yolo-face/blob/dev/docs/README.md Change the current directory to the root of the cloned ultralytics repository. This is necessary before installing the package. ```bash cd ultralytics ``` -------------------------------- ### Train YOLOv8 Model for Parking Detection Source: https://github.com/akanametov/yolo-face/blob/dev/README.md Command to train a YOLOv8 model for parking detection. This example specifies epochs, batch size, and image size for training. ```shell yolo task=detect \ mode=train \ model=yolov8m.pt \ data=datasets/data.yaml \ epochs=10 \ batch=32 \ imagsz=640 ``` -------------------------------- ### Train YOLOv8 Model Source: https://github.com/akanametov/yolo-face/blob/dev/docs/python.md Train a YOLOv8 model. Recommended to start from a pretrained model. Training from scratch requires a model configuration file and a dataset. ```python from ultralytics import YOLO model = YOLO("yolov8n.pt") # pass any model type model.train(epochs=5) ``` ```python from ultralytics import YOLO model = YOLO("yolov8n.yaml") model.train(data="coco128.yaml", epochs=5) ``` -------------------------------- ### Install Ultralytics in Developer Mode Source: https://github.com/akanametov/yolo-face/blob/dev/docs/README.md Install the ultralytics package in developer mode using pip. This allows for immediate reflection of code changes in your Python environment. Ensure you have Python 3 and Git installed. ```bash pip install -e '.[dev]' ``` -------------------------------- ### Add Custom Callbacks to Trainer Source: https://context7.com/akanametov/yolo-face/llms.txt Integrate custom functions as callbacks during the training process. This example shows logging the model checkpoint path after each training epoch. ```python # Add custom callbacks def log_model(trainer): """Callback to log model after each epoch""" last_weight = trainer.last print(f"Saved checkpoint: {last_weight}") trainer = CustomTrainer(overrides={'data': 'coco128.yaml'}) trainer.add_callback("on_train_epoch_end", log_model) trainer.train() ``` -------------------------------- ### Export Model to ONNX Format Source: https://context7.com/akanametov/yolo-face/llms.txt Export a trained YOLOv8 model to ONNX format for deployment. This example shows basic export and export with specific options like image size, FP16 quantization, dynamic shapes, simplification, and opset version. ```python from ultralytics import YOLO # Load a trained model model = YOLO("yolov8n.pt") # Export to ONNX format model.export(format="onnx") # Export with specific options model.export( format="onnx", imgsz=640, # Image size half=True, # FP16 quantization dynamic=True, # Dynamic input shapes simplify=True, # ONNX simplification opset=12 # ONNX opset version ) ``` -------------------------------- ### Perform Inference and Get Results Source: https://github.com/akanametov/yolo-face/blob/dev/docs/predict.md Use the model's call method for inference. Pass `stream=True` for memory-efficient streaming results. ```python inputs = [img, img] # list of np arrays results = model(inputs) # List of Results objects for result in results: boxes = result.boxes # Boxes object for bbox outputs masks = result.masks # Masks object for segmenation masks outputs probs = result.probs # Class probabilities for classification outputs ``` ```python inputs = [img, img] # list of numpy arrays results = model(inputs, stream=True) # generator of Results objects for r in results: boxes = r.boxes # Boxes object for bbox outputs masks = r.masks # Masks object for segmenation masks outputs probs = r.probs # Class probabilities for classification outputs ``` -------------------------------- ### Convert YOLOv8 Model to ONNX Format Source: https://context7.com/akanametov/yolo-face/llms.txt Export a trained YOLOv8 model to the ONNX format for deployment. This example shows default export and export with NMS included and GPU acceleration. ```python from ultralytics import YOLO # Load trained model model = YOLO("yolov12n-face.pt") # Convert to ONNX with default settings model.export(format="onnx") # Convert with NMS included in the model model.export( format="onnx", dynamic=False, # Static input shape nms=True, # Include NMS in export device="cuda:0" # Use GPU for export ) ``` -------------------------------- ### Serve MkDocs Documentation Locally Source: https://github.com/akanametov/yolo-face/blob/dev/docs/README.md Build and serve a local version of the MkDocs documentation site. This command is useful for development and testing, allowing immediate reflection of changes. The default host is localhost:8000. ```bash mkdocs serve ``` -------------------------------- ### Copy and Customize Configuration File Source: https://context7.com/akanametov/yolo-face/llms.txt Create a custom configuration file by copying the default one and modifying its parameters. This allows for more complex and persistent configuration changes. ```bash yolo copy-config yolo cfg=custom_config.yaml imgsz=320 ``` -------------------------------- ### Copy and Override Configuration File via CLI Source: https://github.com/akanametov/yolo-face/blob/dev/docs/cli.md Copy the default configuration file and then use the copied file to run a YOLO command, overriding specific arguments like image size. This allows for custom configurations. ```bash yolo copy-config yolo cfg=default_copy.yaml imgsz=320 ``` -------------------------------- ### Validate YOLOv8n on COCO128 Source: https://github.com/akanametov/yolo-face/blob/dev/examples/tutorial.ipynb Use this command to validate the YOLOv8n model on the COCO128 dataset. Ensure you have the YOLO CLI installed and the necessary datasets downloaded or accessible. ```bash !yolo task=detect mode=val model=yolov8n.pt data=coco128.yaml ``` -------------------------------- ### YOLO CLI: Multi-GPU Training Source: https://context7.com/akanametov/yolo-face/llms.txt Perform multi-GPU training for YOLOv8 detection models by specifying the device IDs. ```bash # Multi-GPU training yolo detect train data=coco128.yaml model=yolov8n.pt device=0,1,2,3 ``` -------------------------------- ### Deploy MkDocs Site to GitHub Pages Source: https://github.com/akanametov/yolo-face/blob/dev/docs/README.md Deploy your MkDocs documentation site to GitHub Pages using the gh-deploy plugin. Ensure your mkdocs.yml is configured for deployment. ```bash mkdocs gh-deploy ``` -------------------------------- ### Clone Ultralytics Repository Source: https://github.com/akanametov/yolo-face/blob/dev/docs/README.md Clone the ultralytics repository to your local machine using Git. This is the first step to setting up the development environment. ```bash git clone https://github.com/ultralytics/ultralytics.git ``` -------------------------------- ### Inference with YOLOv12m Builder Model Source: https://github.com/akanametov/yolo-face/blob/dev/README.md Run inference on an image using the yolov12m-builder model. This command is for detecting builders. ```shell yolo task=detect mode=predict model=yolov12m-builder.pt conf=0.2 imgsz=640 line_thickness=1 source=examples/builders.jpg ``` -------------------------------- ### Train YOLOv8 Model in Python Source: https://github.com/akanametov/yolo-face/blob/dev/ultralytics/models/README.md Instantiate and train a YOLOv8 model from scratch using its YAML configuration file within a Python environment. The 'model.info()' method displays model details. ```python from ultralytics import YOLO model = YOLO("yolov8n.yaml") # build a YOLOv8n model from scratch model.info() # display model information model.train(data="coco128.yaml", epochs=100) # train the model ``` -------------------------------- ### YOLOv8 Training Output Source: https://github.com/akanametov/yolo-face/blob/dev/examples/tutorial.ipynb This output provides a detailed log of the YOLOv8 training process, including version information, hardware details, training parameters, model architecture summary, optimizer configuration, dataset scanning progress, and augmentation settings. ```text Ultralytics YOLOv8.0.5 🚀 Python-3.8.16 torch-1.13.1+cu116 CUDA:0 (Tesla T4, 15110MiB)\nyolo/engine/trainer: task=detect, mode=train, model=yolov8n.pt, data=coco128.yaml, epochs=3, patience=50, batch=16, imgsz=640, save=True, cache=False, device=, workers=8, project=None, name=None, exist_ok=False, pretrained=False, optimizer=SGD, verbose=False, seed=0, deterministic=True, single_cls=False, image_weights=False, rect=False, cos_lr=False, close_mosaic=10, resume=False, overlap_mask=True, mask_ratio=4, dropout=0.0, val=True, save_json=False, save_hybrid=False, conf=None, iou=0.7, max_det=300, half=False, dnn=False, plots=True, source=None, show=False, save_txt=False, save_conf=False, save_crop=False, hide_labels=False, hide_conf=False, vid_stride=1, line_thickness=3, visualize=False, augment=False, agnostic_nms=False, retina_masks=False, format=torchscript, keras=False, optimize=False, int8=False, dynamic=False, simplify=False, opset=17, workspace=4, nms=False, lr0=0.01, lrf=0.01, momentum=0.937, weight_decay=0.0005, warmup_epochs=3.0, warmup_momentum=0.8, warmup_bias_lr=0.1, box=7.5, cls=0.5, dfl=1.5, fl_gamma=0.0, label_smoothing=0.0, nbs=64, hsv_h=0.015, hsv_s=0.7, hsv_v=0.4, degrees=0.0, translate=0.1, scale=0.5, shear=0.0, perspective=0.0, flipud=0.0, fliplr=0.5, mosaic=1.0, mixup=0.0, copy_paste=0.0, cfg=None, hydra={'output_subdir': None, 'run': {'dir': '.'}}, v5loader=False, save_dir=runs/detect/train\n\n from n params module arguments \n 0 -1 1 464 ultralytics.nn.modules.Conv [3, 16, 3, 2] \n 1 -1 1 4672 ultralytics.nn.modules.Conv [16, 32, 3, 2] \n 2 -1 1 7360 ultralytics.nn.modules.C2f [32, 32, 1, True] \n 3 -1 1 18560 ultralytics.nn.modules.Conv [32, 64, 3, 2] \n 4 -1 2 49664 ultralytics.nn.modules.C2f [64, 64, 2, True] \n 5 -1 1 73984 ultralytics.nn.modules.Conv [64, 128, 3, 2] \n 6 -1 2 197632 ultralytics.nn.modules.C2f [128, 128, 2, True] \n 7 -1 1 295424 ultralytics.nn.modules.Conv [128, 256, 3, 2] \n 8 -1 1 460288 ultralytics.nn.modules.C2f [256, 256, 1, True] \n 9 -1 1 164608 ultralytics.nn.modules.SPPF [256, 256, 5] \n 10 -1 1 0 torch.nn.modules.upsampling.Upsample [None, 2, 'nearest'] \n 11 [-1, 6] 1 0 ultralytics.nn.modules.Concat [1] \n 12 -1 1 148224 ultralytics.nn.modules.C2f [384, 128, 1] \n 13 -1 1 0 torch.nn.modules.upsampling.Upsample [None, 2, 'nearest'] \n 14 [-1, 4] 1 0 ultralytics.nn.modules.Concat [1] \n 15 -1 1 37248 ultralytics.nn.modules.C2f [192, 64, 1] \n 16 -1 1 36992 ultralytics.nn.modules.Conv [64, 64, 3, 2] \n 17 [-1, 12] 1 0 ultralytics.nn.modules.Concat [1] \n 18 -1 1 123648 ultralytics.nn.modules.C2f [192, 128, 1] \n 19 -1 1 147712 ultralytics.nn.modules.Conv [128, 128, 3, 2] \n 20 [-1, 9] 1 0 ultralytics.nn.modules.Concat [1] \n 21 -1 1 493056 ultralytics.nn.modules.C2f [384, 256, 1] \n 22 [15, 18, 21] 1 897664 ultralytics.nn.modules.Detect [80, [64, 128, 256]] \nModel summary: 225 layers, 3157200 parameters, 3157184 gradients, 8.9 GFLOPs\n\nTransferred 355/355 items from pretrained weights\noptimizer: SGD(lr=0.01) with parameter groups 57 weight(decay=0.0), 64 weight(decay=0.0005), 63 bias\ntrain: Scanning /datasets/coco128/labels/train2017.cache... 126 images, 2 backgrounds, 0 corrupt: 100% 128/128 [00:00 Trainer for details on the expected format # callback to upload model weights def log_model(trainer): last_weight_path = trainer.last ... trainer = CustomTrainer(overrides={...}) trainer.add_callback("on_train_epoch_end", log_model) # Adds to existing callback trainer.train() ``` -------------------------------- ### Train YOLOv8 Model Source: https://github.com/akanametov/yolo-face/blob/dev/docs/tasks/detection.md Train a YOLOv8 model from scratch or using a pretrained checkpoint. Specify the dataset, number of epochs, and image size. Ensure the 'data' argument points to your dataset configuration file. ```Python from ultralytics import YOLO # Load a model model = YOLO("yolov8n.yaml") # build a new model from scratch model = YOLO("yolov8n.pt") # load a pretrained model (recommended for training) # Train the model results = model.train(data="coco128.yaml", epochs=100, imgsz=640) ``` ```bash yolo detect train data=coco128.yaml model=yolov8n.pt epochs=100 imgsz=640 ``` -------------------------------- ### Customize DetectionTrainer with Custom Model Source: https://github.com/akanametov/yolo-face/blob/dev/docs/engine.md Extend the DetectionTrainer to support custom detection models by overriding the get_model method. This allows training models not directly supported by default. ```python from ultralytics.yolo.v8.detect import DetectionTrainer class CustomTrainer(DetectionTrainer): def get_model(self, cfg, weights): ... trainer = CustomTrainer(overrides={...}) trainer.train() ``` -------------------------------- ### YOLO CLI: Export Source: https://context7.com/akanametov/yolo-face/llms.txt Export YOLOv8 models to various formats like ONNX or TensorRT using the command-line interface. Specify the model, format, device, and other relevant options. ```bash # Export yolo export model=yolov8n.pt format=onnx yolo export model=yolov8n.pt format=engine device=0 half=True ``` -------------------------------- ### Inference with YOLOv8 Drone Model Source: https://github.com/akanametov/yolo-face/blob/dev/README.md Perform object detection on a drone image using a YOLOv8 model. Specify the model, confidence threshold, image size, and source image. ```shell yolo task=detect mode=predict model=yolov8m-drone.pt conf=0.25 imgsz=1280 line_thickness=1 source=examples/drone.jpg ``` -------------------------------- ### Export Model to PaddlePaddle Source: https://context7.com/akanametov/yolo-face/llms.txt Export a trained YOLOv8 model to PaddlePaddle format. ```python from ultralytics import YOLO model = YOLO("yolov8n.pt") # Export to PaddlePaddle model.export(format="paddle") ``` -------------------------------- ### Access Detection Results Source: https://context7.com/akanametov/yolo-face/llms.txt Access and process detection results including bounding boxes, confidence scores, class IDs, segmentation masks, and classification probabilities. Results can be converted to different devices and formats. ```python from ultralytics import YOLO model = YOLO("yolov8n.pt") results = model("bus.jpg") # Process each result for result in results: # Access bounding boxes boxes = result.boxes # Box coordinates in different formats xyxy = boxes.xyxy # [x1, y1, x2, y2] format (N, 4) xywh = boxes.xywh # [x, y, w, h] center format (N, 4) xyxyn = boxes.xyxyn # Normalized [x1, y1, x2, y2] (N, 4) xywhn = boxes.xywhn # Normalized [x, y, w, h] (N, 4) # Confidence scores and class IDs conf = boxes.conf # Confidence scores (N,) cls = boxes.cls # Class IDs (N,) # Raw tensor data data = boxes.data # [x1, y1, x2, y2, conf, cls] (N, 6) # Segmentation masks (for seg models) if result.masks is not None: masks = result.masks.data # Binary masks (N, H, W) segments = result.masks.segments # Polygon coordinates # Classification probabilities (for cls models) if result.probs is not None: probs = result.probs # Class probabilities (num_classes,) # Convert results to different devices/formats result = result.cpu() # Move to CPU result = result.cuda() # Move to GPU result = result.numpy() # Convert to numpy arrays result = result.to("cuda:0") # Move to specific device ``` -------------------------------- ### Export Model to OpenVINO Source: https://context7.com/akanametov/yolo-face/llms.txt Export a trained YOLOv8 model to OpenVINO format, with options for FP16 quantization. ```python from ultralytics import YOLO model = YOLO("yolov8n.pt") # Export to OpenVINO model.export(format="openvino", half=True) ``` -------------------------------- ### Predict with YOLOv8 Model Source: https://github.com/akanametov/yolo-face/blob/dev/docs/python.md Perform predictions using a YOLOv8 model on various sources including webcam, image folders, single images, and videos. Results can be saved and displayed. ```python from ultralytics import YOLO from PIL import Image import cv2 model = YOLO("model.pt") # accepts all formats - image/dir/Path/URL/video/PIL/ndarray. 0 for webcam results = model.predict(source="0") results = model.predict(source="folder", show=True) # Display preds. Accepts all YOLO predict arguments # from PIL im1 = Image.open("bus.jpg") results = model.predict(source=im1, save=True) # save plotted images # from ndarray im2 = cv2.imread("bus.jpg") results = model.predict(source=im2, save=True, save_txt=True) # save predictions as labels # from list of PIL/ndarray results = model.predict(source=[im1, im2]) ``` -------------------------------- ### Custom Trainer with Overridden Methods Source: https://context7.com/akanametov/yolo-face/llms.txt Extend the DetectionTrainer class to implement custom logic for model initialization, loss functions, or other training aspects. Ensure to call superclass methods where appropriate. ```python class CustomTrainer(DetectionTrainer): def get_model(self, cfg, weights): """Custom model initialization""" # Implement custom model loading return super().get_model(cfg, weights) def criterion(self, preds, batch): """Custom loss function""" imgs = batch["imgs"] bboxes = batch["bboxes"] # Implement custom loss calculation loss = ... loss_items = ... return loss, loss_items ```