Image Processing/Cv2

python opencv 를 이용해서 동영상에서 이미지 추출 (이미지에서 동영상)

jinmc 2021. 12. 13. 13:14
반응형

먼저 opencv를 설치합니다.

>>> pip install opencv-python #For python 2.x
>>> pip3 install opencv-python #For python 3.x
>>> conda install opencv-python #If you directly install in anaconda with all dependencies.

다음은 비디오에서 이미지를 추출하는 방법입니다.

레퍼런스에서는 없었지만 디렉토리 안에서 모든 파일들의 이미지들을 비디오에서 추출할 수 있게 만들었습니다.

import cv2
import os

pwd = os.getcwd()
print(pwd)
print(os.listdir(pwd))

files = os.listdir(pwd)

def getFrame(sec, f):
    vidcap = cv2.VideoCapture(f)
    vidcap.set(cv2.CAP_PROP_POS_MSEC,sec*1000)
    hasFrames,image = vidcap.read()
    file_name = f.replace(".mp4", "")
    if hasFrames:
        cv2.imwrite("images/" + file_name + str(count)+".jpg", image)     # save frame as JPG file
    return hasFrames


for f in files:
    if "mp4" not in f:
        print("not video file!")
        continue
    sec = 0
    frameRate = 0.5
    count = 1
    success = getFrame(sec, f)
    while success:
        count = count + 1
        sec = sec + frameRate
        sec = round(sec, 2)
        success = getFrame(sec, f)

 

 

다음은 이미지에서 동영상을 만드는 법입니다.

import cv2
import numpy as np
import os
from os.path import isfile, join
pathIn= './images/testing/'
pathOut = 'video.avi'
fps = 0.5
frame_array = []
files = [f for f in os.listdir(pathIn) if isfile(join(pathIn, f))]
#for sorting the file names properly
files.sort(key = lambda x: x[5:-4])
files.sort()
frame_array = []
files = [f for f in os.listdir(pathIn) if isfile(join(pathIn, f))]
#for sorting the file names properly
files.sort(key = lambda x: x[5:-4])
for i in range(len(files)):
    filename=pathIn + files[i]
    #reading each files
    img = cv2.imread(filename)
    height, width, layers = img.shape
    size = (width,height)
    
    #inserting the frames into an image array
    frame_array.append(img)
out = cv2.VideoWriter(pathOut,cv2.VideoWriter_fourcc(*'DIVX'), fps, size)
for i in range(len(frame_array)):
    # writing to a image array
    out.write(frame_array[i])
out.release()

 

reference : https://medium.com/@iKhushPatel/convert-video-to-images-images-to-video-using-opencv-python-db27a128a481

반응형