OpenCV - Play AVI File - opencv

I am trying to play in avi file using opencv c++ in ubuntu but i am getting no output. The code im using is a standard code that i found online that is used to play an avi video but im seeing no output. And yes the video is in the same directory as my src code folder. The only thing im seeing is that on the first iteration of the while loop, frame is empty and hence breaks. but i do not know why it is happening as the video is working on vlc. I would really appreciate some help here as i have been stuck on it for the past 4-5 hours.
#include "cv.h" // include it to used Main OpenCV functions.
#include "highgui.h" //include it to use GUI functions.
int main(int argc, char** argv)
{
cvNamedWindow("Example3", CV_WINDOW_AUTOSIZE);
//CvCapture* capture = cvCreateFileCapture("20051210-w50s.flv");
CvCapture* capture = cvCreateFileCapture("tree.avi");
/* if(!capture)
{
std::cout <<"Video Not Opened\n";
return -1;
}*/
IplImage* frame = NULL;
while(1) {
frame = cvQueryFrame(capture);
//std::cout << "Inside loop\n";
if (!frame)
break;
cvShowImage("Example3", frame);
char c = cvWaitKey(33);
if (c == 27) break;
}
cvReleaseCapture(&capture);
cvDestroyWindow("Example3");
std::cout << "Hello!";
return 0;
}

Are you running in Debug or release mode?
In openCV 2.4.4 there is only a opencv_ffmpeg244.dll (the release .dll) but not one for debug. try switching to release mode.

Remove the code lines:
char c = cvWaitKey(33);
if (c == 27) break;
and instead of these, just add :
cvWaitKey(33);
May be this could help.Here is the python code, that worked fine for me:
import cv
if __name__ == '__main__':
capture = cv.CreateFileCapture('Wildlife.avi')
loop = True
while(loop):
frame = cv.QueryFrame(capture)
if (frame == None):
break;
cv.ShowImage('Wild Life', frame)
char = cv.WaitKey(33)
if (char != -1):
if (ord(char) == 27):
loop = False
Or this could be helpful.

Related

opencv c++ HSV image channel separation exception

