from ultralytics import YOLO
import os
import cv2
import numpy as np
def get_file_extension(filename):
_, extension = os.path.splitext(filename)
return extension.lstrip('.')
def process_video(video_path, model, test_db_path, output_video_path):
test_res_path = os.path.join(test_db_path, "predictions")
if not os.path.exists(test_res_path):
os.makedirs(test_res_path)
# 영상 파일 확인
if not os.path.isfile(video_path):
print(f"Error: Video file {video_path} does not exist.")
return
# 영상 파일 열기
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
print(f"Error: Could not open video {video_path}")
return
# 영상 속성 가져오기
fps = int(cap.get(cv2.CAP_PROP_FPS))
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
# 출력 영상 설정
fourcc = cv2.VideoWriter_fourcc(*'mp4v') # MP4 코덱
out = cv2.VideoWriter(output_video_path, fourcc, fps, (width, height))
if not out.isOpened():
print(f"Error: Could not create output video {output_video_path}")
cap.release()
return
# 영상 파일 이름에서 확장자 제거
video_basename = os.path.basename(video_path)
video_name = os.path.splitext(video_basename)[0]
# 프레임별 결과 저장 디렉토리 생성
video_pred_path = os.path.join(test_res_path, video_name)
if not os.path.exists(video_pred_path):
os.makedirs(video_pred_path)
frame_idx = 0
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
# YOLO 예측 수행
result = model.predict(frame, imgsz=1280, conf=0.001, iou=0.6)[0]
# 탐지 결과 시각화 (바운딩 박스와 라벨 포함)
annotated_frame = result.plot() # YOLO의 plot()으로 바운딩 박스 그리기
# 출력 영상에 프레임 쓰기
out.write(annotated_frame)
# 텍스트 파일 이름 생성
txt_filename = os.path.join(video_pred_path, f"{frame_idx:06d}.txt")
boxes = result.boxes
num_obj = len(boxes.cls)
# 탐지 결과 저장 (텍스트 출력)
with open(txt_filename, 'w') as f1:
for obj_idx in range(num_obj):
cls_id = int(boxes.cls[obj_idx])
cs = boxes.conf[obj_idx]
xywhn = boxes.xywhn[obj_idx]
# class_id norm_center_x norm_center_y norm_w norm_h confidence_score
f1.write("%d %lf %lf %lf %lf %lf/n" % (cls_id, xywhn[0], xywhn[1], xywhn[2], xywhn[3], cs))
# 객체가 없는 프레임 로그 출력
if num_obj == 0:
print(f"No objects detected in {txt_filename}")
frame_idx += 1
# 리소스 해제
cap.release()
out.release()
print(f"Processed video: {video_path}")
print(f"Output video saved: {output_video_path}")
if __name__ == "__main__":
# 직접 지정한 경로
video_path = "C:/YOLOv8_light/ultralytics/autodrive.mp4" # 입력 동영상 경로
output_video_path = "C:/YOLOv8_light/ultralytics/carla_output_second.mp4" # 출력 동영상 경로
test_db_path = "./tests/carla_frame"
# YOLO 모델 로드
model_filename = "C:/YOLOv8_light/ultralytics/runs/detect/tld_yolov10_x_sgd3/weights/best.pt"
model = YOLO(model_filename)
# 영상 처리
process_video(video_path, model, test_db_path, output_video_path)
cv2.destroyAllWindows()