Capture Video from File or Camera

Capture Video From File

In this lesson, I am going to show you how to read a video file. It's fairly simple. You just need to initialize a VideoCapture object which will open a video file and read frame by frame from that opened video. Here is the sample OpenCV code. If you are using Visual Studio, you will need to include "stdafx.h" header file.

/////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "opencv2/highgui/highgui.hpp"
#include <iostream>

using namespace cv;
using namespace std;

int main(int argc, char* argv[])
{
    VideoCapture cap("C:/Users/SHERMAL/Desktop/SampleVideo.avi"); // open the video file for reading

    if ( !cap.isOpened() )  // if not success, exit program
    {
         cout << "Cannot open the video file" << endl;
         return -1;
    }

    //cap.set(CV_CAP_PROP_POS_MSEC, 300); //start the video at 300ms

    double fps = cap.get(CV_CAP_PROP_FPS); //get the frames per seconds of the video

     cout << "Frame per seconds : " << fps << endl;

    namedWindow("MyVideo",CV_WINDOW_AUTOSIZE); //create a window called "MyVideo"

    while(1)
    {
        Mat frame;

        bool bSuccess = cap.read(frame); // read a new frame from video

if (!bSuccess) //if not success, break loop
{
                        cout << "Cannot read the frame from video file" << endl;
break;
}

        imshow("MyVideo", frame); //show the frame in "MyVideo" window

        if(waitKey(30) == 27) //wait for 'esc' key press for 30 ms. If 'esc' key is pressed, break loop
{
                cout << "esc key is pressed by user" << endl;
break
}
    }

    return 0;

}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
You can download this OpenCV visual c++ project from here. (The downloaded file is a compressed .rar folder. So, you have to extract it using Winrar or other suitable software) 

This is how  I play a video using my OpenCV program


video


New OpenCV functions which are not found earlier are explained here
  • VideoCapture::VideoCapture(const string& filename)
This is one of few constructors available in VideoCapture class. This constructor open the video file and initializes the VideoCapture object for reading the video stream from the specified file. 
The destructor of this class will deallocated any associated memory with this object. Therefore you don't need to deallocate memory explicitly in your program.

  • bool VideoCapture::IsOpened()
If the previous call to VideoCapture constructor is successful, this method will return true. Otherwise it will return false. 
It is essential to check that whether the VideoCapture initialize successfully. If it is unsuccessful, program should be exited. Otherwise when you try to read a frame from the VideoCapture object, your program will crash.

  • bool VideoCapture::set(int propId, double value)
You can change some properties of VideoCapture object. If it is successful, this method will return true. Otherwise it will return false. You should try to change some properties of the video stream in your code. In my code, I have shown you how to change the position of the video, by changing the CV_CAP_PROP_POS_MSEC property.

Parameters :
    • int propID - This argument specify the property you are going to change. There are  many options for this argument. Some of them are listed here.  
      • CV_CAP_PROP_POS_MSEC - current position of the video in milliseconds
      • CV_CAP_PROP_POS_FRAMES - current position of the video in frames
      • CV_CAP_PROP_FRAME_WIDTH - width of the frame of the video stream
      • CV_CAP_PROP_FRAME_HEIGHT - height of the frame of the video stream
      • CV_CAP_PROP_FPS - frame rate (frames per second)
      • CV_CAP_PROP_FOURCC - four character code  of codec
    • double value - This is the new value you are going to assign to the property, specified by the propID

  • doubleVideoCapture::get(int propId)
This function returns the value of the property which is specified by propId. You should try to obtain some properties of the video stream in your code. In my code, I have shown you how to obtain the frame rate (frames per second) of the video, by using the CV_CAP_PROP_FPS argument.

Parameters - 
    • int propID - This argument specify the property you are going to obtain. There are many options for this argument. Some of them are listed here.  
      • CV_CAP_PROP_POS_MSEC - current position of the video in milliseconds
      • CV_CAP_PROP_POS_FRAMES - current position of the video in frames
      • CV_CAP_PROP_FRAME_WIDTH - width of the frame of the video stream
      • CV_CAP_PROP_FRAME_HEIGHT - height of the frame of the video stream
      • CV_CAP_PROP_FPS - frame rate (frames per second)
      • CV_CAP_PROP_FOURCC - four character code  of codec

  • bool VideoCapture::read(Mat& image);
