Saturday, 2 July 2016

TUT5: Playing video file using Python-OpenCV

In this tutorial, you will learn to write a code in Python-OpenCV which can run a video file.
Let' see how to do this. Here is the code:

import cv2                                      #line1
cap=cv2.VideoCapture('chammakchallo.avi')       #line2
while(1):                                       #line3
    ret,frame =                      #line4
    cv2.imshow('frame',frame)                   #line5
    if cv2.waitKey(25) == 27:                   #line6
        break                                   #line7
cap.release()                                   #line8
cv2.destroyAllWindows()                         #line9

Lets understand the code line by line:

Line1: OpenCV library imported first of all.

Line2: VideoCapture object 'cap' initialised with file name of the video as the argument of                              VideoCapture() function. Remember to provide the full path to video file if the video is not in              the same folder as the program.

Line3: while loop starts.

Line4: frame is captured from the camera and saved in frame variable.

Line5: cv2.imshow() used to display the frame on window named 'frame'.

Line6: cv.waitkey(25) holds the screen i.e. 'the frame' for for 25 milliseconds and also checks if ESC               key is pressed(27 is ASCII for 'ESC key'). If ESC key is pressed then break is encoutered and 
            we are out of loop.

Line7: break is a jump statement which when encountered bring program execution to the first line                 after the loop. In this case, its cap.release which is executed as it is the first line after the loop.

Line8: cap.release() release the VideoCapture object. 

Line9: cv2.destroyAllWindows() kills the active windows if any.


As you can see the video is playing after running the code. Note that you wont be able to hear the audio because OpenCV is a vision library and not an audio library. Its use is to manipulate the images,videos and not the sound. This tutorial just teaches you the basic things that you need to know about OpenCV and this feature is one of them.

That's it for this tutorial. See you in the next one where we are going to capture and save a video using a laptop camera. 

Any queries please ask in comments.

No comments:

Post a comment