영상에서 프레임 추출하기

J. Hwang·2025년 1월 6일

영상 파일(mpeg 등)에서 프레임을 추출해서 PIL image 파일로 저장하는 코드

import cv2
from PIL import Image

# 영상에서 프레임을 추출하여 PIL.Image 형식으로 변환하는 함수
def extract_frames_to_pil(video_path):
    frames = []  # PIL.Image 형식의 프레임들을 저장할 리스트
    cap = cv2.VideoCapture(video_path)  # OpenCV로 비디오 파일 열기

    if not cap.isOpened():
        print("Error: Unable to open video file.")
        return frames

    while True:
        ret, frame = cap.read()  # 프레임 읽기
        if not ret:
            break  # 더 이상 프레임이 없으면 종료

        # OpenCV의 프레임은 BGR 형식이므로 RGB로 변환
        frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

        # PIL.Image 형식으로 변환
        pil_image = Image.fromarray(frame_rgb)
        frames.append(pil_image)

    cap.release()  # 비디오 객체 해제
    return frames

# 사용 예제
video_path = "example_video.mp4"  # 처리할 영상 경로
pil_frames = extract_frames_to_pil(video_path)
print(f"Extracted {len(pil_frames)} frames from the video.")

출처 : ChatGPT

profile
Let it code

0개의 댓글