YOLO v8 설치
사전 설치
- Conda 가상환경 등의 python 환경에서 진행
패키지 설치
pip install ultralytics
pip install opencv-python
YOLO v8 샘플 코드
sample_code.py
# author: msk
import cv2
import argparse
from ultralytics import YOLO
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description='Yolo v8 Test'
)
parser.add_argument('flag', help= 'video file path', nargs= '?', const= 1, default= 'None')
args = parser.parse_args()
flag = args.flag
if flag == 'None':
# webcam 사용시
cap = cv2.VideoCapture(0)
else:
# 동영상 불러오기
video_path = flag
cap = cv2.VideoCapture(video_path)
# Load the YOLOv8
model = YOLO('yolov8n.pt')
msec = 1
stop_trigger = False
# for Save
fcc = cv2.VideoWriter_fourcc(*'MP4V')
out = cv2.VideoWriter('result.mp4', fcc, 30, (1280, 720))
# Loop through the video frames
while cap.isOpened():
# Read a frame from the video
success, frame = cap.read()
if success:
# 매 프레임 inference
results = model(frame)
# Visualization
annotated_frame = results[0].plot()
# For print on terminal
print("[Class with bbox-points(x, y)]")
for r in results:
boxes = r.boxes.xyxy
cls = r.boxes.cls
conf = r.boxes.conf
cls_dict = r.names
for box, cls_number, conf in zip(boxes, cls, conf):
conf_number = float(conf.item())
cls_number_int = int(cls_number.item())
cls_name = cls_dict[cls_number_int]
x1, y1, x2, y2 = box
x1_int = int(x1.item())
y1_int = int(y1.item())
x2_int = int(x2.item())
y2_int = int(y2.item())
print("{0} - pt1:({1}, {2}), pt2:({3}, {4})" .format(cls_name, x1_int, y1_int, x2_int, y2_int))
# Display
out.write(annotated_frame)
cv2.imshow("YOLOv8 Inference", annotated_frame)
key = cv2.waitKey(msec) & 0xFF
# input esc
if key == 27:
break
# input spacebar
elif key == 32 and stop_trigger == False:
msec = 0
stop_trigger = True
elif key == 32 and stop_trigger == True:
msec = 1
stop_trigger = False
else:
break
cap.release()
out.release()
cv2.destroyAllWindows()
실행
샘플 코드 실행
아래 명령 프롬포트를 통해 실행
# 웹캠 모드
(yolov8) python sample_code.py
# 동영상 모드
(yolov8) python sample_code.py sample_video.mp4