0%
YOLOv8: A Complete Guide to Object Detection

YOLOv8: A Complete Guide to Object Detection

Learn how to use YOLOv8 for real-time object detection with practical examples.

I

InSkillCoach

· min

YOLOv8: A Complete Guide to Object Detection

YOLOv8 is the latest version of the YOLO (You Only Look Once) algorithm, developed by Ultralytics. It offers improved performance and a more intuitive API.

1. Installation and Setup

# Install dependencies
pip install ultralytics opencv-python numpy

# Import the required libraries
from ultralytics import YOLO
import cv2
import numpy as np

2. Available Models

2.1 Loading the Models

# Load the different models
model_nano = YOLO('yolov8n.pt')  # Nano
model_small = YOLO('yolov8s.pt')  # Small
model_medium = YOLO('yolov8m.pt')  # Medium
model_large = YOLO('yolov8l.pt')  # Large
model_xlarge = YOLO('yolov8x.pt')  # XLarge

2.2 Comparing the Models

def compare_models():
    # Basic configuration
    test_image = "path/to/test/image.jpg"
    
    # Test the different models
    models = {
        'nano': model_nano,
        'small': model_small,
        'medium': model_medium,
        'large': model_large,
        'xlarge': model_xlarge
    }
    
    results = {}
    for name, model in models.items():
        # Measure inference time
        start_time = time.time()
        results[name] = model(test_image)
        inference_time = time.time() - start_time
        
        print(f"Modèle {name}:")
        print(f"Temps d'inférence: {inference_time:.2f}s")
        print(f"Nombre de détections: {len(results[name][0].boxes)}")

3. Object Detection

3.1 Basic Detection

