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

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?

Related

Error while capturing video for a pre-defined time period

This program captures video until I press Esc. But I need to modify this program and capture video for 30s.
After recording the video it plays very fast and the video length reduces. I tried to add waitKey at the end, but it still doesn't work. After recording the video length should be the same. How can I do that? Any suggestions?
int main( int argc, const char** argv )
{
using namespace std;
using namespace cv;
VideoCapture cap(0);
while(!(cap.isOpened() && cap.grab()))
{
cout << "Camera not ready" << endl;
}
VideoWriter Writer("D:/MyVideo.avi", CV_FOURCC('P','I','M','1'),20,Size(640,480), true);
while (waitKey(30)!= 27)
{
Mat frame;
cap >> frame;
Writer.write(frame);
imshow("D:/MyVideo", frame);
}
}
int64 t0 = cv::getTickCount();
while (waitKey(30)!= 27)
{
Mat frame;
cap >> frame; // read a new frame from video
Writer.write(frame); //writer the frame into the file
double t = (cv::getTickCount() - t0) / cv::getTickFrequency();
if (t > 30)
break;
...
// now, we need to adjust to the desired framerate of 20fps,
// so we need to sleep for 1000/20 = 50 milliseconds
// either have a window, and use waitKey():
// imshow("lalala", frame);
// waitKey(50);
// or just sleep(), unfortunately system dependant ;(
// win:
// Sleep(50);
// linux, etc.:
// usleep(50);
}

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.

OpenCV -- Function to grab frame

I'm trying to create a function that gives the frame at the moment the function is called. So when i call the function, it should give the picture of the object that is in front of the camera at the moment the function is called.
I have been trying for hours, but i can't succeed. Anyone?
main file:
#include "camera.h"
#include <iostream>
#include <unistd.h>
int main(int argc, const char *argv[])
{
Camera cam;
cam.setVideoSource(0);
cv::Mat image;
cv::Mat image2;
cam.openCamera();
cam.grabFrame(image); // grap first frame
sleep(5); // wait 5 seconds
cam.grabFrame(image2); // capture seconds frame
cv::namedWindow("1",CV_WINDOW_KEEPRATIO);
cv::imshow("1",image);
cv::namedWindow("2",CV_WINDOW_KEEPRATIO);
cv::imshow("2",image2);
cv::waitKey();
return 0;
}
camera.h file
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/core/core.hpp>
class Camera{
private:
int videoSource; //video source
cv::VideoCapture cap; //capture of camera
public:
//constructor default videoSourceNumber
Camera() : videoSource(0) {};
//Setter: videoSourceNumber
void setVideoSource(int sourceNumber){
videoSource = sourceNumber;
}
//function OPEN CAMERA
//opens the video capture
//returns true if successfull
bool openCamera() {
cap.open(videoSource);
if (!cap.isOpened()){
std::cout << "---- Error ----" << std::endl;
return false;
}
return true;
}
//function GRAB FRAME
//grabs the frame of the video capture
//returns true if successfull
bool grabFrame(cv::Mat& cameraFrame){
cap >> cameraFrame;
if (cameraFrame.empty()){
std::cout << "---- Error ----" << std::endl;
return false;
}
return true;
}
};
A somewhat unsatisfying solution:
//function GRAB FRAME
//grabs the frame of the video capture
//returns true if successfull
bool grabFrame(cv::Mat& cameraFrame){
int attempts = 0;
do {
cap >> cameraFrame;
attempts++;
} while (cameraFrame.empty() && attempts < 10);
if (cameraFrame.empty()){
std::cout << "---- Error ----" << std::endl;
return false;
}
return true;
}
I also played with this for a while and could not find a solution. My instinct was to give the camera more "warm-up" time before asking for the first frame. A sleep of 10 seconds seems to do so reliably, but that is not acceptable. If I don't give it any sleep before the first grabFrame() call, the while loop I added only seems to run twice.
Credit to: https://stackoverflow.com/a/9285151/2518451

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

MJPEG network stream to OpenCV 2

Can anyone explain to me why this code below does not work?
#include "opencv/cv.h"
#include "opencv/highgui.h"
#include <iostream>
int main(int, char**) {
cv::VideoCapture vcap;
cv::Mat image;
const std::string videoStreamAddress = "http://hg55.no-ip.org/mjpg/video.mjpg";
//Yes, this stream does work! Try to paste it into your browser...
//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();
}
cv::imshow("Output Window", image);
if(cv::waitKey(1) >= 0) break;
}
}
This code does cannot open the stream...
The code is based on some code in this thread: OpenCV with Network Cameras
The OpenCV 1 code here works without any problem for me.
Thank you very much in advance
I tried to create a new project with Visual Studio 2010 and OpenCV 2.2, instead of OpenCV 2.3.1.
This solved all my problems!

Resources