Why is there only 414bytes in my mp4 file? (Xcode)(C++) - c++

I designed a program that can record video from webcam by using OpenCV. However, when I check the saved file, I found out that there is only 414 bytes in it.
#include "cv.h"
#include "cxcore.h"
#include "highgui.h"
#include <iostream>
#define NUM_FRAME 300
using namespace std;
int main()
{
CvCapture* capture=cvCaptureFromCAM(-1);
CvVideoWriter* video=0;
IplImage* frame=NULL;
int n;
if(!capture)
{
cout<<"Can not open the camera."<<endl;
return -1;
}
else
{
frame=cvQueryFrame(capture);
video=cvCreateVideoWriter("camera.mp4", CV_FOURCC('D', 'I', 'V', 'X'), 10, cvSize(frame->width,frame->height),1);
if(video)
{
cout<<"VideoWriter has created."<<endl;
}
cvNamedWindow("Camera Video",1);
int i = 0;
while(i <= NUM_FRAME)
{
frame=cvQueryFrame(capture);
if(!frame)
{
cout<<"Can not get frame from the capture."<<endl;
break;
}
n=cvWriteFrame(video,frame);
cout<<n<<endl;
i++;
if(cvWaitKey(2)>0)
break;
}
cvReleaseVideoWriter(&video);
cvReleaseCapture(&capture);
}
return 0;
}
Here is codes of my program. Is anything wrong with the code?

there's no divx codec installed on your machine.
in this case, VideoWriter only writes the mp4 header, and fails silently.
"Is anything wrong with the code ?"
not really. but you should not use the old c-api (IplImages, cv*Functions) any more. it won't be supported in the very near future.

Related

OpenCV haarcascades loading is NOT working at all

I'm using visual studio 2019 with OpenCV 4.4.0
every thing was great but when i want to start face detection the cascade classifiar doesn't load the haarcascade
you also have to know that i installed openCV in the c partition and this is a simple code
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <opencv2\opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <Windows.h>
#include <vector>
#include <stdio.h>
using namespace std;
using namespace cv;
int main()
{
VideoCapture cam(0);
Mat img;
CascadeClassifier detector;
vector<Rect> faces;
Point p[2];
bool cap = false;
if (!detector.load("c:\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_default.xml"))
{
cout << "Image Detector Doesn't work\n";
return EXIT_FAILURE;
}
if (!cam.isOpened())
{
cout << "Can't Open Camera\n";
return EXIT_FAILURE;
}
while (!cap)
{
cam.read(img);
imshow("Cam", img);
waitKey(0);
if (GetAsyncKeyState(VK_ESCAPE))
cap = true;
}
destroyWindow("Cam");
cout << "Detecting Face...\n";
detector.detectMultiScale(img, faces);
for (int i = 0; i < faces.size(); i++)
{
p[0] = Point(faces[i].x,faces[i].y);
p[1] = Point(faces[i].x + faces[i].height,faces[i].y + faces[i].width);
rectangle(img,p[0],p[1],Scalar(0,0,255),3);
}
imwrite("Result.jpg",img);
return EXIT_SUCCESS;
}
this code doesn't load the haarcascade and it returns "can't load" in the cmd
so i really need help with and thanks for all
\ is used as escape sequence in C++ string literals.
Therefore, you should use \\ to put a character \ in them.
if (!dec.load("c:\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_default.xml"))

Can't open HTTP stream: Error opening file (../cap_ffmpeg_impl.hpp:529)