def detect_objects(image_path):
    # Load the model
    model = YOLO('yolov8n.pt')
    
    # Detection
    results = model(image_path)
    
    # Process the results
    for result in results:
        boxes = result.boxes
        for box in boxes:
            # Box coordinates
            x1, y1, x2, y2 = box.xyxy[0]
            x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
            
            # Confidence
            confidence = float(box.conf[0])
            
            # Class
            class_id = int(box.cls[0])
            class_name = model.names[class_id]
            
            # Draw the box
            cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
            
            # Add the text
            label = f"{class_name} {confidence:.2f}"
            cv2.putText(image, label, (x1, y1 - 10),
                       cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
    
    return image

3.2 Real-Time Detection

def real_time_detection():
    # Initialize the camera
    cap = cv2.VideoCapture(0)
    
    # Load the model
    model = YOLO('yolov8n.pt')
    
    while cap.isOpened():
        success, frame = cap.read()
        if not success:
            continue
        
        # Detection
        results = model(frame)
        
        # Visualization
        annotated_frame = results[0].plot()
        
        # Display
        cv2.imshow('YOLOv8 Detection', annotated_frame)
        
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    cap.release()
    cv2.destroyAllWindows()

4. Segmentation

4.1 Instance Segmentation

def instance_segmentation():
    # Load the segmentation model
    model = YOLO('yolov8n-seg.pt')
    
    # Segmentation
    results = model('path/to/image.jpg')
    
    # Visualization
    for result in results:
        # Segmentation masks
        masks = result.masks
        if masks is not None:
            for mask in masks:
                # Convert the mask to an image
                mask_array = mask.data.cpu().numpy()
                
                # Apply the mask
                masked_image = cv2.bitwise_and(
                    image, image, mask=mask_array.astype(np.uint8)
                )
                
                # Display
                cv2.imshow('Segmentation', masked_image)

4.2 Real-Time Segmentation

def real_time_segmentation():
    # Initialization
    cap = cv2.VideoCapture(0)
    model = YOLO('yolov8n-seg.pt')
    
    while cap.isOpened():
        success, frame = cap.read()
        if not success:
            continue
        
        # Segmentation
        results = model(frame)
        
        # Visualization
        annotated_frame = results[0].plot()
        
        # Display
        cv2.imshow('YOLOv8 Segmentation', annotated_frame)
        
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    cap.release()
    cv2.destroyAllWindows()

5. Classification

5.1 Image Classification

def image_classification():
    # Load the classification model
    model = YOLO('yolov8n-cls.pt')
    
    # Classification
    results = model('path/to/image.jpg')
    
    # Process the results
    for result in results:
        # Class probabilities
        probs = result.probs
        
        # Predicted class
        predicted_class = probs.top1
        confidence = probs.top1conf
        
        print(f"Classe prédite: {model.names[predicted_class]}")
        print(f"Confiance: {confidence:.2f}")

5.2 Real-Time Classification

def real_time_classification():
    # Initialization
    cap = cv2.VideoCapture(0)
    model = YOLO('yolov8n-cls.pt')
    
    while cap.isOpened():
        success, frame = cap.read()
        if not success:
            continue
        
        # Classification
        results = model(frame)
        
        # Visualization
        annotated_frame = results[0].plot()
        
        # Display
        cv2.imshow('YOLOv8 Classification', annotated_frame)
        
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    cap.release()
    cv2.destroyAllWindows()

6. Custom Training

6.1 Preparing the Data

def prepare_training():
    # Dataset configuration
    data_yaml = """
    path: dataset  # Path to the dataset
    train: images/train  # Training images
    val: images/val  # Validation images
    
    # Classes
    names:
      0: person
      1: car
      2: truck
      # ... other classes
    """
    
    # Save the configuration
    with open('data.yaml', 'w') as f:
        f.write(data_yaml)

6.2 Training the Model

def train_model():
    # Load the model
    model = YOLO('yolov8n.pt')
    
    # Training configuration
    results = model.train(
        data='data.yaml',
        epochs=100,
        imgsz=640,
        batch=16,
        device='0',  # GPU
        workers=8,
        project='runs/train',
        name='exp'
    )

7. Optimization and Deployment

7.1 Exporting the Model

def export_model():
    # Load the model
    model = YOLO('yolov8n.pt')
    
    # Export to different formats
    model.export(format='onnx')  # ONNX
    model.export(format='engine')  # TensorRT
    model.export(format='coreml')  # CoreML
    model.export(format='tflite')  # TFLite

7.2 Performance Optimization

def optimize_performance():
    # Configuration for better performance
    model = YOLO('yolov8n.pt')
    
    # Parameter tuning
    results = model.predict(
        source='0',  # Camera
        conf=0.25,  # Confidence threshold
        iou=0.45,  # IoU threshold
        agnostic_nms=True,  # Class-agnostic NMS
        max_det=300,  # Maximum number of detections
        half=True  # Use FP16 precision
    )

8. Best Practices

  1. Model Selection

    • Nano for mobile devices
    • Small/Medium for general-purpose applications
    • Large/XLarge for maximum accuracy
  2. Optimization

    • Use FP16 precision on GPUs
    • Tune the confidence and IoU thresholds
    • Optimize the batch size
  3. Deployment

    • Export to the appropriate format
    • Use hardware acceleration
    • Implement a caching system

Conclusion

Key takeaways:

  • Improved performance
  • Intuitive API
  • Cross-platform support
  • Export to multiple formats

Recommendations:

  • Choose the right model for your needs
  • Optimize performance
  • Use hardware acceleration
  • Implement robust error handling
InSkillCoach

About InSkillCoach

Training and technology expert

Coach specializing in advanced technologies and AI, backed by GNeurone Inc.

Certifications:

  • AWS Certified Solutions Architect – Professional
  • Google Cloud certifications
  • Microsoft Certified: DevOps Engineer Expert
  • Certified Kubernetes Administrator (CKA)
  • CompTIA Security+
1.2k
113

Comments

Comments are powered by GitHub Discussions

Sign in with GitHub to join the discussion

Link copied!