Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing YOLOv8 for Object Detection with PyTorch

Tech Apr 29 19

For object detection tasks in PyTorch using YOLOv8, the Ultralytics library provides a streamlined approach. Begin by ensuring the environment supports GPU acceleration if available.

import torch
from ultralytics import YOLO
import os

os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'

def setup_model():
    device_type = 'cuda' if torch.cuda.is_available() else 'cpu'
    print(f"Using device: {device_type}")
    
    model = YOLO('yolov8n.pt').to(device_type)
    return model, device_type

def train_model(model, config_path, device_type):
    model.train(data=config_path, epochs=100, device=device_type, workers=0, batch=2)
    model.val(device=device_type)

if __name__ == '__main__':
    yolo_model, device = setup_model()
    train_model(yolo_model, 'dataset_config.yaml', device)

Model weights (yolov8n.pt) should be downloaded from the official Ultralytics documentation and placed in the working directory. Additionally, install the ultralytics package via pip.

Dataset configuration is managed through a YAML file that defines paths to training, valdiation, and test sets:

train: /path/to/training/data
val: /path/to/validation/data
test: /path/to/test/data

nc: 3
classes: [rice, animal, other]

The dataset must follow standard YOLO formatting where each image has a corresponding annotation file with matching filenames. Tools like makesense.ai can assist in creating labeled datsaets.

After training, best performing model is saved as best.pt within the generated runs/detect/train/weights/ directory. To perform inference:

import matplotlib.pyplot as plt
from ultralytics import YOLO

inference_model = YOLO('runs/detect/train/weights/best.pt')
sample_image = 'test_images/sample.jpg'

predictions = inference_model(sample_image)

if isinstance(predictions, list):
    for prediction in predictions:
        prediction.show()
else:
    predictions.show()

plt.imshow(predictions[0].orig_img)
plt.axis('off')
plt.show()

This workflow enables rapid deployment of custom object detection models using YOLOv8 architecture.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.