Here is my link format to HTTP stream(user, password and address was changed to dummy):
http://username:password#192.168.0.104:8093/axis-cgi/mjpg/video.cgi
This stream works perfectly in VLC. However, I can't open it using OpenCV library.
Here is my code:
#include <iostream>
#include "opencv2/opencv.hpp"
using namespace std;
using namespace cv;
int main()
{
VideoCapture cap;
const string videoStreamAddress = "http://username:password#192.168.0.104:8093/axis-cgi/mjpg/video.cgi";
cap.open(videoStreamAddress);
if (!cap.isOpened())
{
cout << endl << "Videostream not found !" << endl;
system("pause");
return 0;
}
Mat frame;
while(1)
{
cap >> frame;
if (frame.empty())
break;
imshow("IPcamera", frame);
int c = waitKey(1);
if (c == 27)
{
break;
}
}
waitKey(0);
return 0;
}
This gives me an error:
warning: Error opening file (../../modules/highgui/src/cap_ffmpeg_impl.hpp:529)
which points to:
bool CvCapture_FFMPEG::open( const char* _filename )
{
unsigned i;
bool valid = false;
close();
#if LIBAVFORMAT_BUILD >= CALC_FFMPEG_VERSION(52, 111, 0)
int err = avformat_open_input(&ic, _filename, NULL, NULL);
#else
int err = av_open_input_file(&ic, _filename, NULL, 0, NULL);
#endif
if (err < 0)
{
CV_WARN("Error opening file");
goto exit_func;
}
...
What could be a problem?
Did you try opening a video file in your machine using Videocapture? (Just add the path to the video file to the place where you've put the URL) I assume that it fails in the same way.
So this is a problem with ffmpeg. You'll need to build OpenCV yourself with ffmpeg support. (Do some search on gstreamer as well. I'm not much familiar with that).
Also you can try using another software like ManyCam in the middle. It enables you to read the stream easily in the same way you are reading from a webcam.

delay in ouput of combined c++ program

i have two programs in c++. one is to communicate with arduino(pgm1),while the other is an openCV program reading a webcam(pgm2). independently, they work at moral speed.
if we open them simultaneously in different terminals they work perfect.i wanted to join them as a single program, i tried a program (pgm3). i can get images perfectly in real time.. but the data from arduino delays about 7-10 seconds. unfortunately i know only c/c++/embedded c. so kindly refer me a solution in any one of these languages
pgm1
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
char ch;
ifstream f;
f.open("/dev/ttyACM0");
while (f.get(ch))
{
cout<<ch;
if(ch=='#')
cout<<endl;
}
return 0;
pgm2
#include "opencv2/objdetect.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include <iostream>
#include <stdio.h>
using namespace std;
using namespace cv;
/** Function Headers */
String window_name = "webcam c170 preview";
/** #function main */
int main( void )
{
VideoCapture capture;
Mat frame;
capture.open( 1 );
if ( ! capture.isOpened() ) { printf("--(!)Error opening video capture\n"); return -1; }
while ( capture.read(frame) )
{
if( frame.empty() )
{
printf(" --(!) No captured frame -- Break!");
break;
}
//-- 3. show frames
imshow( window_name, frame );
int c = waitKey(30);
if( (char)c == 27 ) { break; } // escape
}
return 0;
}
}
pgm3
#include "opencv2/objdetect.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include<fstream>
using namespace std;
using namespace cv;
void spi_read(void);
/** Global variables */
char ch;
ifstream f;
String window_name = "webcam c170 preview";
/** #function main */
int main( void )
{
VideoCapture capture;
Mat frame;
f.open("/dev/ttyACM0");
capture.open( 1 );
if ( ! capture.isOpened() ) { printf("--(!)Error opening video capture\n"); return -1; }
while ( capture.read(frame) )
{
if( frame.empty() )
{
printf(" --(!) No captured frame -- Break!");
break;
}
//-- 3. show frames
imshow( window_name, frame );
int c = waitKey(30);
if( (char)c == 27 ) { break; } // escape
spi_read();
}
return 0;
}
void spi_read()
{
String str_spi;
do
{
f.get(ch);
str_spi=str_spi+ch;
}while(ch!='#');
cout<<str_spi<<endl;
}
Do not just merge to code into one function - of course it will cause your second program to "delay" - because its starts to execute after ur previos code is done.
You should create separate thread to simulate ur pgm1/pgm2 programs and then maybe process data received by them in ur main thread - depending on your needs.
Most straighforward solution using boost/thread:
void do_what_pgm1_does() {..}
void do_what_pgm2_does() {..}
int main()
{
boost::thread t1(do_what_pgm1_does);
boost::thread t2(do_what_pgm2_does);
t1.join();
t2.join();
}
this will give you similar execution as you had with 2 processes.

Storing and retrieving IplImages from vector?

