영상(.mp4)을 이미지(.jpg)로 쪼개어 저장할 수 있다.
python 3.8.16
opencv-python 4.7.0.72
import os
import cv2
import shutil
from tqdm import tqdm
from absl import app, flags
from absl.flags import FLAGS
flags.DEFINE_string("dir", None, "Video Path")
def get_frame_from_video(_argv):
#Open video file
video = cv2.VideoCapture(FLAGS.dir)
if not video.isOpened():
assert False, "Video load error"
len_video = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
fps = int(video.get(cv2.CAP_PROP_FPS))
#Create directory for saving
images_save_folder = os.path.splitext(FLAGS.dir)[0]
if os.path.exists(images_save_folder):
shutil.rmtree(images_save_folder)
os.makedirs(images_save_folder)
#Save video frame
count = 0; success = True
with tqdm(total = len_video + 1) as pbar:
while success:
success, image = video.read()
frame_idx = int(video.get(1))
if frame_idx % fps == 0: # video 1 sec -> save 1 image
save_idx = str(count + 1).zfill(5)
save_image_path = os.path.join(images_save_folder, f"frame_{save_idx}.jpg")
cv2.imwrite(save_image_path, image)
count += 1
pbar.update(1)
video.release()
if __name__ == "__main__":
app.run(get_frame_from_video)
print("Success!")
python {python file path} -dir {video_path}
(예시)
python .\save_video_to_frames.py -dir .\sample.mp4