The function grabs the next frame from the video, decodes it and stores it in the 'image' variable. Inside this function, VideoCapture::grap() and VideoCapture::retrieve() will be called. If you want, you can use these two functions instead of VideoCapture::read() function. 
If the operation successful, it will return true. Otherwise it will return false.

  • waitKey(30)
The function waits for 30 milliseconds. If a key was pressed before the specified time, it returns the ASCII value of the pressed key. If that value is 27 (ASCII value of 'esc' key is 27), the program will execute inside the if block. If no key is pressed during that 30ms, the function returns -1 program will continue the while loop.

  • VideoCapture::~VideoCapture()
Destructor of VideoCapture object will destroy any associated memory of that particular object. This destructor will be called implicitly on exit of the main method of the above program.


Summary

At first, this program captures a video from a file. Then the program enters into a infinite loop. In that loop, it grabs frames from the captured video sequentially, decodes it, shows it in a window and waits for 30 milliseconds. If the video file has no more frames or if the user presses the 'esc' key, the program will break the infinite loop.

Note:
Using waitKey(int) function is very important because imshow(string&, MAT) function need time to paint the image in the window and waitKey(int) will give that necessary time.



Capture Video From Camera


The main difference of the following program from the above program is the argument to the VideoCapture constructor. Here you just need to give the index of your camera to the constructor of the VideoCapture object instead of the filename in the above program. Here is the sample OpenCV code.

///////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "opencv2/highgui/highgui.hpp"
#include <iostream>

using namespace cv;
using namespace std;

int main(int argc, char* argv[])
{
    VideoCapture cap(0); // open the video camera no. 0

    if (!cap.isOpened())  // if not success, exit program
    {
cout << "Cannot open the video cam" << endl;
        return -1;
    }

   double dWidth = cap.get(CV_CAP_PROP_FRAME_WIDTH); //get the width of frames of the video
   double dHeight = cap.get(CV_CAP_PROP_FRAME_HEIGHT); //get the height of frames of the video

    cout << "Frame size : " << dWidth << " x " << dHeight << endl;

    namedWindow("MyVideo",CV_WINDOW_AUTOSIZE); //create a window called "MyVideo"

    while (1)
    {
        Mat frame;

        bool bSuccess = cap.read(frame); // read a new frame from video

if (!bSuccess) //if not success, break loop
{
cout << "Cannot read a frame from video stream" << endl;
break;
}

        imshow("MyVideo", frame); //show the frame in "MyVideo" window

        if (waitKey(30) == 27) //wait for 'esc' key press for 30ms. If 'esc' key is pressed, break loop
{
cout << "esc key is pressed by user" << endl;
break
}
    }
    return 0;

}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////

You can download this OpenCV visual c++ project from here. (The downloaded file is a compressed .rar folder. So, you have to extract it using Winrar or other suitable software)

This is how  I capture myself with my webcam using the OpenCV program


video


New OpenCV functions which are not found earlier are explained here
  • VideoCapture::VideoCapture(int device)
This is one of constructors available in VideoCapture class. This constructor open the camera indexed by  the argument of this constructor and initializes the VideoCapture object for reading the video stream from the specified camera.
Here the '0' means the index of the camera to be used. You can use 1,2,3.. instead of 0, if your computer is attached to more than 1 camera. 
The destructor of this class will deallocated any associated memory with this object. Therefore you don't need to deallocate memory explicitly in your program.


  • if (!cap.isOpened())
If the VideoCapture object initialization unsuccessful, the expression inside the 'if 'parentheses will evaluate to true and the statements inside the 'if' block will be executed. 
It is a good practice to check this scenario and handle it accordingly because otherwise it may cause the program to crash.



  • double dWidth = cap.get(CV_CAP_PROP_FRAME_WIDTH)