I want to store IplImage's ( grabbed from a video file) into a vector and then playback from this iplimage vector.
#include <iostream>
#include "highgui.h"
using namespace std;
int main()
{
CvCapture* capture=cvCreateFileCapture("D:\\Video\\Hands tracking.avi");
vector<IplImage*> imagesNames[2];
//playing video
while(1)
{
IplImage* img=cvQueryFrame(capture);
cvShowImage("Video Opencv example nd testing purpose",img);
imagesNames[0].push_back(img);
char c = cvWaitKey(30);
if(c==27) break;
}
cvDestroyWindow( "Video Opencv example nd testing purpose" );
cvReleaseCapture(&capture);
// play back grabbed IplImages
for(unsigned i=0; imagesNames[0].size();i++)
{
cvShowImage("PlayBack from IplImages vector",imagesNames[0][i]);
char c = cvWaitKey(30);
if(c==27) break;
}
return 0;
}
But the playback part of the above program is not working and showing error at runtime.
#include <iostream>
#include "highgui.h"
using namespace std;
int main()
{
CvCapture* capture=cvCreateFileCapture("D:\\Video\\Hands tracking.avi");
vector<IplImage*> imagesNames;
//playing video
while(1)
{
IplImage* img=cvQueryFrame(capture);
cvShowImage("Video Opencv example nd testing purpose",img);
imagesNames.push_back(img);
char c = cvWaitKey(30);
if(c==27)
break;
}
cvDestroyWindow( "Video Opencv example nd testing purpose" );
cvReleaseCapture(&capture);
// play back grabbed IplImages
for(unsigned i=0; i < imagesNames.size();i++)
{
cvShowImage("PlayBack from IplImages vector",imagesNames[i]);
char c = cvWaitKey(30);
if(c==27)
break;
}
return 0;
}

Why does OpenCV emit "Bad flag in unknown function" for this code?

I have been trying to get a real basic video player working using the Open CV API. Everything seems to run smoothly until the end of a video clip, then i get this error:
OpenCV Error: Bad flag in unknown function, file ........\ocv\opencv\modules\core\src\array.cpp
This creates a break in the code at imshow("video", frame), i find this wierd as this is the part that effectively plays the video so why does it only kick up a fuss at the end of the clip?? I found that it seems to give me this error in the last 90% of every video i play so at the moment im working around it by telling it to stop once 90% of the clip has played but this isnt very good programming so can anyone send some suggestions/help?
I have looked at other peoples post on this matter and none of the solution suggested have worked for me as of yet.
Heres my code...its only an experimentation piece so im sorry if its a bit messy:
Thanks for any help in advance
#include <cv.h>
#include <cxcore.h>
#include <highgui.h>
#include <direct.h>
#include <iostream>
using namespace cv;
void onTrackBarSlide(int);
double the_next_play_frame;
VideoCapture video("test.MOV"); // open the video file
int main(int, char**)
{
if(!video.isOpened()) // check if we succeeded
{
return -1;
}
int no_of_frames = video.get(CV_CAP_PROP_FRAME_COUNT); //total number of frames in video
std::cout << no_of_frames << std::endl;
std::cout << video.get(CV_CAP_PROP_FPS) << std::endl;
namedWindow("Video", 1);
cvCreateTrackbar("trackbar", "Video", 0, 40, onTrackBarSlide);
double stop_at = no_of_frames * 0.999;
for(;;){
if(the_next_play_frame >= double(stop_at))
{
break;
}
Mat frame;
video >> frame; // get a new frame from camera
imshow("Video", frame); // <---------- place where break/error occurs
if(waitKey(30) >= 0)
{
break;
}
}
return 0;
}
void onTrackBarSlide(int pos)
{
std::cout << getTrackbarPos("trackbar", "Video") << std::endl;
double frameratio = video.get(CV_CAP_PROP_FRAME_COUNT)/40; //10005 is the maximum value the slider can actual hold
double next_play_frame = frameratio * getTrackbarPos("trackbar", "Video");
video.set(CV_CAP_PROP_POS_FRAMES,next_play_frame);
the_next_play_frame = next_play_frame;
}
VideoCapture video("test.MOV"); // open the video file
int main(int, char**)
{
if(!video.isOpened()) // check if we succeeded
{
return -1;
}
}
Try put the VideoCapture instantiation inside main.
int main(){
VideoCapture video("test.MOV"); // open the video file
...
}