📚
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
  • A simple tutorial for YOLOv5 Testing in Local PC
  • Part 1. YOLOv5 Installation
  • Part 2. Run YOLOv5 in Local PC with CLI
  • 1. Inference
  • 2. Train (Opendataset COCO)
  • 3. Train with custom dataset
  • Run YOLOv5 Inference in Local PC with PyTorch Hub
  • Procedure

Was this helpful?

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

Tutorial: Yolov5 in Pytorch (VS code)

PreviousTutorial: Train Yolo v5 with custom datasetNextTutorial: Yolov3 in Keras

Last updated 11 months ago

Was this helpful?

A simple tutorial for YOLOv5 Testing in Local PC

본 튜토리얼에서는 local PC에 설치한 py39환경으로 YOLO v5를 실행하는 두가지 방법의 간단한 예제를 제공합니다.

  1. 명령창을 활용해 구동하는 방법

  2. VS code와 같은 IDE로 torch hub를 활용하여 구동하는 방법

반드시 을 먼저 완료한 후 실행하십시오. 설치 라이브러리 버전이 모두 맞아야 합니다.

Part 1. YOLOv5 Installation

YOLOv5 github()에 접속하여 아래와 같이 Repository를 다운로드합니다.

image

압축해제 후 폴더명을 yolov5-master → yolov5로 변경 후 원하는 위치에 붙여넣습니다.

/yolov5 폴더에 진입 후 아래 그림과 같이 경로 주소를 복사(ctrl+C)합니다.

Anaconda prompt를 관리자모드로 실행 후 아래 코드 순차적으로 실행합니다 (아래 그림 참조)

conda activate py39
cd $YOLOv5PATH$ // [ctrl+V] 하여 복사한 yolov5 경로 붙여넣기 (그림 참조)
pip install -r requirements.txt

이후 설치가 완료됩니다. 아래와 같이 경고가 뜨지만 무시해도 됩니다.

Part 2. Run YOLOv5 in Local PC with CLI

명령창(command line, CLI)로 YOLO v5 실행시 detect.py, val.py, train.py와 같이 git에서 제공된 파일을 빌드합니다.

  • 따라서 CLI로 빌드시, 반드시 git을 local PC에 저장하고 폴더 경로에 진입하는 과정이 선행되어야 합니다.

  • 즉, 위의 Part 1을 수행해서 Yolov5 repository를 local PC에 저장하면 됩니다.

1. Inference

yolov5 폴더 경로에 진입한 상태에서 아래 코드 입력하여 detect.py를 실행합니다.

python detect.py --weights yolov5n.pt --img 640 --conf 0.25 --source data/images

결과창. 아래와 같이 객체검출 저장된 폴더가 상대경로로 표시됩니다.

실제로 해당 상대경로로 진입하면 결과를 확인할 수 있습니다.

2. Train (Opendataset COCO)

COCO128 학습 오픈데이터셋으로 YOLOv5 학습하는 튜토리얼입니다.

yolov5 폴더 경로가 유지된 상태에서 아래 코드 입력하여 train.py를 실행합니다.

python train.py --img 640 --batch 1 --epochs 1 --data coco128.yaml --weights yolov5n.pt

coco128.yml 파일에서 지정된 바와 같이 workspace의 상위 폴더 \dataset 에 coco 데이터셋 (이미지 및 라벨)이 자동으로 다운로드가 됩니다.

데이터셋 자동 다운로드 후 학습을 진행하며 아래와 같이 결과창이 보여집니다.

그리고 학습결과가 저장된 폴더가 상대경로로 표시됩니다.

실제로 해 상대경로로 진입하면 결과를 확인할 수 있습니다.

3. Train with custom dataset

-----------------------------------------------------------------------------------------------------

Run YOLOv5 Inference in Local PC with PyTorch Hub

  • VS code와 같은 IDE에서도 YOLO v5 결과에 접근하여 프로그래밍할 수 있습니다.

  • 필요한 모듈(requirements)만 설치하면, git을 local PC에 저장하는 선행과정이 필요하지 않습니다.

Procedure

임의의 workspace(작업) 폴더를 생성 후 우클릭 → Code로 열기를 클릭합니다.

혹은 VS Code 실행 후 작업 폴더를 열어도 됩니다.

파이썬 파일 YOLOv5_run_test.py 을 생성하들고 아래의 코드를 붙여 넣습니다.

import torch
import cv2
import random
from PIL import Image

# Load the Model
model = torch.hub.load('ultralytics/yolov5', 'yolov5n', pretrained=True)

# Image preparation from URL . images link
img_URL = [           
           "https://user-images.githubusercontent.com/23421059/168719874-be48ef28-954c-4a4c-a048-1e11699e0b56.png",
           ]

imgs = []
img_L = len(img_URL)

# Append these 3 images and save 
for i in range(img_L):
  imgName = f"{i}.jpg"
  torch.hub.download_url_to_file(img_URL[i],imgName)  # download 2 images
  # imgs.append(Image.open(fileName))  # PIL image
  imgs.append(cv2.imread(imgName)[:,:,::-1]) # OpenCV image (BGR to RGB)

# Run Inference
results = model(imgs)

# Print Results
results.print()

# Save Result images with bounding box drawn
results.save()  # or .show()

# Select a random test image
randNo = random.choice(range(img_L))
print(f"Selected Image No = {randNo}\n\n")

# Print the Bounding Box result:  6 columns
# Column (1~4) Coordinates of TL, BR corners (5) Confidence (6) Class ID
print(results.xyxy[randNo],'\n')  # imgs predictions (tensor)

# Print the Bounding Box result using Pandas
print(results.pandas().xyxy[randNo],'\n')  # imgs predictions (pandas)

# Show result image
cv2.imshow("result", (results.imgs[randNo])[:,:,::-1])
cv2.waitKey(0)

아래 그림과 같이 위 코드가 새 python 파일에 작성되었습니다.

F1키를 눌러 select interpreter를 검색 후 클릭 → py39를 선택합니다.

DLIP 2022 에서는 py39 사용

F1키를 눌러 select default profile을 검색 후 클릭 → command prompt를 선택합니다.

F5 또는 ctrl+F5를 눌러 빌드하여 아래와 같이 결과창이 뜨는 것을 확인합니다

아래와 같이 학습결과가 저장된 폴더가 상대경로로 표시됩니다.

실제로 해당 상대경로로 진입하면 결과를 확인할 수 있습니다.

image
image
image
image
image
image
image

See

사전에 를 선행하시기 바랍니다.

image
image
image
image
image
image
Tutorial: Yolov5 with custom dataset
VS code 설치 및 사용법 숙지
⚠️
Installation Guide for DLIP
https://github.com/ultralytics/yolov5