4

I'm writing a programme in Windows XP using Python and OpenCV that adds image frames captured from a webcam to a video (.avi), but only when a certain condition is met. For testing purposes this condition is time based, but this will change. The only problem is, my programme does not output anything. Everything seems to run fine, but then when I check for the .avi file that it should be outputting, there is nothing.

Here's my code. I've been told my style is a little unconventional, but hopefully you can see what I'm up to. Thank you in advance.

import cv, time ##Import modules
cv.NamedWindow("Experiment", cv.CV_WINDOW_AUTOSIZE)                         ##Open window
camera_index = 1
capture = cv.CaptureFromCAM(camera_index)
x = time.clock()+5

try:
    while 1:
        if time.clock() < x:                                                ##Clock to capture 5 seconds of footage
            frame = cv.QueryFrame(capture)                                  ##Capture webcam frame
            cv.ShowImage("Experiment", frame)                               ##Display image
            writer = cv.CreateVideoWriter("C:\/test.avi", cv.CV_FOURCC('F', 'M', 'P', '4'),
                                          24, (640, 480), 1)                ##Write video file (codec = MPEG-4 - .avi)
            if writer:                                                      ##Write frame to file
                cv.WriteFrame(writer, frame)
            if not writer:                                                  ##Failure to register video writer
                print "Error: Video writer malfunction"
                sys.exit(1)
                cv.DestroyWindow("Experiment")
                break
        else:
            if writer:
                print "Video capture succeeded"
                cv.DestroyWindow("Experiment")
                camera_index += 1
                capture = cv.CaptureFromCAM(-1)
                break
        c = cv.WaitKey(10)
        if(c=="n"):
            camera_index += 1
            capture = cv.CaptureFromCAM(-1)
except:
    print "Video capture failed"                                            ##Total systems failure escape routine!!!
    cv.DestroyWindow("Experiment")

--Edit--

If I change cv.CV_FOURCC('F', 'M', 'P', '4') in line 12 to "-1" a video is output, but it is 0 bytes.

Florent
  • 12,310
  • 10
  • 49
  • 58
GenericGuy
  • 41
  • 1
  • 3
  • If I had to guess, I'd say it's a problem with the codec you're using, especially if no file is actually output whatsoever... I also had a lot of trouble with codecs when I had to do this, and the only one that worked for me was `cv.CV_FOURCC('i', 'Y', 'U', 'V')`. Else you can refer to [this question](http://stackoverflow.com/questions/1136989/creating-avi-files-in-opencv/1137034#1137034) for more on codecs. As an aside, I would highly recommend that you look into the newer `cv2` interface for Python, it will make your life much easier. – hjweide Nov 08 '12 at 20:29

0 Answers0