Python video or motion picture gif save as a picture frame by frame

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/lianggyu/article/details/98744359

       Opencv herein is based on the video and saved as a dynamic image frame gif FIG. According to the different formats of the input video, modify line 21.

       FIG processing differs from moving video, PIL library contains basic support for the image sequence. When opening gif image, automatically loads the first frame. When the image reading is completed, throws EOFError exception. We can use seek () and tell () function reads the image frame is completed.

       This front portion of the code is to read the file. Dataset file structure is as follows:

|——datasets
     |——action1
           action1_1.gif
           action1_2.gif
           ......
     |——action2
           action2_1.gif
           action2_2.gif
           ......
import cv2
import os
from PIL import Image

video_path = 'PATH_ROOT/datasets/' #视频或gif图像的路径
save_path = 'PATH_ROOT/save/'   #保存帧的路径

action_list = os.listdir(video_path)

for action in action_list:
    if not os.path.exists(save_path+action):
        os.mkdir(save_path+action)
    video_list = os.listdir(video_path+action)
    for video in video_list:
        prefix = video.split('.')[0]
        if not os.path.exists(save_path+action+'/'+prefix):
            os.mkdir(save_path+action+'/'+prefix)
        save_name = save_path + action + '/' + prefix + '/'
        video_name = video_path+action+'/'+video
        name = video_name.split('.')[1]
        if name == "avi":
            cap = cv2.VideoCapture(video_name)
            fps = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
            fps_count = 0
            for i in range(fps):
                ret, frame = cap.read()
                if ret:
                    cv2.imwrite(save_name + str(10000 + fps_count) + '.jpg', frame)
                    fps_count += 1
        if name == "gif":
           im = Image.open(video_name)
           #当打开一个序列文件时,PIL库自动加载第一帧。
           #可以使用seek()函数和tell()函数在不同帧之间移动。实现保存
           try:
              while True:
                   current = im.tell()
                   #为了保存为jpg格式,需要转化。否则可以保存为png
                   img = im.convert('RGB')  
                   img.save(save_name+'/'+str(10000+current)+'.jpg')
                   im.seek(current + 1)
           except EOFError:
               pass

 

Guess you like

Origin blog.csdn.net/lianggyu/article/details/98744359