📚
DLIP
  • Introduction
  • Prerequisite
  • Image Processing Basics
    • Notes
      • Thresholding
      • Spatial Filtering
      • Masking with Bitwise Operation
      • Model n Calibration
    • Tutorial
      • Tutorial: Install OpenCV C++
      • Tutorial: Create OpenCV Project
      • Tutorial: C++ basics
      • Tutorial: OpenCV Basics
      • Tutorial: Image Watch for Debugging
      • Tutorial: Spatial Filter
      • Tutorial: Thresholding and Morphology
      • Tutorial: Camera Calibration
      • Tutorial: Color Image Processing
      • Tutorial: Edge Line Circle Detection
      • Tutorial: Corner Detection and Optical Flow
      • Tutorial: OpenCV C++ Cheatsheet
      • Tutorial: Installation for Py OpenCV
      • Tutorial: OpenCv (Python) Basics
    • LAB
      • Lab Report Template
      • Lab Report Grading Criteria
      • LAB Report Instruction
      • LAB: Grayscale Image Segmentation
        • LAB: Grayscale Image Segmentation -Gear
        • LAB: Grayscale Image Segmentation - Bolt and Nut
      • LAB: Color Image Segmentation
        • LAB: Facial Temperature Measurement with IR images
        • LAB: Magic Cloak
      • LAB: Straight Lane Detection and Departure Warning
      • LAB: Dimension Measurement with 2D camera
      • LAB: Tension Detection of Rolling Metal Sheet
  • Deep Learning for Perception
    • Notes
      • Lane Detection with Deep Learning
      • Overview of Deep Learning
        • Object Detection
        • Deep Learning Basics: Introduction
        • Deep Learning State of the Art
        • CNN, Object Detection
      • Perceptron
      • Activation Function
      • Optimization
      • Convolution
      • CNN Overview
      • Evaluation Metric
      • LossFunction Regularization
      • Bias vs Variance
      • BottleNeck Unit
      • Object Detection
      • DL Techniques
        • Technical Strategy by A.Ng
    • Tutorial - PyTorch
      • Tutorial: Install PyTorch
      • Tutorial: Python Numpy
      • Tutorial: PyTorch Tutorial List
      • Tutorial: PyTorch Example Code
      • Tutorial: Tensorboard in Pytorch
      • Tutorial: YOLO in PyTorch
        • Tutorial: Yolov8 in PyTorch
        • Tutorial: Train Yolo v8 with custom dataset
          • Tutorial: Train Yolo v5 with custom dataset
        • Tutorial: Yolov5 in Pytorch (VS code)
        • Tutorial: Yolov3 in Keras
    • LAB
      • Assignment: CNN Classification
      • Assignment: Object Detection
      • LAB: CNN Object Detection 1
      • LAB: CNN Object Detection 2
      • LAB Grading Criteria
    • Tutorial- Keras
      • Train Dataset
      • Train custom dataset
      • Test model
      • LeNet-5 Tutorial
      • AlexNet Tutorial
      • VGG Tutorial
      • ResNet Tutorial
    • Resource
      • Online Lecture
      • Programming tutorial
      • Books
      • Hardware
      • Dataset
      • Useful sites
  • Must Read Papers
    • AlexNet
    • VGG
    • ResNet
    • R-CNN, Fast-RCNN, Faster-RCNN
    • YOLOv1-3
    • Inception
    • MobileNet
    • SSD
    • ShuffleNet
    • Recent Methods
  • DLIP Project
    • Report Template
    • DLIP 2021 Projects
      • Digital Door Lock Control with Face Recognition
      • People Counting with YOLOv4 and DeepSORT
      • Eye Blinking Detection Alarm
      • Helmet-Detection Using YOLO-V5
      • Mask Detection using YOLOv5
      • Parking Space Management
      • Vehicle, Pedestrian Detection with IR Image
      • Drum Playing Detection
      • Turtle neck measurement program using OpenPose
    • DLIP 2022 Projects
      • BakeryCashier
      • Virtual Mouse
      • Sudoku Program with Hand gesture
      • Exercise Posture Assistance System
      • People Counting Embedded System
      • Turtle neck measurement program using OpenPose
    • DLIP Past Projects
  • Installation Guide
    • Installation Guide for Pytorch
      • Installation Guide 2021
    • Anaconda
    • CUDA cuDNN
      • CUDA 10.2
    • OpenCV
      • OpenCV Install and Setup
        • OpenCV 3.4.13 with VS2019
        • OpenCV3.4.7 VS2017
        • MacOS OpenCV C++ in XCode
      • Python OpenCV
      • MATLAB-OpenCV
    • Framework
      • Keras
      • TensorFlow
        • Cheat Sheet
        • Tutorial
      • PyTorch
    • IDE
      • Visual Studio Community
      • Google Codelab
      • Visual Studio Code
        • Python with VS Code
        • Notebook with VS Code
        • C++ with VS Code
      • Jupyter Notebook
        • Install
        • How to use
    • Ubuntu
      • Ubuntu 18.04 Installation
      • Ubuntu Installation using Docker in Win10
      • Ubuntu Troubleshooting
    • ROS
  • Programming
    • Python_Numpy
      • Python Tutorial - Tips
      • Python Tutorial - For Loop
      • Python Tutorial - List Tuple, Dic, Set
    • Markdown
      • Example: API documentation
    • Github
      • Create account
      • Tutorial: Github basic
      • Tutorial: Github Desktop
    • Keras
      • Tutorial Keras
      • Cheat Sheet
    • PyTorch
      • Cheat Sheet
      • Autograd in PyTorch
      • Simple ConvNet
      • MNIST using LeNet
      • Train ConvNet using CIFAR10
  • Resources
    • Useful Resources
    • Github
