You're here: Home / OpenCV /

Display Video from Webcam

If you have a webcam attached to your computer, you can display video stream using OpenCV easily. Here's the basic code.

#include <stdio.h>
#include "cv.h"
#include "highgui.h"

int main(int argc, char **argv)
{
    CvCapture *capture = 0;
    IplImage  *frame = 0;
    int       key = 0;

    /* initialize camera */
    capture = cvCaptureFromCAM(0);

    /* always check */
    if (!capture) {
        fprintf (stderr, "Cannot open initialize webcam!\n");
        return(1);
    }

    /* create a window for the video */
    cvNamedWindow("result", CV_WINDOW_AUTOSIZE);

    for (;;) {
        if (!cvGrabFrame(capture)) {
            break;
        }
        
        frame = cvRetrieveFrame(capture);

        /* always check */
        if (!frame) {
            break;
        }
        
        /* display current frame */
        cvShowImage("result", frame);

        /* exit if user press a key */
        if ((key = cvWaitKey(1)) > 0) {
            goto done;
        }
    }

done:
    /* free memory */
    cvDestroyWindow("result");
    cvReleaseCapture(&capture);

    return(0);
}

Save it to webcam.c and compile with command like this:

gcc webcam.c -o webcam
    -I"C:\OpenCV\cv\include"
    -I"C:\OpenCV\cxcore\include"
    -I"C:\OpenCV\otherlibs\highgui"
    -L"C:\OpenCV\lib" -lcxcore -lcv -lhighgui

Be sure to change C:\OpenCV with your OpenCV base directory. To run the program, type webcam from your command line.

What's next?

After you have successfully displayed video from your webcam, here are some possible things you can do to play around:

  • Create your own photobox by saving a frame to JPEG.
  • Save the video to AVI or MPEG files, and send it to YouTube!
  • Create a security system.
  • etc.

Keywords: display video, video stream, video processing, webcam, opencv

Share:  del.icio.us logo Save to del.icio.us  digg logo Digg this!

comment.gifComments

Hello
After I read I don't understand how to do it. How to put the code inside CamVideo.

what do you mean? just compile the code and run it. it will display a window with streaming video in it.

comment.gifAdd your comment

(required, will not be published) (optional)