OpenCV 3 and threading on Ubuntu - c++

Can OpenCV be made to work with the following code, modified from here:
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <thread>
using namespace cv;
using namespace std;
void showWindow(std::string const &name, cv::Mat const &img)
{
cv::namedWindow(name, cv::WINDOW_AUTOSIZE);
cv::imshow(name, img);
}
int main( int argc, char** argv )
{
if( argc != 2)
{
cout <<" Usage: display_image ImageToLoadAndDisplay" << endl;
return -1;
}
Mat image;
image = imread(argv[1], CV_LOAD_IMAGE_COLOR);
if(! image.data )
{
cout << "Could not open or find the image" << std::endl ;
return -1;
}
std::thread t1(showWindow, "Display window", image);
t1.join();
waitKey(0);
return 0;
}
Compiled with g++ -std=c++11 -g opencv.cpp -o app `pkg-config --cflags --libs opencv`. My actual example is much more complex, but this is a MCVE.
The program hangs, and pressing CTRL+C in gdb gives me:
Program received signal SIGINT, Interrupt.
0x00007ffff6a7dd4d in nanosleep () at ../sysdeps/unix/syscall-template.S:81
81 ../sysdeps/unix/syscall-template.S: No such file or directory.
(gdb) bt
#0 0x00007ffff6a7dd4d in nanosleep () at ../sysdeps/unix/syscall-template.S:81
#1 0x00007ffff6aaefd4 in usleep (useconds=<optimised out>) at ../sysdeps/unix/sysv/linux/usleep.c:32
#2 0x00007ffff7bafe1e in cvWaitKey () from /usr/local/lib/libopencv_highgui.so.3.2
#3 0x00007ffff7baa2c6 in cv::waitKey(int) () from /usr/local/lib/libopencv_highgui.so.3.2
#4 0x0000000000401970 in main (argc=3, argv=0x7fffffffd418) at opencv.cpp:31
I tried rebuilding with WITH_TBB=ON but it made no difference.

Related

How to solved Segmentation fault when read the next video frame on centos

I run this program on Centos6.8, I always got Segmentation fault (core dumped)
I also used GDB to debug,it says
Program received signal SIGSEGV, Segmentation fault.
memcpy () at ../sysdeps/x86_64/memcpy.S:398
398 movq 48(%rsi), %r13
But when I run this same program on my Ubuntu 18.04, it worked great.
Does anything I miss install on Centos, or I need to change another API to read frame.
BTW, I can read four frames at the beginning, after that, I got Segmentation fault.
Opencv version is 2.4.9
#include <iostream>
#include <math.h>
#include <chrono>
#include <opencv2/opencv.hpp>
#include <fstream>
using namespace std;
using namespace cv;
int main(int argc, char* argv[])
{
Mat image;
int a;
VideoCapture video("15_41_24_24670.avi");
int i = 0;
try{
while(true){
video >> image;
if(image.empty())
break;
cout << i++ <<endl;
}
}
catch(std::exception& e){
std::cerr << "Exception caught : " << e.what() << std::endl;
cout<<"error"<<endl;
return 0;
}
cout<<"successful"<<endl;
return 0;
}
Output:
0
1
2
3
4
5
6
Segmentation fault (core dumped)
Try to set backend for VideoCapture:
VideoCapture video("15_41_24_24670.avi", cv::CAP_FFMPEG);
or
VideoCapture video("15_41_24_24670.avi", cv::CAP_GSTREAMER);
or anything else

OpenCV example compilation results in core dump

I am compiling an example for OpenCV with the following code:
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main( int argc, char** argv )
{
if( argc != 2)
{
cout <<" Usage: display_image ImageToLoadAndDisplay" << endl;
return -1;
}
Mat image;
image = imread(argv[1], CV_LOAD_IMAGE_COLOR); // Read the file
if(! image.data ) // Check for invalid input
{
cout << "Could not open or find the image" << std::endl ;
return -1;
}
namedWindow( "Display window", WINDOW_AUTOSIZE );// Create a window for display.
imshow( "Display window", image ); // Show our image inside it.
waitKey(0); // Wait for a keystroke in the window
return 0;
}
The compilation code is:
g++ -I/usr/local/include/opencv2 `pkg-config --cflags --libs opencv` -L /usr/local/share/OpenCV/3rdparty/lib/ opencv.cpp -o opencv -lopencv_core -lopencv_imgproc -lopencv_highgui -lopencv_features2d -lopencv_imgcodecs
If I omit one of the libraries I add additionally, I get linking errors. When trying to run the program, I get an"Invalid machine code" error. How can that be solved?

Can we use pthread library for opencv C++ programming?

