SoFunction
Updated on 2024-11-21

python tools implements the extraction and saving of each frame of a video

Preface

Recently I've been working on video caption related and have to deal with a lot of videos.

I ran into a problem today with getting theYoutubeClips The avi format videos in the dataset are extracted from each frame of their videos. Afterwards, the video was analyzed using theHigh accuracy optical flow estimation based on a theory for warping Optical Flow is proposed to extract the optical flow characteristics of the motion.

Method 1

Method 1 is the simplest, usingFFmpeg tools to accomplish this.

Specifically there is a lot of information on the Internet in this regard, I just briefly understand how to use. As shown below, there is a file namedffmpeg_test.avi The video:

Open a terminal in the current directory and enter the following command:

$ffmpeg -i ffmpeg_test.avi frames_% -hide_banner

I didn't specify too many parameters above, in fact there are a lot of parameters that can be specified, such as the time to start and stop, how many seconds to fetch a frame, and so on.

Enter to get each frame.

Method 2

The following is what can be extracted with VideoCapture, VideoWriter in cv2 module, the specific code is as follows:

#! encoding: UTF-8

import os

import cv2
import cv

videos_src_path = '/home/ou-lc/chenxp/Downloads/Youtube/youtube_select'
videos_save_path = '/home/ou-lc/chenxp/Downloads/Youtube/youtube_frames'

videos = (videos_src_path)
videos = filter(lambda x: ('avi'), videos)

for each_video in videos:
 print each_video

 # get the name of each video, and make the directory to save frames
 each_video_name, _ = each_video.split('.')
 (videos_save_path + '/' + each_video_name) 

 each_video_save_full_path = (videos_save_path, each_video_name) + '/'

 # get the full path of each video, which will open the video tp extract frames
 each_video_full_path = (videos_src_path, each_video)

 cap = (each_video_full_path)
 frame_count = 1
 success = True
 while(success):
 success, frame = ()
 print 'Read a new frame: ', success

 params = []
 (cv.CV_IMWRITE_PXM_BINARY)
 (1)
 (each_video_save_full_path + each_video_name + "_%" % frame_count, frame, params)

 frame_count = frame_count + 1

()

At the end, I saved each frame in PPM format. This is because I need to call the of program from the previous optical flow paper to extract the optical flow image.

When saving, according to opencv's Doc:OpenCV 2.4.9 , whose parameters are specified as above. Stumbled a few times here at first because I didn't know how to specify the parameters correctly.

Reference

/questions/33311153/python-extracting-and-saving-video-frames
/questions/12216333/opencv-imread-imwrite-increases-the-size-of-png

This is the whole content of this article.