Saturday, May 10, 2014

Extract frame from video when user presses a key in Open CV

Capturing the frames from video using Open CV is very simple. Just we need to use cvSaveImage method from Open CV library. But some times we need to capture the images interactively like when the user presses a key. For doing this we can use the function kbhit(). this function returns non zero values when there is something in the keyboard buffer. So by using this we can interactively extract the frames.

By using the fallowing code we can accomplish this.

#include "stdafx.h"
#include "cv.h"
#include "highgui.h"
#include <conio.h>

void main()
{
IplImage * img;
CvCapture * v;
v = cvCreateFileCapture("E:/v.mp4");
int k = 0;
char text[10];
while(true)
{
if(_kbhit())
{
sprintf(text,"%s%d%s","E:/Image",k,".jpeg");
cvSaveImage(text,img);
getch();
}
else
{
img= cvQueryFrame(v);
cvWaitKey(0);
k++;
}
}
_getch();
}

we have one while loop which continuously reads the frames from the video. The if block will be executed when the user presses a key from keyboard else else block gets executed. In else block we are extracting the frames from the video we have one delay loop as well else the the computer reads all the frames one by one with in fraction of seconds.

To change the saved image file name every time we are using char buffor. By using sprintf we are changing the file name. cvSaveImage saves the image on the specifed path supplied as first argument and the image to be saved as second argument. getch() is used to clear the buffor else the if block executed continuously.

No comments:

Post a Comment

DC motor control with Pulse Width Modulation Part 1

DC Motor intro DC motor is a device which converts electrical energy into kinetic energy. It converts the DC power into movement. The typica...