python

python cv2로 동영상 프레임별로 나누기, 클립 따기

orangecode 2023. 5. 3. 23:37
728x90

python 코드와 opencv 라이브러리를 이용해서 동영상을 프레임 별로 나누거나, 1개의 동영상에서 여러개의 영상을 저장해주는 방법을 알려드리려 해요

 

1개의 동영상을 분할해서 내가 원하는 시작점에서 끝점까지 재생한 뒤, 저장할 수 있는 코드입니다.

 

 

1. 라이브러리 불러오기

import cv2
import os

먼저 기본 라이브러리인 opencv를 import cv2로 불러옵니다.

 

추가적으로 input 파일을 불러오기 위한 os 라이브러리도 불러와줍니다.

 

 

2. input / output, 동영상 파일 경로 설정하기

# Path to the folder containing videos
folder_path = 'C:/Users/kwonk/Downloads/video/input/video.mp4'
out_path = 'C:/Users/kwonk/Downloads/video/output'

나누어줘야할 raw video 파일의folder_path를 설정합니다.

 

영상을 분할해서 딴 클립을 저장할 out_path도 설정합니다. 

 

 

3. 비디오 파일 오픈 + 영상 구간 확인

# 비디오 파일 오픈
cap = cv2.VideoCapture(folder_path)

# frame 구하기 = 현재 비디오 재생 위치 확인
frame_count=0

cv2.VideoCapture(path)함수로 비디오 파일 경로를 입력해주면 비디오 파일을 읽어와 cap 변수에 담아준다.

 

frame = 0 을 설정해서 cap을 읽어올 때 frame마다 1씩 증가시켜서 현재 비디오 재생 위치를 파악할 수 있다.

 

 

4. video를 frame 별로 읽어오기

# Loop over the video frames
while cap.isOpened():
    # Read the next frame
    ret, frame = cap.read()
    frame_count += 1

cap.read() 함수로 frame을 읽어오고, frame_count += 1을 이용하여 프레임이 1씩 지나갈 때마다 1씩 추가하여 현재 프레임의 위치를 알 수 있다.

 

 

5. space bar를 누르면 영상 저장 시작

# 스페이스바를 눌러 영상 저장 시작
if ret:
    cv2.imshow('frame', frame)
    key = cv2.waitKey(25)
    if key == 32:  # space bar
        # Create a video writer object to save the clip
        fourcc = cv2.VideoWriter_fourcc(*'mp4v')
        out = cv2.VideoWriter(f'{out_path}/clip_{frame_count}.mp4', fourcc, 30, (frame.shape[1], frame.shape[0]))

성공적으로 frame을 읽어왔을 때, imshow()를 이용하여 frame을 화면에 띄우고 영상 시작 점을 찾아준다.

 

다음으로 space bar를 누르면 영상 저장을 시작한다.

 

 

6. enter키를 누르면 영상 녹화 끝 + 클립 저장 완료

# Save the frames until we reach the end of the clip or the user presses the enter key
while cap.isOpened():
    ret, frame = cap.read()
    if key == 13:  # enter key
        break
    if ret:
        out.write(frame)
        cv2.imshow('frame', frame)
        key = cv2.waitKey(25)

# Release the video writer and close the window
out.release()
cv2.destroyAllWindows()

다음으로 클립을 마무리할 수 있도록 enter를 입력하면 영상 저장이 완료되면서 클립이 자동으로 저장되게 된다.

 

 

전체 코드

# 비디오 파일 오픈
cap = cv2.VideoCapture(folder_path)

# frame 구하기
frame_count=0

# Loop over the video frames
while cap.isOpened():
    # Read the next frame
    ret, frame = cap.read()
    frame_count += 1

    # If the frame was read successfully, display it and wait for the space bar to start saving the video
    if ret:
        cv2.imshow('frame', frame)
        key = cv2.waitKey(25)
        if key == 32:  # space bar
            # Create a video writer object to save the clip
            fourcc = cv2.VideoWriter_fourcc(*'mp4v')
            out = cv2.VideoWriter(f'{out_path}/clip_{frame_count}.mp4', fourcc, 30, (frame.shape[1], frame.shape[0]))

            # Save the frames until we reach the end of the clip or the user presses the enter key
            while cap.isOpened():
                ret, frame = cap.read()
                if key == 13:  # enter key
                    break
                if ret:
                    out.write(frame)
                    cv2.imshow('frame', frame)
                    key = cv2.waitKey(25)

            # Release the video writer and close the window
            out.release()
            cv2.destroyAllWindows()
     cap.release()
반응형