Chapter 8: Operations on Videos

a. Process a video with canny

You will learn nothing new in this section. The piece of code below just mix the two chapters of image filter and video reading. This example just apply the canny algorithm on the video to find contours on the video.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import cv2.cv as cv

capture = cv.CaptureFromFile('img/myvideo.avi')

nbFrames = int(cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_COUNT))
fps = cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_FPS)
wait = int(1/fps * 1000/1)

dst = cv.CreateImage((int(cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_WIDTH)),
                        int(cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_HEIGHT))), 8, 1)

for f in xrange( nbFrames ):

    frame = cv.QueryFrame(capture)

    cv.CvtColor(frame, dst, cv.CV_BGR2GRAY)
    cv.Canny(dst, dst, 125, 350)
    cv.Threshold(dst, dst, 128, 255, cv.CV_THRESH_BINARY_INV)

    cv.ShowImage("The Video", frame)
    cv.ShowImage("The Dst", dst)
    cv.WaitKey(wait)

Original image:

Canny image:

b. Haar Object detection

Once again a simple adaptation of the Haar Object detection with the webcam.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import cv2.cv as cv

capture=cv.CaptureFromCAM(0)

hc = cv.Load("haarcascades/haarcascade_frontalface_alt.xml")

while True:
frame=cv.QueryFrame(capture)
faces = cv.HaarDetectObjects(frame, hc, cv.CreateMemStorage(), 1.2,2, cv.CV_HAAR_DO_CANNY_PRUNING, (0,0) )

for ((x,y,w,h),stub) in faces:
    cv.Rectangle(frame,(int(x),int(y)),(int(x)+w,int(y)+h),(0,255,0),2,0)

    cv.ShowImage("Window",frame)
    c=cv.WaitKey(1)
    if c==27 or c == 1048603: #If Esc entered
        break

<<Video IO and Sources | Home | Tracking Moving Objects>>