Powered by GitBook
On this page
  • Tutorial: YOLO v8 in PyTorch
  • Documentation and Github
  • Installation of Yolov8
  • Requirement
  • 1)Install Yolov8 via pip package
  • 2)Install Yolov8 via pip package(numpy 1.26 ver.)
  • Check for YOLO Installation
  • Using YOLOv8 with Python : Example Codes
  • Example: Detection Inference
  • Example: Train

Was this helpful?

  1. Deep Learning for Perception
  2. Tutorial - PyTorch
  3. Tutorial: YOLO in PyTorch

Tutorial: Yolov8 in PyTorch

PreviousTutorial: YOLO in PyTorchNextTutorial: Train Yolo v8 with custom dataset

Last updated 10 days ago

Was this helpful?

Tutorial: YOLO v8 in PyTorch

https://docs.ultralytics.com/quickstart/#install-ultralytics

is a cutting-edge, state-of-the-art (SOTA) model that builds upon the success of previous YOLO versions and introduces new features and improvements to further boost performance and flexibility. Y

img

Documentation and Github


Installation of Yolov8

Requirement

Install necessary packages such as Python, Numpy, PyTorch, CUDA and more

  • Python >=3.8

  • PyTorch>=1.8

  • opencv-python>=4.6.0

  • matplotlib>=3.3.0

1)Install Yolov8 via pip package

First, create a new environment for YOLOv8 in Anaconda Prompt.

  • e.g. $myENV$ = yolov8

You can also make an exact copy of the existing environment by creating a clone

  • If you already have an environment named py39, clone it as yolov8

conda create --name yolov8 --clone py39

Activate the environment and Install YOLOv8 with pip to get stable packages.

Also, install the latest ONNX

conda activate yolov8
pip install ultralytics
pip install onnx

2)Install Yolov8 via pip package(numpy 1.26 ver.)

If There is an OpenCV DLL issue, follow the setup intructions below to configure your environment

(The DLL issue might be caused by an incompatible Numpy version[your numpy ver. numpy 2.x])

conda create -n yolov8 python=3.9.12
conda activate yolov8

conda install -c anaconda numpy==1.26
pip install opencv-python matplotlib

conda install pytorch=2.1 torchvision torchaudio pytorch-cuda=11.8 -c pytorch -c nvidia

pip install torchsummary
pip install ultralytics
pip install onnx  

Check for YOLO Installation

After the installation, you can check the saved source code and libs of YOLOv8 in the local folder :

\USER\anaconda3\envs\yolov8\Lib\site-packages\ultralytics

Now, lets run simple prediction examples to check the YOLO installation.

In Anaconda Prompt, activate yolov8 environment.

Then, move directory to the working directory. Here, the result images will be saved.

  • Example: C:\Users\ykkim\source\repos\DLIP\yolov8\

conda activate yolov8

cd C:\Users\ykkim\source\repos\DLIP\yolov8

Run a Detection Example

In the Anaconda prompt, type the following command to predict a simple image.

yolo predict model=yolov8n.pt source='https://ultralytics.com/images/bus.jpg'

The result will be saved in the project folder \runs\detect\predict\

Example: C:\Users\ykkim\source\repos\DLIP\yolov8\runs\detect\predict\

Run a Segmentation Example

Predict a YouTube video using a pretrained segmentation model at image size 320:

yolo predict model=yolov8n-seg.pt source='https://youtu.be/LNwODJXcvt4' imgsz=320

The result will be saved in the project folder \runs\segment\predict\


Using YOLOv8 with Python : Example Codes

In the project folder, create a new python code file

  • Project Folder: \source\repos\DLIP\yolov8\

  • Activate yolov8 environment in Anaconda Prompt

