import time
import cv2
from ultralytics import YOLO
from google.colab.patches import cv2_imshow
# YOLOv8 모델 로드
model = YOLO('/content/best.pt') # 경로 넣기
# 영상 파일 경로
video_path = '/content/predictions_video.mp4'
output_path = '%s_output_2.mp4' % video_path.split('.')[0]
# 영상 파일 열기
cap = cv2.VideoCapture(video_path)
# 원본 영상의 프레임 속도 가져오기
fps = cap.get(cv2.CAP_PROP_FPS)
frame_time = 5.0 / fps # 초 단위로 변환
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
# VideoWriter 객체 생성
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
while cap.isOpened():
start_time = time.time()
ret, frame = cap.read()
if not ret:
break
# 객체 감지
results = model(frame)
# 감지 결과 그리기
for result in results:
annotated_frame = result.plot()
# 결과 프레임을 파일에 저장
out.write(annotated_frame)
# 결과 표시
cv2_imshow(annotated_frame)
# 프레임 간 실제 지연 시간 계산
elapsed_time = time.time() - start_time
delay = max(int((frame_time - elapsed_time) * 1000), 1)
if cv2.waitKey(delay) & 0xFF == ord('q'):
break
cap.release()
out.release()
cv2.destroyAllWindows()
