opencv VideoCapture is blocked in thread - c++

I need some some help with the usage of opencv VideoCapture in another thread.
When I use the VideoCapture in the main thread, it is perfectly fine and it shows the video smoothly. But once I put the code in another thread and expect it do the same thing, it seems the VideoCapture does not work at all.
I made some attempts: if I initialize the VideoCapture with 0 (the default one) as parameter, it gets blocked. But if I don't initialize it
VideoCapture cap;
or use another number
VideoCapture cap(1);
it prints out error message and exits but does not get blocked.
Here is the code:
#include <iostream>
#include <thread>
#include <functional>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
using namespace std;
using namespace cv;
class MyClass {
public:
// display the video
static void display(int i) {
VideoCapture cap(0);
if (!cap.isOpened()) {
cout << "cannot access webcame" << endl;
exit(-1);
}
Mat imgOriginal;
namedWindow("Original", WINDOW_AUTOSIZE);
while (true) {
bool success = cap.read(imgOriginal);
if (!success) {
cout << "fail to read video into mat" << endl;
break;
}
imshow("Original", imgOriginal);
if (waitKey(30) == 27) {
break;
}
}
}
};
int main()
{
//cout << "Hello World!" << endl;
thread myThread(bind(MyClass::display, 0));
myThread.join();
return 0;
}
Very appreciated if anyone can point out where I got it wrong. Thank you.

Related

Cannot read video from file while can read from camera

My problem is that I cannot read from file I tried with .mp4 and .mov using cpp code on windows with library opencv3.4.0. I tried to read from camera it is working.
What could be the reason ?
cv::VideoCapture cap("001.mp4");
// Check if camera opened successfully
if (!cap.isOpened()) {
std::cout << "Error opening video stream or file" << std::endl;
break; //==>hits here
}
/// while below code part works correctly
cv::VideoCapture cap(0);
// Check if camera opened successfully
if (!cap.isOpened()) {
std::cout << "Error opening video stream or file" << std::endl;
break;
}
Copy and try below code, if it doesnt work either. It is completely about your opencv installation or directory mistake.
#include <opencv2/core.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
#include <stdio.h>
#include "opencv2/opencv.hpp"
#include <iostream>
using namespace std;
using namespace cv;
int main(){
VideoCapture cap("videoname.mp4");
if(!cap.isOpened()){
cout << "Error opening video stream or file" << endl;
return -1;
}
while(1){
Mat frame;
cap >> frame;
if (frame.empty())
break;
imshow( "Frame", frame );
char c=(char)waitKey(25);
if(c==27)
break;
}
cap.release();
destroyAllWindows();
return 0;
}

Is it possible to crop raw video before extracting all the frames using OpenCV and C++?

I want to crop a certain area of my raw video before extracting the frames. I don't want to use external cropping video software because I need the video to be raw for processing. Is it possible to crop a certain area before extraction ? I read about ROI for images, is it possible for video too ?
Here's my extraction code that's already working :
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <string>
#include <sstream>
using namespace cv;
using namespace std;
int c = 0;
string int2str(int &);
int main(int argc, char **argv) {
string s;
VideoCapture cap("test_video.mov");
if (!cap.isOpened())
{
cout << "Cannot open the video file" << endl;
return -1;
}
double fps = cap.get(CV_CAP_PROP_FPS);
cout << "Frame per seconds : " << fps << endl;
namedWindow("MyVideo", CV_WINDOW_NORMAL);
resizeWindow("MyVideo", 600, 600);
while (1)
{
Mat frame;
Mat Gray_frame;
bool bSuccess = cap.read(frame);
if (!bSuccess)
{
cout << "Cannot read the frame from video file" << endl;
break;
}
s = int2str(c);
//cout<<("%d\n",frame )<<endl;
c++;
imshow("MyVideo", frame);
imwrite("frame" + s + ".jpg", frame);
if (waitKey(30) == 27)
{
cout << "esc key is pressed by user" << endl;
break;
}
}
return 0;
}
string int2str(int &i) {
string s;
stringstream ss(s);
ss << i;
return ss.str();
}
Still need to crop the video, any advice ?

Extract all video frame from mp4 video using OpenCV and C++

I'm following a tutorial to extract video frames. I've read this question, it doesn't work, also queationfrom Open CV Answer, but the solution is for capturing current frame. I have a 120fps video and want to extract all of them. Here's my code
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <string>
#include <sstream>
using namespace cv;
using namespace std;
int c = 0;
string int2str(int &);
int main(int argc, char **argv) {
string s;
VideoCapture cap("test.mp4"); // video
if (!cap.isOpened())
{
cout << "Cannot open the video file" << endl;
return -1;
}
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;
Mat Gray_frame;
bool bSuccess = cap.read(frame); // read a new frame from video
if (!bSuccess)
{
cout << "Cannot read the frame from video file" << endl;
break;
}
s = int2str(c);
//cout<<("%d\n",frame )<<endl;
c++;
imshow("MyVideo", frame); //show the frame in "MyVideo" window
imwrite("ig" + s + ".jpg", frame);
if (waitKey(30) == 27) //esc key
{
cout << "esc key is pressed by user" << endl;
break;
}
}
return 0;
}
//int to string function
string int2str(int &i) {
string s;
stringstream ss(s);
ss << i;
return ss.str();
}
My problem is, I have a minute video at 120fps. I expected to be able to extract 120 frames. But the extraction went wrong, the video last for 1 minute but I got more than 200 frames stored in my folder. Did I do something wrong in my code ?

