Convert Video to Images (Frames) & Images (Frames) to Video using OpenCV (Python)

Khush Patel
2 min readFeb 2, 2019
Video to Images and Images to Video

This post has 2 different part to generate frames from Video and from multiple images we can generate video in any format.

Video to Image (Frames) conversion

This will require to install CV2 library. If you have not installed it, just install using the following command.

>>> 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.

Code :

import cv2
vidcap = cv2.VideoCapture('video.mp4')
def getFrame(sec):
vidcap.set(cv2.CAP_PROP_POS_MSEC,sec*1000)
hasFrames,image = vidcap.read()
if hasFrames:
cv2.imwrite("image"+str(count)+".jpg", image) # save frame as JPG file
return hasFrames
sec = 0
frameRate = 0.5 #//it will capture image in each 0.5 second
count=1
success = getFrame(sec)
while success:
count = count + 1
sec = sec + frameRate
sec = round(sec, 2)
success = getFrame(sec)

Explanation :

In cv2.VideoCapture(‘video.mp4’), we just have to mention the video name with it’s extension. Here my video name is “video.mp4”. You can set frame rate which is widely known as fps (frames per second). Here…

--

--

Khush Patel

ML Engineer / Data Scientist | Master’s in AI | DL & CV Nanodegree Holder | Facebook AI Scholar | Inventor | Int’l Medal Winner@USA | http://www.khushpatel.com