Program to extract frames using OpenCV in Python?


OpenCV(Open source computer vision) is an open source programming library basically developed for machine learning and computer vision. It provides common infrastructure to work on computer vision applications and to fasten the use of machine learning in commercial products.

With more than 2.5 thousand optimized algorithms for both computer vision and machine learning are both classic and state-of-the-art algorithms. With so many algorithms, makes it to use the library for multiple purposes including face detection & reorganization, identify objects, classify human actions in videos, track camera movements, join images together to produce a high resolution image of an entire scene and much more.

In this exercise we are going to implement frame by frame video processing. The input video can be live camera video or video stored in your local machine. We are going to create frames from the video stored in our local machine & then store the frames in our local drive.

As opencv is not a standard python library, so we need to install it. We can install it using pip very easily:

pip install opencv-python
Collecting opencv-python
Downloading https://files.pythonhosted.org/packages/49/4b/ad55a2e2c309fb698e1283e687129e0892c7864de9a4424c4ff01ba0a3bb/opencv_python-4.0.0.21-cp36-cp36m-win32.whl (22.1MB)
100% |████████████████████████████████| 22.1MB 141kB/s
Requirement already satisfied: numpy>=1.11.3 in c:\python\python361\lib\site-packages (from opencv-python) (1.13.0)
Installing collected packages: opencv-python
Successfully installed opencv-python-4.0.0.21

My video file is stored in the f: drive, which I want to convert into frames (thumbnails) and then store the frames in my chosen location.

Code: Program to read a video file and extract frames from it.

#Import libraries
import cv2
import os
#Function to extract frames
def extractFrames(pathIn, pathOut):
   #directory path, where my video images will be stored
   os.mkdir(r'c:/users/rajesh/Desktop/data')
   #Capture vidoe from video file
   cap = cv2.VideoCapture(pathIn)
#Counter Variable
count = 0

while (cap.isOpened()):
   # Capture frame-by-frame
   ret, frame = cap.read()
   if ret == True:
      print('Read %d frame: ' % count, ret)
      # save frame as JPEG file
      cv2.imwrite(os.path.join(pathOut, "frame{:d}.jpg".format(count)), frame)
      count += 1
   else:
      break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
def main():
   extractFrames(r'f:/I Miss You.mp4' , 'data')
if __name__=="__main__":
   main()

Output

We can see, a data folder is created in my desktop(destination path) and the frames from the video are stored inside the folder.

Updated on: 30-Jul-2019

247 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements