In this video we will learn how to extract images/frames from videos.
If you need extra images for you neural network, or maybe you just want the images for GIFs, wallpapers etc.
OpenCV comes with many powerful video editing functions. In current scenario, techniques such as image scanning, face recognition can be accomplished using OpenCV.
Image Analysis is a very common field in the area of Computer Vision. It is the extraction of meaningful information from videos or images. OpenCv library can be used to perform multiple operations on videos.
Modules Needed:
import cv2
import os
Function Used :
VideoCapture(File_path) : Read the video(.mp4 format)
read() : Read data depending upon the type of object that calls
imwrite(filename, img[, params]) : Saves an image to a specified file.
Below is the implementation:
# Importing all necessary libraries
import cv2
import os
# Read the video from specified path
cam = cv2.VideoCapture("C:\\Users\\Admin\\PycharmProjects\\project_1\\openCV.mp4")
try:
# creating a folder named data
if not os.path.exists('data'):
os.makedirs('data')
# if not created then raise error
except OSError:
print ('Error: Creating directory of data')
# frame
currentframe = 0
while(True):
# reading from frame
ret,frame = cam.read()
if ret:
# if video is still left continue creating images
name = './data/frame' + str(currentframe) + '.jpg'
print ('Creating...' + name)
# writing the extracted images
cv2.imwrite(name, frame)
# increasing counter so that it will
# show how many frames are created
currentframe += 1
else:
break
# Release all space and windows once done
cam.release()
cv2.destroyAllWindows()
Output:
All the extracted images will be saved in a folder named “data” on the system.
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 I set 0.5 so it will capture a frame at every 0.5 seconds, means 2 frames (images) for each second.
It will save images with name as image1.jpg, image2.jpg and so on.
Images (Frames) to Video
Code:
import cv2
import numpy as np
import os
from os.path import isfile, joinpathIn= './images/testing/'
pathOut = 'video.avi'
fps = 0.5frame_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()
Explanation:
Using this code we can generate video from Images (Frames). We have to add pathIn (path of the folder which contains all the images). I set framerate with 0.5 so it will take 2 images for 1 second.)
It will generate output video in any format. (eg.: .avi, .mp4, etc.)
!!! Please take care that all images are in sequence like image1.jpg, image2.jpg and so on.
#python #opencv #web-development #image