You are here

VidRecord example in Python

You may download the source code for this example. Software is released under terms of the Open Source Initiative BSD 2 - Clause license. Copy of the license for this software is at .

Required imports are:

import argparse
import os
import time
from cv2 import *

You need to define the following properties to record video as they seem to be
missing in the OpenCV 2.4.2 python module.


Also the CV_FOURCC function is not defined in the OpenCV 2.4.2 python module.

def CV_FOURCC(c1, c2, c3, c4) :
    return (c1 & 255) + ((c2 & 255) << 8) + ((c3 & 255) << 16) + ((c4 & 255) << 24)

Here is a function to create a video file named with the time stamp of when its created

def createVideoFile(path, width, height, fps ,fourcc,tsec):
    filename = time.strftime("%Y-%m-%dT%Hh%Mm%Ss", time.gmtime(tsec))
    pathname = os.path.join(path,filename) + ".avi"
    print "Create video file "+pathname
    writer = VideoWriter(pathname, fourcc, fps,(width,height))
    return writer;

And a function to write an image file

def writeImageFile(path, tsec, frame):
    filename = time.strftime("%Y-%m-%dT%Hh%Mm%Ss", time.gmtime(tsec))
    pathname = os.path.join(path,filename) + "." + imageFmt
    print "Create image file "+pathname
    imwrite(pathname, frame)

To get started we set the default video and image directories to store videos and images. These may be overridden by command line arguments.

videoDir = os.path.join(os.getenv("HOME","."),"Videos")
imageDir = os.path.join(os.getenv("HOME","."),"Pictures")

We can use Python's nifty ArgumentParser class to set up defaults and parse the command line.

parser = argparse.ArgumentParser()
parser.add_argument("-dis","--dis", help="Display video frame (set DIS to True or False)",default=True)
parser.add_argument("-viddir","--viddir",help="Set directory to save videos", default=videoDir)
parser.add_argument("-viddev","--viddev",help="Select video device number (usually 0 or 1, defailt is 0)",type=int,default = 0) 
parser.add_argument("-vidint","--vidint",help="recording interval in sec (default=0)",type=int,default=60)
parser.add_argument("-vidnum","--vidnum",help="number of videos to record default is 1",type=int,default=0)
parser.add_argument("-codec","--codec",help="Set recording codec MJPG,PIM1,MP42,U263,I263,FLV1 default is DIVX (mpeg4)",default="DIVX")
parser.add_argument("-vidfps", "--vidfps", help="Set recording fps", type=int, default=30)
parser.add_argument("-imgfmt","--imgfmt",help="Set video image format [jpg, png, tiff]",default="jpg")
parser.add_argument("-imgint","--imgint",help="Set interval between images (sec)", type=int,default=60)
parser.add_argument("-imgdir", "--imgdir", help="Set directory to save images",default=imageDir)
parser.add_argument("-imgnum", "--imgnum", help="Number of images to take", type=int, default=0)
args = parser.parse_args()

The argument values can be accessed through the "args" variable returned by the parser, for example args.dis, args.vidfps, etc. We use these to initialize some variables.

Now calculate the fourcc value from codec specified.; by default the codec is "DIVX"

codecArr = list(args.codec)
fourcc = CV_FOURCC(ord(codecArr[0]),ord(codecArr[1]),ord(codecArr[2]),ord(codecArr[3]))

Then open the video device to which the camera is connected. Its necessary to set width and height as some device drivers default to a only a frame which is only a few pixels in width and height.

cap = VideoCapture(videoDevice)
if cap.isOpened():
    cap.set(CV_CAP_PROP_FRAME_WIDTH, 640)
    cap.set(CV_CAP_PROP_FRAME_HEIGHT, 480)

A video frame is transferred to a image matrix by simply:

cap >> frame;

Frames are transferred from the VideoCapture class to an image matrix called "frame" on each pass through the loop.

To control everything the current time in seconds since 1970 is obtained by the following call.

sec = time.time()

The createVideoFile or writeImageFile functions are called at the proper intervals by checking the difference between current time and last time the file was written. Here is some of the code inside the loop for calling the writeImageFile function.

    if isImageEnabled:
        imageDelta = sec - imageTime
        if (imageDelta >= imageInterval):
            writeImageFile(imageDir, sec, frame)
            imageTime = sec
            imageTotal = imageTotal + 1
            if (imageTotal >= imageNum):
                isImageEnabled = False

The code for creating the image file is similar. See source code file referenced above for more details.