I have implemented a openCV program which can capture frames from video file and process it and create a new file. That is doing for single in file . Now I want for multiple files . then I have an idea about POSIX thread pthread library . Is that is a good or bad idea . Actually when I implement pthreads in opencv program I got some errors like following :
OpenCV Error: Assertion failed (_src.sameSize(_dst) && dcn == scn) in
accumulate, file
/home/satinder/opencv_installation/OpenCV/opencv/modules/imgproc/src/accum.cpp,
line 915
what():
/home/satinder/opencv_installation/OpenCV/opencv/modules/imgproc/src/accum.cpp:915:
error: (-215) _src.sameSize(_dst) && dcn == scn in function accumulate
Aborted (core dumped)
corrupted double-linked list: 0x00007fcd048f73d0 ***
Aborted (core dumped)
seg fault also some time .
Is there any possible way how I can implement multi-threading or equivalent my goal make a program which can get more that one input files for same processing.
FOllowing is my code snapshot :
#include "opencv2/highgui/highgui.hpp"
#include <sys/types.h>
#include <pthread.h>
#include <iostream>
using namespace cv;
using namespace std;
void * VideoCap(void *);
void * VideoCap(void *arg)
{
VideoCapture cap((char *)arg); // open the video file for reading
if ( !cap.isOpened() ) // if not success, exit program
{
cout << "Cannot open the video file" << endl;
exit(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;
}
}
}
int main(int argc, char* argv[])
{
int ret ;
pthread_t th[2];
ret = pthread_create(&th[0] , NULL , VideoCap , (void *)"cctv3.mp4");
if(0 == ret)
{
cout << "Thread 1 is created successfull" << endl;
}
ret = pthread_create(&th[1] , NULL , VideoCap , (void *)"cctv10.mp4");
if(0 == ret)
{
cout << "Thread 2 is created successfull" << endl;
}
pthread_join(th[0] , NULL);
pthread_join(th[1] , NULL);
return 0;
}
There are some problems with your code
namedWindow("MyVideo",CV_WINDOW_AUTOSIZE); //create a window called "MyVideo"
You are creating two threads, so the windows should have different identifiers.
namedWindow((char *)arg, CV_WINDOW_AUTOSIZE);
...
imshow((char *)arg, frame);
Since this question was posted with linux tag, I'm guessing that gtk is relevant. After inserting the directives
#include <gdk/gdk.h>
#include <gtk/gtkmain.h>
at the beginning of the file and then in the main()
pthread_t th[2];
gtk_disable_setlocale();
gtk_init(&argc, &argv);
gdk_threads_init();
New linker / compiler flags are probably needed,
g++ -O -Wall test.cpp -lopencv_highgui -lopencv_core `pkg-config --libs --cflags gdk-2.0 gtk+-2.0`
After these changes there was still an occasional crash, so I added gdk_threads_enter() and gdk_threads_leave(); calls to test if they would help:
gdk_threads_enter();
namedWindow ((char *) arg, CV_WINDOW_AUTOSIZE);
gdk_threads_leave();
Since the crashing was not reproducible, it is hard to tell if those lines have any effect.

Getting camera image from thread

I am using opencv library to obtain video from the built-in webcam. The following code works perfectly well when i put camera logic code into the main function, but it doesn't when i put it into separate thread. The task1() thread stops at cv::VideoCapture capture(0). Meanwhile both task2() and the main thread are executing correctly.
Could someone explain me why opencv logic doesn't work when put into separate thread?
My code:
#include <iostream>
#include <string.h>
#include <thread>
#include <unistd.h>
#include <opencv2/opencv.hpp>
using namespace std;
void task1 (){
cout<<"1st thread ";
cv::Mat frame;
cv::VideoCapture capture(0);
if ( capture.isOpened() == false )
{
cout<<"Failed to open camera";
}
cv::namedWindow("Test OpenCV",1);
while ( true ){
capture >> frame;
cv::imshow("Test OpenCV", frame );
int key = cv::waitKey(1);
if ( key == 27 )
break;
}
}
void task2 (){
int n = 0;
while (1){
cout<<"2nd thread "<<n<<"\n";
sleep(3);
n++;
}
}
int main(int argc, const char * argv[]) {
// insert code here...
cout << "Hello, World!\n";
thread t1(task1);
thread t2(task2);
//t1.join();
//t2.join();
int n = 0;
while (1){
cout<<"main thread "<<n<<"\n";
sleep(1);
n++;
}
return 0;
}
Your code runs as it should for me (without any modifications) and I get the live feed through the task1 thread (using OpenCV 2.4.5).
I added -std=gnu++0x flag for compiler support (otherwise g++ throws an error).
g++ -std=gnu++0x opencv_thread.cpp -o opencv_thread `pkg-config --cflags --libs opencv`
Check my console output here. I added a cout << "1st thread "<< endl; within the while loop in task1.
I think the issue might be specific to some opencv versions as I have seen similar issues in an older version (don't remember which one) and boost threads.
Can you give details about the version you used?. Also try it with 2.4.5.

VideoCapture crashing with opencv2.0

This simple program is crashing at VideoCapture.
My configuration is OpenCV 2.0, MinGW, Windows7
int main()
{
cout<<"reached here"<<endl;
VideoCapture cap;
cap.open("Z:\\snapshot\\streaminput\\video1.avi");
if (!cap.isOpened())
{
cout<<"capture failed"<<endl;
// print error msg
return -1;
}
cout<<"capture successful"<<endl;
Mat frame;
namedWindow("gray",1);
do
{
cap >> frame;
cout<<"got a frame"<<endl;
imshow("gray", frame);
cvWaitKey(300);
}while(1);
//cvDestroyAllWindows();
cout << "Hello world!" << endl;
return 0;
}
CALLSTACK:
#0 002FB4B8 cv::VideoCapture::VideoCapture(int) ()(C:\OpenCV2.0\bin\libhighgui200.dll:??)
#1 77CCE115 ntdll!RtlAllocateMemoryZone() (C:\Windows\system32\ntdll.dll:??)
#2 00000000 0x0022fe78 in ??() (??:??)
PROGRAMOUTPUT(BEFORE CRASH POINT):
capture name is:Z:\snapshot\streaminput\video1.avi
Process returned 255 (0xFF) execution time : 9.874
Press any key to continue.
Any idea what is wrong in this program or in configuration??