Display Video from Webcam

Nov 4, 2008 | Tags: OpenCV | del.icio.us del.icio.us | digg Digg

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

Listing 1: Display Video from Webcam

  1. /**
  2.  * Display video from webcam
  3.  *
  4.  * Author  Nash
  5.  * License GPL
  6.  * Website http://nashruddin.com
  7.  */
  8.  
  9. #include <stdio.h>
  10. #include "cv.h"
  11. #include "highgui.h"
  12.  
  13. int main( int argc, char **argv )
  14. {
  15.     CvCapture *capture = 0;
  16.     IplImage  *frame = 0;
  17.     int       key = 0;
  18.  
  19.     /* initialize camera */
  20.     capture = cvCaptureFromCAM( 0 );
  21.  
  22.     /* always check */
  23.     if ( !capture ) {
  24.         fprintf( stderr, "Cannot open initialize webcam!\n" );
  25.         return 1;
  26.     }
  27.  
  28.     /* create a window for the video */
  29.     cvNamedWindow( "result", CV_WINDOW_AUTOSIZE );
  30.  
  31.     while( key != 'q' ) {
  32.         /* get a frame */
  33.         frame = cvQueryFrame( capture );
  34.  
  35.         /* always check */
  36.         if( !frame ) break;
  37.        
  38.         /* display current frame */
  39.         cvShowImage( "result", frame );
  40.  
  41.         /* exit if user press 'q' */
  42.         key = cvWaitKey( 1 );
  43.     }
  44.  
  45.     /* free memory */
  46.     cvDestroyWindow( "result" );
  47.     cvReleaseCapture( &capture );
  48.  
  49.     return 0;
  50. }

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.

Related Articles

Recommended Book

The Downloads

36 Comments

Tien Loc on Jul 10, 2008:

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

Nash on Jul 11, 2008:

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

lancer on Oct 5, 2008:

If i would like to do some image processing for the video, can i just add-in together with image processing tools provided by OpenCV?

Nash on Oct 6, 2008:

Yes. See this post for an example.

Jose on Nov 7, 2008:

I cannnot display anything...it shows a black window...anybody know why?

Nash on Nov 8, 2008:

make sure your webcam properly connected

Yosef on Dec 14, 2008:

How to use 2 webcam's with OpenCV simultaneously?

jackson on Dec 14, 2008:

Hello. Me again. I wish you did the commentary of the code line by line http://www.nashruddin.com/display-video-from-webcam-with-opencv.html can I use it for a school project.

Nash on Dec 14, 2008:

Yes you can use the code for any purpose. However, some credits for me will be highly appreciated

jackson on Dec 14, 2008:

this code is working very good in my pc. tank you very Nashruddin. please i need your response about my other questions.

Nash on Dec 14, 2008:

Glad to hear it works. what is your question? send your mail to me @ nashruddin.com

jackson on Dec 15, 2008:

I need a C language code that captures images of the webcam and when the person moving the
program will play a beep but it should be any different in the position of the person. can be used
to capture this part via OpenCV. Thanks and I hope that you gona help me to implement this application.

lucky on Jan 6, 2009:

We are making a robot and the problem statement is that the robot must be able to steer itself in a virtual city marked with colors for specific operations. Can you suggest some code for real time image capturing, color detection and comparison to mainpulate the robot?

Nash on Jan 7, 2009:

can anyone help?
btw, cool project

Tab Khan on Jan 27, 2009:

Hey Nash, you have a great collection of examples and I highly appreciate that. Too good, I had a query, I am working for motion detection, am using Vista enterprise and MFC application is in progress for that. I wanted to save the frames(read from an avi file)as bmp or some other format images. I think, I need to add some code in the while loop to save those frames as images. Please do help me out.

Nash on Jan 28, 2009:

Here's an example to save the first 10 frames from the code above.

IplImage *frames[10];
int      i = 0;

while( key != 'q' ) {
    /* get a frame */
    frame = cvQueryFrame( capture );

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

    /* copy first 10 frames to buffer */
    if( i < 10 ) {
        frames[i++] = cvCloneImage( frame );
    }
               
    /* exit if user press 'q' */
    key = cvWaitKey( 1 );
}

/* save images in buffer to disk */
char *filename = "";
for( i = 0 ; i < 10 ; i++ ) {
    sprintf( filename, "%d.jpg", (i+1) );
    cvSaveImage( filename, frames[i] );
}
The code above will save the frames to 1.jpg, 2.jpg, ..., 10.jpg

vishal on Mar 12, 2009:

i use "dev-c++/c" on windows. how can i make this code work on this platform. i m doing a project on 'displaying videos from a webcam connected wireless to my pc." .... do u have any suggestions on how to do this ... thanx in advance