This function obtain the width (in pixels) of frames of the camera output.

  •  double dHeight = cap.get(CV_CAP_PROP_FRAME_HEIGHT)
This function obtain the height (in pixels) of frames of the camera output.

 All other OpenCV functions and their arguments are exactly same as the 1st program.



Next Tutorial : Write Image & Video to File

Previous Tutorial : Read & Display Image






100 comments:

  1. Execellent tutorial! YOU ARE AWESOME!!!!
    Made it so easy and fun, thanks a bunch!

    ReplyDelete
  2. I need help with accessing TP-Link IP Camera TL-SC3130G in OpenCV. How can I access it wirelessly using WAN IP and port from a remote network?

    ReplyDelete
    Replies
    1. OpenCV doesn't have inbuilt functions to access a camera remotely. You have to write your own code from sockets

      Delete
  3. Thanks, u made it effortless :)
    keep up the good work (y)

    ReplyDelete
  4. Hi,

    I wanted to know how can we get the type of image "frame" is when we capture a frame from a video saved on disk using cv::Videocapture?

    Thanks

    ReplyDelete
    Replies
    1. Using "double VideoCapture::get(int propId)" function, you can get many information about frames of the captured video.

      Delete
    2. Yes, I did try that. But there is no information on the type of image that frame is. For e.g I want to use a library that only works for ppm images. So I'm capturing frames from videos, and trying to determine whether I can directly use that library to compute something on those frames.

      Am I make any incorrect assumptions here?

      Delete
  5. Thanks for the great explanation. I was wondering if there is an easy way to remove black frames from videos (like when the videos end) using cv::VideoCapture.

    Any clues?

    ReplyDelete
    Replies
    1. You can take the average pixel value for a frame. If that average value is smaller than some threshold, it should be a black frame.

      Delete
  6. Hi, what to do when i want to capture video from fullHD Camera through HDMI?
    VideoCapture::VideoCapture(int device) doesnt work for me in that case.

    ReplyDelete
    Replies
    1. I have done it with VideoCapture::VideoCapture(int device). Please check the number, you passed to the VideoCapture constructor.

      Delete
    2. Now I noticed that Im using capture = cvCreateCameraCapture(0); instead of VideoCapture::VideoCapture(int device); its probably because im using older opencv version (2.3) but i still hope i can use that fullHD HDMI camera in this version.
      Please tell me if I cant. I've got 3cameras, 2 of them are USB webcams and third one is HDMI camera. When Im using that cvCreateCameraCapture(x); where x is 0 or 1, its working correctly, 2 of webcams are showing images as I wanted, but I cant find a way to get that HD camera working. On the linux device list, webcams are shown as 'video0' and 'video1', but HD cam is not shown directly. On the list I can see 'blackmagic' and 'blackmagic0' i guess its where HD cam should be, since its connected through HDMI to blackmagic video card.

      Delete
    3. I have tested with cvCreateCameraCapture(0)in Windows. But I think you are using linux and I have no idea about that

      Delete
    4. Yes Im using Linux. Thank you for tutorial and your responses.

      Delete
  7. Thank you for your easy tutorial :)
    I have a question, I am reading this tutorial and i am in this chapter, are there any chapter after that talking about how to compare two images ??

    ReplyDelete
  8. Dear Shermal Fernando,
    I'm wondering that why i could not get the frame rate of webcam by using cap.set(CV_CAP_PROS_FPS) like i do in the reading video program?

    ReplyDelete
    Replies
    1. You are refering to cap.get(CV_CAP_PROS_FPS), not cap.set(CV_CAP_PROS_FPS). Anyway I think it's a bug in the OpenCV library.

      Delete
  9. Dear Shermal Fernando, I am trying to execute your code. It has no build errors. But it could not capture frame from the webcam. I think below if structure is executed that means webcam not capture frame. But why can't? Please give a reply............

    if (!bSuccess) //if not success, break loop
    {
    cout << "Cannot read a frame from video file" << endl;
    break;
    }

    ReplyDelete
    Replies
    1. Dear Dejan Gope, add "cap.retrieve(frame);" in a line before "bool bSuccess = cap.read(frame);"

      Delete
  10. OpenCV does not support some cameras

    ReplyDelete
  11. Hello,
    Ages ago I run a video capture in my old computer and it was work fine. Now I run your program and after adding cap.retrieve(frame) function I could to see myself in the monitor, but it is very delay. I think it needs to initialise the capture time to real time. Do you know how to fix this issue?

    Regards

    Amir

    ReplyDelete
    Replies
    1. waitKey(30) ;
      Try reducing the value 30. But if that value is two low, you can't even see the video. You should find the optimum value for this

      Delete
    2. Thank you. It is working.
      I have another problem with capturing video from file. I ran the program, but it cannot capture the video from file. The program terminated anytime it tried to open the video from the file.
      Regards

      Delete
    3. The type of the video file may not be supported by OpenCV library. Try a different video file

      Delete
  12. I can't run this program.

    there's a warn, apllication error:
    "the instruction at )x767ddbba referenced memory at 0xcccccccc. the memory coldnot be read"

    ReplyDelete
  13. great post i am using this Video Camera from last few months i never face any kind of problem from the date of the purchase it

    ReplyDelete
  14. Great tutorial mate ;)

    but I need some help, some code does not work for me. I get the video just fine and any data I need from the frame. The problem I have is that I can't set anything
    example:
    cap.set(CV_CAP_PROP_FPS)
    or cap.set(CV_CAP_PROP_FRAME_WIDTH)
    I letter use the cap.get and it shows that nothing has changed(I can also see it in the video).

    Also the waitKey() does not work for me. What ever I press (including Ecs) it does not exit the program.

    Both of this problems are with video file ans camera. I'm using OpenCV 2.4.6.1.

    ReplyDelete
    Replies
    1. The set method should be used as follows
      cap.set(CV_CAP_PROP_FPS, value)
      It is true that this method may not work with some cameras.

      But waitKey(int) should work. You have to check the return value of waitKey(int) function and exist the program.

      Delete
    2. Forgot to right the value in my comment but in the program I wrote
      bool x = cap.set(CV_CAP_PROP_FPS, 20);
      and x is true after that but the when I use the cap.get is says tha fps is 29.97. I can under stand why is would not work with the camera but why not the the .avi video file?

      for the waitKey I do exactly what you do,
      if (waitKey(30) == 27)
      {
      cout << "esc key is pressed by user" << endl;
      break;
      }

      is side the while(1) loop but nothing. How do I check the return value?

      Delete
    3. Increase the value from 30 to 100 or something bigger and check whether the while loop breaks.
      Otherwise do the following
      int iReturnValue = waitKey(30);
      cout << iReturnValue << endl;

      Delete
    4. so I did the 30 to 100 and the video is playing is slow motion and if I keep Esc press down long enough the video played in normal speed... not sure why :P

      when I did the second thing, the iReturnValue had the number 1048603. Don't know why that but what I did was after that put if(iReturnValue==1048603){break;}. Not the best solution but works for now :). Thanks for the help ;)

      Delete
    5. hmmm now I got it I think. I'm running Linux so maybe the Esc returns 27 for Windows and 1048603 for Linux or something like that I guess :)

      Delete
  15. Hi All,
    I have installed Visual Studio Express 2013. I'm getting an error such as shown below while running the program mentioned in this page of the tutorial. Could anyone please help me resolve this issue ?

    'First Project.exe' (Win32): Loaded 'C:\Users\Saisagar\Documents\Visual Studio 2013\Projects\First Project\x64\Debug\First Project.exe'. Symbols loaded.
    'First Project.exe' (Win32): Loaded 'C:\Windows\System32\ntdll.dll'. Cannot find or open the PDB file.
    'First Project.exe' (Win32): Loaded 'C:\Windows\System32\kernel32.dll'. Cannot find or open the PDB file.
    'First Project.exe' (Win32): Loaded 'C:\Windows\System32\KernelBase.dll'. Cannot find or open the PDB file.
    'First Project.exe' (Win32): Loaded 'C:\opencv\build\x64\vc11\bin\opencv_core246d.dll'. Cannot find or open the PDB file.
    'First Project.exe' (Win32): Loaded 'C:\opencv\build\x64\vc11\bin\opencv_highgui246d.dll'. Cannot find or open the PDB file.
    'First Project.exe' (Win32): Loaded 'C:\Windows\System32\msvcp120d.dll'. Cannot find or open the PDB file.
    'First Project.exe' (Win32): Loaded 'C:\Windows\System32\msvcr120d.dll'. Cannot find or open the PDB file.
    'First Project.exe' (Win32): Loaded 'C:\Windows\System32\msvcp110d.dll'. Cannot find or open the PDB file.
    'First Project.exe' (Win32): Loaded 'C:\Windows\System32\msvcp110d.dll'. Cannot find or open the PDB file.
    'First Project.exe' (Win32): Unloaded 'C:\Windows\System32\msvcp110d.dll'
    'First Project.exe' (Win32): Unloaded 'C:\Windows\System32\msvcp110d.dll'
    The program '[5240] First Project.exe' has exited with code -1073741701 (0xc000007b).

    Thanks in Advance !!

    ReplyDelete
    Replies
    1. This showed me, when I had set full path of video file. You can bypass it by copying corresponding file right to the project folder, where you have stored cpp file with main function.

      Delete
  16. would u please give us the code for comparing two images ..

    ReplyDelete
  17. Hello Fernando! I'm also Fernando :)
    I have a problem when I run your "Capture Video From Camera" program. The program build correctly, but when I run in a terminal, show the message "Cannot open the video file". I think that OpenCV 2.4.2 doesn't recognize my cam, because I tried to make the program with the algorithm:

    >CvCapture* capture = NULL;
    >capture = cvCaptureFromCAM(0);

    I've also tried changing the '0' by '1', '-1', 'CV_CAP_DSHOW', and 'CV_CAP_ANY' with others similar programs,but the error persists. I use Ubuntu 12.04 LTS, and I write my programs in Eclipse Juno and compile it, but I run in a terminal.
    Your response would be of great help to me and my university project.
    THANKS YOU SO MUCH!
    Fernando.

    ReplyDelete
  18. when i try your code it gives error that: error C2039: 'read' : is not a member of 'cv::VideoCapture'

    ReplyDelete
  19. Hi,
    I started OpenCV week back, I don't know much about OpenCV, I am trying to do it. How can I capture the video, I copied the same image but What I have to do, means which part I should change the program. I am giving the input to the Camera from usb cable but I am not getting

    ReplyDelete
    Replies
    1. Do you want to capture the video from the camera? or from a file?

      Delete
  20. Thank you so much for your tutorials!
    I'm totally new to OpenCV and I had to make use of it for a project for face detection.
    I couldn't even get it to start well by reading other tutorials, but yours was simple and easy to follow!

    Now that I can get it to run and capture from a webcam, it's a good start!
    I hope you'll continue with more tutorials, cheers!

    ReplyDelete
  21. Thank you for your tutorials.

    One question: Would it not be better in the loop-forevers in beach of these routines if the statement "Mat frame;" were outside the while loop.

    ReplyDelete
    Replies
    1. Good suggestion!! That will enhance the performance

      Delete
  22. hello,

    I connect my sony camera to my laptop with a HDMI cable. And in the VideoCapture constructor I put 1. I get this error HIGHGUI ERROR: V4L: index 1 is not correct!

    ReplyDelete
  23. Hi, thanks for all the tutorials.
    I am new to OpenCV and I am currently trying to detect a person's gender through a webcam video. I can't seem to get the OpenCV Gender Classification (Fisherfaces) demo to work, and I was hoping that you could help. I am using Visual Studio 2010, C++. Currently, I only have a working face detection program.

    Demo: http://docs.opencv.org/trunk/modules/contrib/doc/facerec/tutorial/facerec_gender_classification.html

    I hope you can provide a tutorial on gender classification through a video if it's possible.
    Thanks for the helpful tutorials once again!

    ReplyDelete
  24. Hi, i try your tutorial "capture video from file"
    i used opencv 2.1, visual studio 2008 and windows 32 bit.
    But i doesn't work and have may errors.
    So i change the header from #include "opencv2/highgui/highgui.hpp" to #include "highgui.h"
    but its still have 1 error >>error C2039: 'read' : is not a member of 'cv::VideoCapture'
    Could you help me resolve this?

    ReplyDelete
    Replies
    1. My program is written in OpenCV/C++. It seems that you are using OpenCV/C.

      Delete
    2. I am using OpenCV version 2.4.9 and at the beginning of cpp file in Visual Studio 2013 I have this:

      #include
      #include
      #include "opencv2/core/core.hpp"
      #include "opencv2/features2d/features2d.hpp"
      #include "opencv2/highgui/highgui.hpp"
      #include "opencv2/calib3d/calib3d.hpp"

      Delete
  25. Hi Fernando ..When I run code it works fine the build is successful.. but the camera console just flashes and closes without showing any thing . I get The program '[4124] try.exe: Native' has exited with code 0 (0x0). in my output. What can the problem possibly be is it because of my webcam ? I tried opencv facedetection code asswell but in the console window it say no frames grabbed break! .Thanks in advance :)

    ReplyDelete
  26. Hello Fernando! Thank you for your tutorials...Am new in Opencv although am good in C++..Now am learning through your tutorials ...But how can i find ROI (region of interest) for example the eye or Iris from the captured video using openCV?Thanks

    ReplyDelete
  27. Hi! This tutorial has been so helpful, thank you! I was wondering, how do you set/specify the width and height of the webcam. Mine seems to be performing at 160x120 ..... would love to have it perform at 640x480

    ReplyDelete
  28. Why we needn't release the hold resource. Like this capture.release(); capture is the type of VideoCapture. My email:jesse_deng@163.com

    ReplyDelete
  29. Hey.. I have a problem. Cannot read a frame from video stream. What could be the possible reasons??

    ReplyDelete
  30. Hello, if i want to use the Dlink DCS-930L camera in opencv, how can i write the code.....

    ReplyDelete
  31. i tried to capture image from webcam and display in the window but it is showing window without image.can you give solution for this problem

    using namespace cv;
    int main()
    {
    cvNamedWindow("Window", CV_WINDOW_AUTOSIZE);
    CvCapture* capture =cvCreateCameraCapture(-1);
    if (!capture){
    printf("Error. Cannot capture.");
    }
    else{
    cvNamedWindow("Window", CV_WINDOW_AUTOSIZE);

    while (1){
    IplImage* frame = cvQueryFrame(capture);
    if(!frame){
    printf("Error. Cannot get the frame.");
    break;
    }
    cvShowImage("Window",frame);
    char c = cvWaitKey(33);
    if( c == 27 ) break;
    }
    cvReleaseCapture(&capture);
    cvDestroyWindow("Window");
    }
    return 0;
    }

    ReplyDelete
  32. its not workink for me :( ..its giving error "Error 1 error LNK1104: cannot open file 'opencv_calib3d245d.lib' " HELP PLZZZZ....

    ReplyDelete
  33. hi ..how to conver image frames into videos

    ReplyDelete
  34. how to resolve this ? please help :'(
    Unhandled exception at 0x000007FEE96CA027 (opencv_highgui248d.dll) in ConsoleApplication6.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF.

    ReplyDelete
    Replies
    1. I have the similar problem. Does any one know why? I am using VS 2010 and 32 bit. In debug mode it builds but gives errors of missing lots of dll files in the syswow64 folder. Then I ran it in release mode and received "Unhandled exception at 0x75b8ee1b in ConsoleApplication.exe: 0xC0000005: Access violation reading location 0x00000020.". Thanks.

      Delete
  35. This comment has been removed by the author.

    ReplyDelete
  36. @zaarah batool: I think you are trying to access one variable that not initialize in visua c++, example you have used one VideoCapture but your camera not work so that system generate one error.

    ReplyDelete
  37. is there a C program through which we can access the frames of a video stream?
    i have written a C++ program but i need a C program.

    ReplyDelete
  38. i try the same above program to read a video file (tried with both mp4 & avi) from a file. i am not getting any error,but it is not opening the video.it is showing "cannot open the video file" . In output window it shows "cannot open PDB file".

    ReplyDelete
    Replies
    1. Look at the comment http://opencv-srf.blogspot.com/2011/09/capturing-images-videos.html?showComment=1410567788553#c3391439242547428234

      Delete
  39. Open video from file worked perfectly. Thank You! Just one thing - can't close video window, it always reappears again and again :)
    Windows 7 + Eclipse Kepler + MinGW + OpenCV 4.2.8

    ReplyDelete
    Replies
    1. sir do you have a solution to the error i posted?? it's really urgent..

      Delete
  40. It's giving an error "warning--Error opening File(---/---/modules/highgui/src/cap/ff_mpeg_impl.hpp:545>
    cannot open the video file...
    Is there anything that i'm missing??

    ReplyDelete
    Replies
    1. I also got this error a lot...so tried to run the code via the command line. Just add this code

      if( argc != 2)
      {
      cout <<" Usage: display_image ImageToLoadAndDisplay" << endl;
      return -1;
      }


      VideoCapture cap(argv[1]); // open the video file for reading

      if ( !cap.isOpened() ) // if not success, exit program
      {
      cout << "Cannot open the video file" << endl;
      return -1;
      }

      then go to the command prompt and run the program with the desired argument. It worked for me. Thanks

      Delete
  41. Just tested your program with my webcam. Worked just fine. Thanks a lot. I would like to read/write the pixels of the images as they appear (turn bright spot to white on a black background and scan it for tracking). I am totally new to opencv. Any advice on what I should look for into the documentation?

    ReplyDelete
  42. the Mat frame initialization can stand outside of the while(1) loop

    ReplyDelete
  43. Dear Sir, I am getting an error.
    Error 2 error C2039: 'read' : is not a member of 'cv::VideoCapture'.. Can you please tell me how to get rid of this error. Thanks

    ReplyDelete
  44. This comment has been removed by the author.

    ReplyDelete
  45. it's possible to do live stream with gopro camera into opencv?

    ReplyDelete
  46. This comment has been removed by the author.

    ReplyDelete
  47. This comment has been removed by the author.

    ReplyDelete
  48. Thanks a lot for the tutorials!!. I have a problem, my program builds successfully but it cannot read any frame, I don't think that it's the camera because when I run the next code in C it works well, what could it be?

    #include "opencv2/highgui/highgui.hpp"

    int main(int argc, const char** argv)
    {
    CvCapture* capture;
    IplImage* frame = 0;

    while (true)
    {
    //Read the video stream
    capture = cvCaptureFromCAM(0);
    frame = cvQueryFrame(capture);

    // create a window to display detected faces
    cvNamedWindow("Sample Program", CV_WINDOW_AUTOSIZE);

    // display face detections
    cvShowImage("Sample Program", frame);

    int c = cvWaitKey(10);
    if ((char)c == 27) { exit(0); }

    }

    // clean up and release resources
    cvReleaseImage(&frame);

    return 0;
    }

    ReplyDelete
  49. Hi,

    Thanks for posting.

    I've found a bug in your code.

    The "Mat frame" statement should be outside of the look, otherwise, it raises an exception (at least on my machine with opencv 2.4.9).

    Gil

    ReplyDelete
  50. Hi ad. I have a problem when streaming from webcam. I used your source but it not working. There are some error like this:
    VIDIOC_QUERYMENU: invalid argument
    VIDIOC_QUERYMENU: invalid argument
    libv4l2: error setting pixformat: device or resource busy
    HIGHGUI ERROR: libv4l unable to ioctl S_FMT

    HIGHGUI ERROR: libv4l unable to ioctl VIDIOCSPICT

    anyone did get it. Please help me.

    ReplyDelete
  51. Hi :-)
    Could anyone tell a method to capture all frames of a video?
    Is it possible to achieve using waitkey??

    ReplyDelete
  52. Width an Height are not the desired ones.

    Hi, tanks for the tutorial i am able to capture the frames from the camera. The problem I have is with the size of the frames. I am using a 1294x964 GigE Basler camera, but I always get an 640x480 frame. I have adjust the Area Of Interest of the camera in the Basler Software “Pylon Viewer” to the full image or to a 500x500 square, but the frames are always of the same size, and wen I check again in Pylon Viewer the AOI is again set to 640x480. I have tried setting the width and height as cap.set(CV_CAP_PROP_FRAME_WIDTH,1294) cap.set(CV_CAP_PROP_FRAME_HEIGHT,964) matching the Pylon Viewer setting to get the full image (or 500 and 500 to get only an area) but I get an error informing buffer sizes do not match. Can you help me identifying why this is happening and how can I fix it. Thanks!

    ReplyDelete
  53. This comment has been removed by the author.

    ReplyDelete
  54. Hi, thanks for such a helpful tutorial.
    I have some doubts, firstly, when i tried to capture multiple videos from files, i was able to run only one video, but the other's fps information did get displayed. How can i capture multiple videos efficiently?
    Secondly, I tried to capture video from camera, ad display its fps information. The video was successfully captured, but the fps data was outputted as -1. How to rectify this?
    Thanks.

    ReplyDelete
  55. I'm facing errors as opencv_core245.dll is missing.. i think its the #include "opencv2/highgui/highgui.hpp" file is missing..
    how can i solve this problem? need hlp =(

    ReplyDelete
    Replies
    1. Maybe wrong IDE settings. Check http://opencv-srf.blogspot.sk/2013/05/installing-configuring-opencv-with-vs.html

      Delete
  56. HI I am using this tutorial with raspberry pi camera board (uv4l driver) I have this message with a very small video 64x64 , any idea ?
    ./video_cam
    VIDIOC_QUERYMENU: Invalid argument
    VIDIOC_QUERYMENU: Invalid argument
    VIDIOC_QUERYMENU: Invalid argument
    VIDIOC_QUERYMENU: Invalid argument
    VIDIOC_QUERYMENU: Invalid argument
    VIDIOC_QUERYMENU: Invalid argument
    VIDIOC_QUERYMENU: Invalid argument
    VIDIOC_QUERYMENU: Invalid argument
    Frame size : 64 x 64

    ReplyDelete
  57. Hi Shermal,
    Just curious that when we processed a fast video rate fps=30 for eg, it will have to take some time to process each of the frame and causing the low output. There are two ways that I had understand which is to reduce the fps or use a better PC.

    In a recorded video, do u know how we could sample for eg, every 3rd of the frames will be processed instead of taking all the frames.. If you have some information on this, I would really appreciate if you can share with us.

    THanks
    Zamani

    ReplyDelete
  58. Hey ... I tried running the same code... it showed error while opening the video file... But when i tried opening a video file using cvCaptureFromFile it worked well ... Can you tell me what could be the problem with VideoCapture command??
    Thank you

    ReplyDelete
  59. Man, You are awesome...these tuts are just great...........thanks a million for these

    ReplyDelete
  60. I want to capture 1 frame per second from a video file which has 25 fps.
    I saw on diff forums but solutions were developed by people.
    is there any property in opencv that could be set and serve my purpose?

    ReplyDelete
  61. This comment has been removed by the author.

    ReplyDelete
  62. I have these messages:

    First-chance exception at 0x779d1d05 (ntdll.dll) in prova_video.exe: 0xC0000005: Access violation reading location 0x0263ffff.
    First-chance exception at 0x75dbc42d (KernelBase.dll) in prova_video.exe: 0x00FF00FF: 0xff00ff.

    I searched on Internet but I really don't know how to fix this problem.

    ReplyDelete
  63. You are amazing, so clear and detailed tutorial !
    Thank you so much.

    ReplyDelete