2개 비디오 한 화면으로 좌우 병합하기, 합치기
import cv2
import numpy as np
from pathlib import Path
# ────────────────────────────────────────
# ① 입력·출력 파일 경로 설정
# ────────────────────────────────────────
left_path = Path(r"observation.images.side\episode_000000.mp4")
right_path = Path(r"observation.images.top\episode_000000.mp4")
output_path = Path(r"episode_000000_side_by_side.mp4")
# ────────────────────────────────────────
# ② 비디오 캡처 열기
# ────────────────────────────────────────
cap_left = cv2.VideoCapture(str(left_path))
cap_right = cv2.VideoCapture(str(right_path))
if not (cap_left.isOpened() and cap_right.isOpened()):
raise RuntimeError("두 비디오 중 하나를 열 수 없습니다.")
# ────────────────────────────────────────
# ③ 해상도·FPS 획득 & 출력용 VideoWriter 설정
# ────────────────────────────────────────
fps = int(min(cap_left.get(cv2.CAP_PROP_FPS),
cap_right.get(cv2.CAP_PROP_FPS))) # 서로 다르면 더 낮은 FPS 사용
width_l = int(cap_left.get(cv2.CAP_PROP_FRAME_WIDTH))
height_l = int(cap_left.get(cv2.CAP_PROP_FRAME_HEIGHT))
width_r = int(cap_right.get(cv2.CAP_PROP_FRAME_WIDTH))
height_r = int(cap_right.get(cv2.CAP_PROP_FRAME_HEIGHT))
# 필요하면 사이즈 맞추기 (예: 오른쪽 해상도를 왼쪽과 동일하게 리사이즈)
target_h = max(height_l, height_r) # 두 영상 중 큰 쪽에 맞춥니다
target_w_l = int(width_l * target_h / height_l)
target_w_r = int(width_r * target_h / height_r)
fourcc = cv2.VideoWriter_fourcc(*"mp4v") # .mp4용 코덱
out_width = target_w_l + target_w_r
out_height = target_h
writer = cv2.VideoWriter(str(output_path), fourcc, fps, (out_width, out_height))
# ────────────────────────────────────────
# ④ 프레임 단위로 읽어 붙이기
# ────────────────────────────────────────
while True:
ret_l, frame_l = cap_left.read()
ret_r, frame_r = cap_right.read()
if not (ret_l and ret_r):
break
# 해상도가 다르면 리사이즈
if frame_l.shape[:2] != (target_h, target_w_l):
frame_l = cv2.resize(frame_l, (target_w_l, target_h))
if frame_r.shape[:2] != (target_h, target_w_r):
frame_r = cv2.resize(frame_r, (target_w_r, target_h))
# 좌우 연결 (hstack 또는 cv2.hconcat)
combined = np.hstack((frame_l, frame_r))
writer.write(combined)
# ────────────────────────────────────────
# ⑤ 자원 정리
# ────────────────────────────────────────
cap_left.release()
cap_right.release()
writer.release()
print(f"✅ 병합 완료 → {output_path}")