머신러닝/영상인식

YOLO 기초, 영상 인식, 영상에서 사물인식하기 yolo11x, yolo11n

Olivia-BlackCherry 2025. 3. 8. 11:33

YOLO 기초, 영상 인식, 영상에서 사물인식하기 yolo11x, yolo11n

 

1. requirements.txt

pip install -r requirements.txt

 

2. 모듈 만들기

utils 폴더를 보면 init파일이 있다. 

video_utils.py에 이 모듈의 메서드가 있다.

 

main()함수가 잘 작동되는지 테스트 해보자.

import cv2
from ultralytics import YOLO
from utils import (read_video)

def main():
    print("hello")

if __name__ == "__main__":
    main()

 

 

3. save video

video_utils.py

import cv2

def read_video(video_path):
    cap = cv2.VideoCapture(video_path)
    frames = []
    while True:
        ret, frame = cap.read()
        if ret:
            frames.append(frame)
        else:
            break
    cap.release()
    return frames

def save_video(output_video_frames, output_video_path):
    #코덱 및 비디오 파일 생성
    #VideoWrtier : 이미지 프레임을 하나씩 받아서 동영상 파일로 인코딩하고 저장하는 역할
    fourcc = cv2.VideoWriter_fourcc(*'MJPG')
    height, width = output_video_frames[0].shape[:2]
    out = cv2.VideoWriter(output_video_path, fourcc, 24,(width, height))
    for frame in output_video_frames:
        out.write(frame)
    out.release()

 

main.py

import cv2
from ultralytics import YOLO
from utils import (read_video, save_video)

def main():
    print("hello")
    input_video_path = "input_videos/input_video.mp4"
    video_frames = read_video(input_video_path)
    #Save the output video
    save_video(video_frames, "output_videos/output.avi")

if __name__ == "__main__":
    main()

folder만들기

확인은 실제 폴더에서

 

 

4. yolo 모델

yolo11n은 가볍지만 속도가 빠름, 정확도는 낮음

yolo11x는 무겁지만 속도가 낮음, 정확도는 높음. 

실시간 검출이나 속도가 우선된다면 경량모델을 사용하는 것이 좋음

 

 

5. yolo11x.pt YOLO 이용하여 detection

conf = confidence신뢰도, 해당 신뢰도 이상인 것들만 검출

save=True 결과를 파일로 저장

show=True 화면에 결과 표시

from ultralytics import YOLO
#Load the Model
model = YOLO("yolo11x.pt")
results = model.predict("input_videos/input_video.mp4", conf=0.2, save=True, show=True)

 

 

내가 디텍트하고 싶은 것은? 움직이는 플레이어와 움직이는 볼 총 3가지이다. 

이런 경우 어떤 것을 손 볼 것인가?

 

6. yolo11n.pt

persist=True 모델이 이전 예측 결과를 유지하도록 설정하는 옵션

여러 개의 비디오 또는 이미지에 대해 연속적으로 예측할 때 속도를 향상시키는 역할을 함

pip install lap
from ultralytics import YOLO
#Load the Model
model = YOLO("yolo11n.pt")
# results = model.predict("input_videos/input_video.mp4", conf=0.2, save=True, show=True)
results = model.track("input_videos/input_video.mp4", conf=0.2, save=True, persist=True)

id가 저장되어 있다는 점이 특별하다. 

input_video.avi
11.34MB

 

 

하지만 아직까지 볼을 detect하지 못했기 때문에 다음 시간에는 Yolo모델을 튜닝하여 문제를 해결해보도록 하자.

 

YOLO 기초, 영상 인식, 영상에서 사물인식하기 yolo11x, yolo11n