Programming a webcam in C using ‘OpenCv library’

 OpenCv library is  really a great help in programing a web-cam.I  tried to access a web-cam through a C code and was succesfull in doing it.Before the code can be executed and the web-cam can be accesed ,a library named ‘opencv’ is to be installed .
                          OpenCV (Open Source Computer Vision) is a library of programming functions for real time computer vision . OpenCV is released under a BSD license, it is free .

The library is available in debian distro cd’s and can be installed by issuing the commands

apt-get install opencv*

apt-get install libhighgui*

apt-get install libaux-dev

  •   Program in C to access web-cam, Capturing and Saving image

The web-cam can be accessed in C and the images  saved is in .jpg format

A simple program to see the video accessed by the webcam.

 My Cheese app in C.


#include <  opencv/cv.h  >
int main(int argc,char **argv)
        CvCapture* cap = cvCreateCameraCapture(0);
        IplImage *image1,*image2;
                image1  = cvQueryFrame(cap);


//waiting 33 milliseconds for a key to be pressed

                char c = cvWaitKey(33);

//if the key pressed is esc
//ascii of esc is 27

//if the key pressed is an up-arrow key
                else if(c ==’82’)
                        image2 = image1;
                        cvNamedWindow(“rohit photo”,CV_WINDOW_AUTOSIZE);
                        cvShowImage(“rohit photo”,image2);
        cvDestroyWindow(“rohit photo”);

Compile the above code by executing the command:

gcc -o cheese_in_c cheese.c `pkg-config opencv --cflags --libs `

 this command creates an executable named “cheese_in_c”.
Execute the executable as


this program displays a window named “rohit”showing the pictures taken from the webcam,then it waits for 33 milliseconds for the user to press a key.If key pressed is ‘up-arrow’ the picture from the camera is captured and saved in the same directory in the name “my-photo.jpg”.

  1. #1 by Anonymous on March 20, 2011 - 11:00 PM

    thank u for code….even if my camera is working properly i can't save the captured image in my home directory…….. why it is so???cn u pls help me for that……

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: