Tuesday, March 4, 2014

Convert the video into images using Open CV and C

 In previous post we have seen how we can use Open CV to show images of a folder continuously so that the viewer can fell like as a video. We can use the Open CV for extracting the frames of a video. After extracting we can save them with the desired file extension. You can use the fallowing code for that.

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

int main()
{
    char  video_path[100];
    char  destination[100];
    char file_name[20];
    int count=100000;

    CvCapture *capture;
    IplImage * image;
   

    printf("Enter the path to the Video file");
    gets(video_path);

    printf("Enter the destinatio folder to save images");
    gets(destination);

    capture=cvCreateFileCapture(video_path);
    for(;;)
    {
        sprintf(file_name,"%s%d%s",destination,count,".jpg");
        image=cvQueryFrame(capture);
        cvSaveImage(file_name,image);
        printf("%s is saved.. \n",file_name);
        count++;
    }
    cvReleaseCapture(&capture);
    puts("Video is converted to images...");
    getch();
    return 0;
}

In this code we used two character arrays. One is for storing the path for the video. Second one is for storing the path to the folder to store images. You might have observed the integer variable this is for giving the file names sequentially for the images. file_name is another char array for temporally storing the file name.

By using sprintf we are appending the .jpg extension to the integer and we are saving the extracted frame from the video with the name containing in the file_name char array. This data changes for each frame.
We are using the very beautiful function provided by Open CV to save the image on the secondary memory that is out HDD. The function is cvSaveImage. This function takes two arguments first one is the filename and the second one is the image data typically variable of type IplImage*.

We are using the infinity loop to get all the frames from the video. After extracting all the frames the loop automatically breaks. Next we are releasing all the resources used by the Open CV by using  cvReleaseCapture.

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...