Tutorial: Yolov5 in Pytorch (VS code)

A simple tutorial for YOLOv5 Testing in Local PC

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

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

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

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

Part 1. YOLOv5 Installation

YOLOv5 github(https://github.com/ultralytics/yolov5)에 접속하여 아래와 같이 Repository를 다운로드합니다.

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

/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

See Tutorial: Yolov5 with custom dataset

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

Run YOLOv5 Inference in Local PC with PyTorch Hub

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

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

  • 사전에 VS code 설치 및 사용법 숙지를 선행하시기 바랍니다.

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를 눌러 빌드하여 아래와 같이 결과창이 뜨는 것을 확인합니다

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

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

Last updated