Nash on Mar 13, 2009:

Hi,
Here's how to configure Dev-C++ to compile OpenCV programs:

http://opencv.willowgarage.com/wiki/DevCpp

I don't have wireless cameras, so I don't have any experience with that. However, we'll wait for your code here

Robert on Mar 16, 2009:

Hi! Is it possible to easily send video stream to other computer on the Internet using openCV?

Nash on Mar 16, 2009:

Hi Robert,
I've made a small project about web based surveillance system using OpenCV, PHP, and Javascript. check it out.

Kent on Mar 18, 2009:

Does OpenCV support USB Video Class (UVC) Device?

Nash on Mar 18, 2009:

I think so. For more information, see Linux OpenCV Camera Compability at OpenCV wiki.

nel on Mar 22, 2009:

Hello ,
I've got a problem about executing the code. Actually I added all necessary libraries,headers etc. as told in tutorials. But I coudn't capture frame from webcam. It just returns 0 and stop executing, I mean there is no actually an error but I couldn't understand what the problem is. It reports a lot of thing but I write the last 2 lines:
'cap_cam.exe': Unloaded 'C:\Windows\System32\iyuv_32.dll'
The program '[6028] cap_cam.exe: Native' has exited with code 0 (0x0).
Thanks for helping.

Deena on Apr 19, 2009:

hi again,
i try your source code in display the video but i can not preview the video from my laptop webcam (built in), only the black screen. is there any configuration to be done unto my webcam, or something like that?
tq!

Nash on Apr 20, 2009:

Actually there is no configuration or such. Check if other application can display your webcam too.

Deena on Apr 20, 2009:

I mean, it seem does work, becos i can see the light coming from the webcam, but the screen that suppose to show the video stand still black or sometimes grey.
i try check the other application to make sure the webcam is functioning. It 's in a good condition.
so what am i going to do next?

- others can give advise me too..tq

Anaas on Jul 25, 2009:

Thank you so much bro!!!

simple and effective code

ebrian on Jul 31, 2009:

how to save image from webcam with video format (avi, mpeg, etc..) ??

Nash on Aug 6, 2009:

There is an OpenCV tutorial that explain how to save frames to file, but it doesn't seem to be working properly. I think we have to install OpenCV with ffmpeg in order to have video functionality in OpenCV.

Kao on Aug 25, 2009:

For those who get the code run but only show a black screen, try to change 0 to 1 or 2

capture = cvCaptureFromCAM( 0 )

Ali on Aug 26, 2009:

Hi Nash,

First, your sample codes and instructions helped me so much when i had to learn opencv in short time for my graduation project. Thanks a lot!

I wonder, can we capture webcam, process it by opencv, then stream like a webcam source. There are programs streaming a video from hdd, in MSN or other chat programs as webcam.

In short, how can we create a virtual webcam source with opencv?

Thanks again.

Ali

Nash on Aug 26, 2009:

Man, I never thought about it! It's definitely gonna be a kickass OpenCV app. I'll look some way to make it. Thanks.

Ali on Aug 27, 2009:

I've searched opencv forum/groups archives for a streaming application but couldn't find it. Besides, I didn't see any function related to streaming video, in highgui.

I think, webcam frames should be processed by opencv, but, creating a webcam source is topic of system programming and it is supposed to be quite complex.

Silveira Neto on Sep 14, 2009:

I'm using OpenCV 1.0 in Ubuntu 8.04, I'm compiling this code by
gcc `pkg-config opencv --cflags --libs` webcam.c -o webcam

It's working, but very slowly compared with others webcam tools, but seems to be a start.

Rajdeep Das on Oct 11, 2009:

Thanks buddy...nashruddin...becoz of you i could successfully finish my project...

gde permana on Nov 2, 2009:

thx nash...... your code was helping me so much.. this is the fisrt time i use opencv

Leave a comment

Name (required)
Email (will not be published) (required)
Website

Characters left = 1000

Tags

Recent Posts

  1. OpenCV 2.0 Installation on Windows XP and Visual Studio 2008
  2. Runtime ROI Selection using Mouse
  3. Real Time Eye Tracking and Blink Detection
  4. HTTP Scripting Made Really Easy
  5. PHP Script for Converting Relative to Absolute URL
View Archives

About the Author

avatar Cool PHP programmer writing cool PHP scripts. Feel free to contact
Tel. +62 31 8662872
+62 856 338 6017
ICQ 489571630
Skype dede_bl4ckheart
Yahoo dede_bl4ckheart
Google nashruddin.amin

Recommended Sites:

Hacker's HTTP Client
HTML and CSS Tutorials
Stop Dreaming Start Action
Online Quran and Translation