I know this question has been asked a number of times and I'm trying to implement their answers but its causing an exception in my code.
OS: Windows 7
OpenCV: 2.4.9
Here is my code:
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
using namespace cv;
using namespace std;
int main( int argc, char** argv )
{
VideoCapture cap(0); //capture the video from webcam
if ( !cap.isOpened() ) // if not success, exit program
{
cout << "Cannot open the web cam" << endl;
return -1;
}
Mat imgHSV;
_sleep(100); //give the camera a chance to wake up
while (true)
{
Mat imgOriginal;
bool success = cap.read(imgOriginal);
if (!success) //if not success, break loop
{
cout << "Cannot read a frame from video stream" << endl;
break;
}
cvtColor(imgOriginal, imgHSV, COLOR_BGR2HSV); //Convert the captured frame from BGR to HSV
vector<Mat> hsv_planes;
split( imgHSV, hsv_planes );
//hsv_planes[0] // H channel
//hsv_planes[1] // S channel
//hsv_planes[2] // V channel
imshow(thresholded_window, hsg_planes[2]); //show the S channel
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;
}
Exception is thrown on the split line: "Unhandled exception at 0x62B978C9 (opencv_core249.dll) in TrackColour.exe: 0xC0000005: Access violation writing location 0xFEEEFEEE."
I figured out my problem, incase this happens to anyone else.
In VS I was doing a debug build but I was linking to the non debug versions of opencv. Notice in my error message opencv_core249, it should have been opencv_core249d (Note the 'd'). I updated my CV linking to use the debug libraries and it works.
The other opencv calls performed fine using the wrong libraries, something must be unique with split.

Does cvQueryFrame advance the current frame?

I'm trying to learn OpenCV using an O'Reilley book and am finding the sample programs raise as many questions as they answer. In a very basic program to show a video:
#include <highgui.h>
#include <string>
int main( int argc, char** argv){
std::string name = "Example 2";
cvNamedWindow(name.c_str(),CV_WINDOW_AUTOSIZE);
CvCapture* capture = cvCreateFileCapture( argv[1]);
IplImage* frame;
while(1) {
frame = cvQueryFrame( capture );
if ( !frame ) break;
cvShowImage (name.c_str(), frame);
char c = cvWaitKey(33);
if (c == 27) break; //User hits ESC key - ASCII value 27
}
cvReleaseCapture( &capture );
cvDestroyWindow(name.c_str());
}
I find myself wondering why I ever see more than a single frame. Everything I read online about cvQueryFrame says it retrieves the current frame. No where have I seen anything about how/when/where the "current" frame advances.
Does cvQueryFrame act more like reading from a file or stream, in that it reads data and then prepares to read the next piece of data, or does the current frame advance in some other way?

saving an image sequence from video using opencv2

Newbie question and yes I have spent a lot of time sifting through similar questions and Answers with no luck.
What I am trying to do is save frames from a video file in a sequential order. I have managed to save one image using c and I cannot seem to save images after that. I have started using c++ in opencv instead of c and all I can do is view the video and not save any jpg's from it.
I am using opencv2.4.4a on mac if that helps.
below is my c example
#include <stdio.h>
#include <stdlib.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <iostream>
using namespace cv;
using namespace std;
int main (int argc, char** argv)
{
//initializing capture from file
CvCapture * capture = cvCaptureFromAVI ("/example/example.mov");
//Capturing a frame
IplImage* img = 0;
if(!cvGrabFrame(capture)) //capture a frame
{
printf)Could not grab a fram\n\7");
exit(0);
}
img=cvRerieveFrame(capture); //retrieve the captured frame
//writing an image to a file
if (!cvSaveImage("/frames/test.jpg", img))
printf("Could not save: %s\n","test.jpg");
//free resources
cvReleaseCapture(&capture);
}
Thank you in advance
edit to the above.
I have added to the above code which results in an image to be saved with the test.jpg and then gets rewritten with the next frame. How do I tell opencv to not copy over the last image and rename the next frame to test_2.jpg eg, test_1.jpg, test_2.jpg and so on?
double num_frames = cvGetCaptureProperty (capture, CV_CAP_PROP_FRAME_COUNT);
for (int i = 0; i < (int)num_frames; i++)
{
img = cvQueryFrame(capture);
cvSaveImage("frames/test.jpg", img);
}
cvReleaseCapture(&capture);
}
This is my code... I tryed a lot and finally made it
this is c++ using opencv 3... hope it works
#include "opencv2/opencv.hpp"
#include <sstream>
#include <iostream>
using namespace cv;
using namespace std;
Mat frame,img;
int counter;
int main(int,char**)
{
VideoCapture vid("video3.avi");
while (!vid.isOpened())
{
VideoCapture vid("video2.MOV");
cout << "charging" << endl;
waitKey(1000);
}
cout << "Video opened!" << endl;
while(1)
{
stringstream file;
vid.read(frame);
if(frame.empty()) break;
file << "/home/pedro/workspace/videoFrame/Debug/frames/image" << counter << ".jpg";
counter++;
imwrite(file.str(),frame);
char key = waitKey(10);
if ( key == 27)
{break;}
}
}
Use an index that will keep track of the number part in the filename. In the image capturing loop, add the index with the filename and build the final filename.
here is an example :
while(1)
{
cap.read ( frame);
if( frame.empty()) break;
imshow("video", frame);
char filename[80];
sprintf(filename,"C:/Users/cssc/Desktop/testFolder/test_%d.png",i);
imwrite(filename, frame);
i++;
char key = waitKey(10);
if ( key == 27) break;
}
This is my way to do in Python3.0. Have to have CV2 3+ version for it to work.
This function saves images with frequency given.
import cv2
import os
print(cv2.__version__)
# Function to extract frames
def FrameCapture(path,frame_freq):
# Path to video file
video = cv2.VideoCapture(path)
success, image = video.read()
# Number of frames in video
fps = int(video.get(cv2.CAP_PROP_FPS))
length = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
print('FPS:', fps)
print('Extracting every {} frames'.format(frame_freq))
print('Total Frames:', length)
print('Number of Frames Saved:', (length // frame_freq) + 1)
# Directory for saved frames
try:
frame_dir = path.split('.')[0]
os.mkdir(frame_dir)
except FileExistsError:
print('Directory ({}) already exists'.format(frame_dir))
# Used as counter variable
count = 0
# checks whether frames were extracted
success = 1
# vidObj object calls read
# function extract frames
while count < length :
video.set(cv2.CAP_PROP_POS_FRAMES , count)
success, image = video.read()
# Saves the frames with frame-count
cv2.imwrite(frame_dir + "/frame%d.jpg" % count, image)
count = count + frame_freq

After reading multiple frames from a camera, OpenCV suddenly always fails to read frames. How do I diagnose this?

I run a program similar to the one in this question: https://stackoverflow.com/a/8719192/26070
#include <opencv/highgui.h>
#include <iostream>
/** #function main */
int main( int argc, char** argv )
{
cv::VideoCapture vcap;
cv::Mat image;
const std::string videoStreamAddress = "rtsp://192.0.0.1:8081/live.sdp";
//open the video stream and make sure it's opened
if(!vcap.open(videoStreamAddress)) {
std::cout << "Error opening video stream or file" << std::endl;
return -1;
}
for(;;) {
if(!vcap.read(image)) {
std::cout << "No frame" << std::endl;
cv::waitKey(500);
} else {
cv::imshow("Output Window", image);
}
if(cv::waitKey(1) >= 0) break;
}
}
The program runs fine for a certain amount of time (about one minute or so) and then the call to read() (method from cv::VideoCapture) always returns false.
The output is as follows:
[mpeg4 # 00da27a0] ac-tex damaged at 22 7
[mpeg4 # 00da27a0] Error at MB: 309
No frame
No frame
No frame
Note: the first two lines are not always present.
So, how can I determine what the root of the problem is?

OpenCV VideoWriter won't write anything, although cvWriteToAVI does

I'm been trying to capture video from a cam and write it into an AVI file. I'm using Qt 4.8.2 with MSVC 2010 (x86) on Windows 7. I have 2 versions of the code: one using cv::Mat and the other using IplImage*. However, only the IplImage* version is working. Here's my code using cv::Mat:
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
int main() {
VideoCapture* capture2 = new VideoCapture( CV_CAP_DSHOW );
Size size2 = Size(640,480);
int codec = CV_FOURCC('M', 'J', 'P', 'G');
VideoWriter* writer2 = new VideoWriter("video.avi",codec,15,size2);
int a = 100;
Mat frame2;
while ( a > 0 ) {
capture2->read(frame2);
writer2->write(frame2);
a--;
}
writer2->release();
capture2->release();
return 0;
}
And here's the code using IplImage*:
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
int main() {
CvCapture* capture = cvCaptureFromCAM( CV_CAP_DSHOW );
CvSize size = cvSize(640,480);
int codec = CV_FOURCC('M', 'J', 'P', 'G');
CvVideoWriter* writer = cvCreateVideoWriter("video.avi",codec,15,size);
int a = 100;
while ( a > 0 ) {
IplImage* frame = cvQueryFrame( capture );
cvWriteToAVI(writer,frame);
a--;
}
cvReleaseVideoWriter(&writer);
cvReleaseCapture( &capture );
return 0;
}
It's basically the same, or at least it looks like the same thing to me. It reads 100 frames and should write them into "video.avi". It compiles and runs without errors, but the cv::Mat version doesn't write anything, and the IplImage* version works perfectly.
Does someone have any idea on what's going on?
The syntax in Opencv C++ reference is bit different, and here is a working code in C++.
I Just added imshow and waitkey, for checking you can remove them if you want.
int main()
{
VideoCapture* capture2 = new VideoCapture(CV_CAP_DSHOW);
Size size2 = Size(640, 480);
int codec = CV_FOURCC('M', 'J', 'P', 'G');
// Unlike in C, here we use an object of the class VideoWriter//
VideoWriter writer2("video_.avi", codec, 15.0, size2, true);
writer2.open("video_.avi", codec, 15.0, size2, true);
if (writer2.isOpened())
{
int a = 100;
Mat frame2;
while (a > 0)
{
capture2->read(frame2);
imshow("live", frame2);
waitKey(100);
writer2.write(frame2);
a--;
}
}
else
{
cout << "ERROR while opening" << endl;
}
// No Need to release the Writer as the distructor will called automatically
capture2->release();
return 0;
}
I had the same problem over and over again, and none of the solutions I found online helped.
Strange enough, the problem (identified purely with a trial and error method) was with the write permission. Everything worked after I sudo chmod u+rwx the python script.
I have the same problem and after a few time i realize that the input video isn't the same size with the output. Resize the input video may help u.
capture2->read(frame2);
cv::resize(frame2,frame2,cv::Size(640,480);
writer2->write(frame2);

Resources