컴퓨터/리눅스 (LINUX)

ffmpeg 사용, image to video, video to image 만들기

Honbul 2022. 8. 25. 15:31

영상 관련 딥러닝 처리를 하기 위해서는

이미지 형태의 데이터를 준비해야 한다.

즉, 비디오를 이미지로 (frame) 잘라내야 한다.

 

이때, ffmpeg 패키지를 사용할 수 있다.

 

참고글

Stitching images to video using ffmpeg - SoByte

 

Stitching images to video using ffmpeg

This article describes how to use ffmpeg to stitch a large number of images into a video, and introduces the meaning of some of the parameters. Before using ffmpeg to stitch images into a video, you need to pre-process the image file name, the file name mu

www.sobyte.net

 

How to use FFmpeg to convert images to video — Shotstack

 

How to use FFmpeg to convert images to video

Convert multiple images into a video slideshow containing audio and transition effects using FFmpeg.

shotstack.io

 

Extracting frames from GIF : ffmpeg (reddit.com)

 

Extracting frames from GIF

I'm trying to extract the frames from [this GIF](https://cdn.betterttv.net/emote/55b6f480e66682f576dd94f5/3x) as PNG images with this command ...

www.reddit.com

 

참고글을 보면 복잡한 영상관련 파라미터들이 있다.

여기서는 파라미터들을 길게 설명하기 보다는

특정 용도로 사용한 코드들을 정리하겠다.

 

1. Video to Image

 

ffmpeg -i video.mp4 -s 577x479 %04d.png

 

같은 경로에 있는 video.mp4 파일을 앞에 네 자리 숫자.png (예시, 1234.png, 0001.png)로 저장하는 코드

 

2. Image to Video

 

#예시 1
ffmpeg -framerate 30 -i results/video/output_%04d.png -preset slow -qp 18 -pix_fmt yuv420p result_video.mp4

#예시 2
ffmpeg -framerate 30 -i image_sr2/v1885/V1885_p2_SSL_%05d-2275000_E.png -c:v libx264 -crf 18 -preset veryslow sr_vids2/v1885.mp4

 

results/video 경로에 있는 output_xxxx.png 파일들을 합쳐 result_video.mp4 파일로 저장하는 코드이다.

-framerate 30 이므로, fps가 30인 영상이 만들어진다. 나머지 파라미터들은 참고글을 본다.

 

3. Gif to Image

 

ffmpeg -i test.gif -vsync 0 result_%d.png

 

test.gif 파일을 result_x.png 파일로 쪼개는 코드

gif는 일반 영상과 다르기 때문에 파라미터가 추가된다.

 

4. 영상에서 소리 추출 및 합치기

ffmpeg를 사용해서 frame들로 쪼개는 과정에서 소리는 당연히 사라진다.

최종 파일에 소리를 입히기 위해서는 미리 영상으로부터 소리를 분리한 후

영상 처리가 끝난 파일에 다시 합쳐준다.

 

ffmpeg -i 'sample_video.mp4' -f mp3 -ab 192000 -vn 'sampe_audio.mp3'

 

sample_video.mp4 파일로부터 소리를 추출하여 sample_audio.mp3 파일로 저장하는 코드

 

import ffmpeg

input_video = ffmpeg.input('video_only.mp4')
input_audio = ffmpeg.input('audio_only.mp3')

ffmpeg.concat(input_video, input_audio, v=1, a=1).output('video_with_sound.mp4').run()

 

bash에서 처리하는 방법이 있을텐데, 필자는 python에서 했는 탓에 python 코드를 기록한다.

video와 audio를 불러온 다음 concatenate 해주는 코드

 

5. bash에서 비디오 해상도 확인

 

ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of csv=s=x:p=0 video.mp4

 

끝!