If you need reference code check this and this to get you started.
Anyway, the code below displays video from the webcam. If you take a closer look you'll see there's a conversion from the colored frame to a grayscale version and the grayscale is displayed on the window.
The grayscale frame is also recorded on file on the disk, named out.avi. You must know that this code wont work on Mac OS X with OpenCV 2.1 simply because OpenCV needs to be compiled with ffmpeg to allow enconding video to a file.
On Windows, cvCreateVideoWriter() will display a dialog box for you to select the appropriate codec you want to use when saving the video. Its possible to change this function call by setting a parameter that will hardcode the codec of your preference.
I wrote it in a hurry, but I know it works.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cv.h>
#include <highgui.h>
#include <cxtypes.h>
#include <cvaux.h>
int main()
{
int camera_index = 0;
IplImage *color_frame = NULL;
int exit_key_press = 0;
CvCapture *capture = NULL;
capture = cvCaptureFromCAM(camera_index);
if (!capture)
{
printf("!!! ERROR: cvCaptureFromCAM\n");
return -1;
}
double cam_w = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH);
double cam_h = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT);
double fps = cvGetCaptureProperty(capture, CV_CAP_PROP_FPS);
printf("* Capture properties: %f x %f - %f fps\n", cam_w, cam_h, fps);
cvNamedWindow("Grayscale video", CV_WINDOW_AUTOSIZE);
CvVideoWriter* writer = NULL;
writer = cvCreateVideoWriter("out.avi", -1, fps, cvSize((int)cam_w,(int)cam_h), 1);
if (writer == NULL)
{
printf("!!! ERROR: cvCreateVideoWriter\n");
return -1;
}
while (exit_key_press != 'q')
{
color_frame = cvQueryFrame(capture);
if (color_frame == NULL)
{
printf("!!! ERROR: cvQueryFrame\n");
break;
}
IplImage* gray_frame = cvCreateImage(cvSize(color_frame->width, color_frame->height), color_frame->depth, 1);
if (gray_frame == NULL)
{
printf("!!! ERROR: cvCreateImage\n");
continue;
}
cvCvtColor(color_frame, gray_frame, CV_BGR2GRAY);
cvShowImage("Grayscale video", gray_frame);
cvWriteFrame(writer, gray_frame);
cvReleaseImage(&gray_frame);
exit_key_press = cvWaitKey(1);
}
cvReleaseVideoWriter(&writer);
cvDestroyWindow("Grayscale video");
cvReleaseCapture(&capture);
return 0;
}