Saved video doesn't have the same duration as streamed video from a camera

I have a question about saving a video with openCV in C++ (I'm using Linux Ubuntu).
I was trying to save a stream from open camera for some time. I finally succeeded, but now I have really not many ideas why the saved stream doesn't have the same duration as I was streaming from my camera. When I am streaming for 10 seconds it has only for example 2-3 seconds and looks like it is accelerated.
Does anybody have some clue what could be the problem? Something wrong in my code or maybe computing performance, maybe the system doesn't save every frame?
Thanks for your help.
My code:
#include <stdio.h>
#include <iostream> // for standard I/O
#include <string> // for strings
#include <opencv2/core.hpp> // Basic OpenCV structures (cv::Mat)
#include <opencv2/videoio.hpp> // Video write
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/opencv.hpp"
using namespace std;
using namespace cv;
int main(int argc, char** argv)
{
Mat capture;
VideoCapture cap(0);
if(!cap.isOpened())
{
cout<<"Cannot connect to camera"<<endl;
return -1;
}
namedWindow("Display",CV_WINDOW_AUTOSIZE);
double dWidth = cap.get(CV_CAP_PROP_FRAME_WIDTH);
double dHeight = cap.get(CV_CAP_PROP_FRAME_HEIGHT);
Size frameSize(static_cast<int>(dWidth), static_cast<int>(dHeight));
VideoWriter oVideoWriter ("/home/Stream_video/cpp/Cam/out.avi", CV_FOURCC('P','I','M','1'), 20, frameSize,true);
if ( !oVideoWriter.isOpened() ) {
cout << "ERROR: Failed to write the video" << endl;
return -1;
}
while(true){
Mat frame;
bool bSuccess = cap.read(frame); // read a new frame from video
if (!bSuccess) {
cout << "ERROR: Cannot read a frame from video file" << endl;
break; //if not success, break loop
}
oVideoWriter.write(frame); //writer the frame into the file
imshow("Display", frame);
if (waitKey(10) == 27) {
cout << "esc key is pressed by user" << endl;
break;
}
}
}

Unhandled exception at Canny edge detector

I want to try Canny edge detector, but when I try to start I receive an Unhandled exception:
Unhandled exception at 0x00007FF97F6C8B9C in canny_project.exe: Microsoft C++ exception: cv::Exception at memory location 0x0000002485D89860
Below is the code that I implemented In VS2012.
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
using namespace cv;
int main(int, char**)
{
namedWindow("Edges", CV_WINDOW_NORMAL);
CvCapture* capture = cvCaptureFromCAM(-1);
cv::Mat frame; cv::Mat out; cv::Mat out2;
while (1) {
frame = cvQueryFrame(capture);
GaussianBlur(frame, out, Size(5, 5), 0, 0);
cvtColor(out, out2, CV_BGR2GRAY); // produces out2, a one-channel image (CV_8UC1)
Canny(out2, out2, 100, 200, 3); // the result goes to out2 again,but since it is still one channel it is fine
if (!frame.data) break;
imshow("Edges", out2);
char c = cvWaitKey(33);
if (c == 'c') break;
}
return 0;
}
Thanks in advance
The problem is probably you are using cvCaptureFromCAM wrong.
cvCaptureFromCAM(0) // not -1
Why do you use OpenCV with C-Code? Use VideoCapture instead CvCapture.
Please try this instead and tell me whether images are shown or not and try different device numbers too:
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
using namespace cv;
int main(int, char**)
{
cv::namedWindow("Capture");
int deviceNum = 0; // please try different device numbers too like -1, 1, 2, ...
cv:VideoCapture capture(deviceNum);
cv::Mat frame;
if(!capture.isOpened())
{
std::cout << "Could not open device " << deviceNum << std::endl;
return 0;
}
while (true)
{
capture >> frame; // = cvQueryFrame(capture);
//if (!frame.data) break;
if(frame.empty())
{
std::cout << "could not capture a legal frame" << std::endl;
continue;
//break;
}
cv::imshow("Capture", frame);
char c = cv::waitKey(33);
if (c == 'c') break;
}
std::cout << "press any key to exit" << std::endl;
cv::waitKey(0); // wait until key pressed
return 0;
}
cvCaptureFromCAM(-1) has wrong argument, use 0, if you have just one camera connected. In addition, in C API, when you finished working with video, release CvCapture structure with cvReleaseCapture(), or use Ptr<CvCapture> that calls cvReleaseCapture() automatically in the destructor. Have a try, please, this example, to see if you access your camera properly.