A list of useful commands for YOLOv8

from ultralytics import YOLO

# Create a new YOLO model from scratch
model = YOLO('yolov8n.yaml')

# Load a pretrained YOLO model (recommended for training)
model = YOLO('yolov8n.pt')

# Train the model using the 'coco8.yaml' dataset for 3 epochs
results = model.train(data='coco8.yaml', epochs=3)

# Evaluate the model's performance on the validation set
results = model.val()

# Perform object detection on an image using the model
results = model('https://ultralytics.com/images/bus.jpg')

Example: Detection Inference

Download the dataset file and save in the project folder

You can download the COCO pretrained models such as YOLOv8n and more.

Inference one image

Create a new python source file in the project folder

  • Yolo8-Inference-Ex1.py

#########################################################
# YOLO v8  Tutorial : Prediction  Ex1
#
# Load Pretrained Model and Display the Annoted Results
#
#########################################################

from ultralytics import YOLO
import cv2
from matplotlib import pyplot as plt



# Load a pretrained YOLO model (recommended for training)
model = YOLO('yolov8n.pt')

# Inference Source - a single source
src = cv2.imread("bus.jpg")


# Perform object detection on an image using the model
result = model.predict(source=src, save=True, save_txt=True)  # save predictions as labels


# View result   
for r in result:

    # print the Boxes object containing the detection bounding boxes        
    print(r.boxes)  
    
    # Show results to screen (not recommended)
    print("result.show()")
    r.show()    

   
    # Plot results image    
    print("result.plot()") 
    dst = r.plot()      # return BGR-order numpy array
    cv2.imshow("result plot",dst)         
    

    # Plot the original image (NParray)
    print("result.orig_img")
    cv2.imshow("result orig",r.orig_img)   


# Save results to disk
r.save(filename='result.jpg')
cv2.waitKey(0)



##########################################################################################


Inference of multiple images

Create a new python source file in the project folder

  • Yolo8-Inference-Ex2.py

For multiple input source images, you can copy bus.jpg as bus2.jpg.

#########################################################
# YOLO v8  Tutorial : Prediction  Ex2
#
# Load Pretrained Model and Display the Annoted Results (multiple images)
#
#########################################################


from ultralytics import YOLO
import cv2
from matplotlib import pyplot as plt


# Load a pretrained YOLO model (recommended for training)
model = YOLO('yolov8n.pt')


# Inference Source - multiple images
# Perform object detection on images using the model
results = model(['bus.jpg', 'bus2.jpg'])  # return a list of Results objects


# View results
for i, r in enumerate(results):

    # Plot results image    
    dst = r.plot()      # return BGR-order numpy array
    cv2.imshow("r.plot",dst)       
   

    # Save results to disk
    r.save(filename=f'results{i}.jpg')
    
cv2.waitKey(0)

Inference on Webcam stream

Create a new python source file in the project folder

  • Yolo8-Inference-Webcam-Ex3.py

#########################################################
# YOLO v8  Tutorial : Prediction  Ex3
#
# Stream Video Prediction 
#
# This script will run predictions on each frame of the video
# visualize the results, and display them in a window. 
# The loop can be exited by pressing 'q'.
#########################################################


import cv2 as cv
from ultralytics import YOLO

# Load the YOLOv8 model
model = YOLO('yolov8n.pt')

# Open the video camera no.0
cap = cv.VideoCapture(0)

# If not success, exit the program
if not cap.isOpened():
    print('Cannot open camera')


# Loop through the video frames
while cap.isOpened():
    # Read a frame from the video
    success, frame = cap.read()

    if success:
        # Run YOLOv8 inference on the frame
        results = model(frame)

        # Visualize the results on the frame
        annotated_frame = results[0].plot()

        # Display the annotated frame
        cv.imshow("YOLOv8 Inference", annotated_frame)

        # Break the loop if 'q' is pressed
        if cv.waitKey(1) & 0xFF == ord("q"):
            break
    else:
        # Break the loop if the end of the video is reached
        break

# Release the video capture object and close the display window
cap.release()
cv.destroyAllWindows()

Example: Train

See the for full documentation on training, validation, prediction and deployment.

Also, you can visit the github repository:

Ultralytics provides various installation methods including pip, conda, and Docker. Install YOLOv8 via the ultralytics pip package for the latest stable release or by cloning the for the most up-to-date version.

For installations of requirements,

and more.

Read

YOLOv8 Docs
https://github.com/ultralytics/ultralytics
Ultralytics GitHub repository
read for more detail instructions
See requirements
Doc of Prediction with YOLO for more examples
bus.jpg
https://docs.ultralytics.com/datasets/detect/coco/
Ultralytics
YOLOv8