Ubuntu Illegal Instruction opencv - c++

I recently installed opencv on Ubuntu 12.04.5 from the repository using this command.
sudo apt-get install libopencv-dev python-opencv
When I try to run the following code to confirm that it works properly I get an Illegal instruction (it compiled fine).
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include<iostream>
using namespace std;
int main(){
cv::Mat img;
img = cv::imread("RO.ppm");
cout << img.size() << endl;
return 0;
}
I compiled using this command (due to undefined reference errors).
g++ -o test test.cpp $(pkg-config opencv --cflags --libs)
Update: Commenting out the cout line does not change the result and I've triple checked that RO.ppm exists in this directory (even if it didn't imread doesn't throw an error with illegal or not found input in my experience). I guess my question is two-fold what causes illegal instruction errors and how do I fix it?

You can't cout cv::Size directly without overloading '<<' operator for cv::Size. Instead you can get rows and columns from cv::Size and multiply them in order to get total size of the image:
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include<iostream>
using namespace std;
int main(){
cv::Mat img;
img = cv::imread("RO.ppm");
cv::Size img_size = img.size();
int cols = img_size.width;
int rows = img_size.height;
cout << "image size: " << rows*cols << endl;
return 0;
}
See this similar post for usage of cv::Size.

Related

OpenCV C++ cannot open video unless program is run as root

I'm trying to open a video file in Opencv C++, but it doesn't work in a weird way.
I'm on Fedora, and opencv is installed through dnf's opencv-devel package.
Here is the test code I'm using :
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/imgcodecs/imgcodecs.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/videoio/videoio.hpp>
int main(int argc, char *argv[])
{
std::string imagePath = "/home/me/picture.png";
cv::Mat image = cv::imread(imagePath);
std::cout << image << std::endl;
std::string videoPath = "/home/me/video.mp4";
cv::VideoCapture cap{ videoPath };
if(!cap.isOpened())
{
std::cout << "Error while opening video" << std::endl;
return -1;
}
cv::Mat startFrame;
cap >> startFrame;
std::cout << startFrame;
cap.release();
return 0;
}
Then, I Compile it with the libraries:
g++ -c -Wall -Wno-unknown-pragmas -I/usr/include/opencv4/ -o dist/obj/main.o src/main.cpp
g++ -lopencv_core -lopencv_highgui -lopencv_imgcodecs -lopencv_imgproc -lopencv_videoio dist/obj/main.o -o dist/bin/main
And when I run it, the image is read fine, but the video shows an error.
However, when I run it as sudo, the video reads just fine. I searched around a lot and couldn't find someone with a similar problem, so I'm posting this here.
Also, the python version works fine, so it shouldn'ttm be a codec problem.

How to compile/run a cpp file in mac

I downloaded a webcam_face_pose_ex.cpp file from GitHub and now i want to compile and run it on my mac.
#include <dlib/opencv.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <dlib/image_processing/frontal_face_detector.h>
#include <dlib/image_processing/render_face_detections.h>
#include <dlib/image_processing.h>
#include <dlib/gui_widgets.h>
#include <X11/Xlib.h>
using namespace dlib;
using namespace std;
int main()
{
try
{
cv::VideoCapture cap(0);
if (!cap.isOpened())
{
cerr << "Unable to connect to camera" << endl;
return 1;
}
image_window win;
// Load face detection and pose estimation models.
frontal_face_detector detector = get_frontal_face_detector();
shape_predictor pose_model;
deserialize("shape_predictor_68_face_landmarks.dat") >> pose_model;
// Grab and process frames until the main window is closed by the user.
while(!win.is_closed())
{
// Grab a frame
cv::Mat temp;
if (!cap.read(temp))
{
break;
}
// Turn OpenCV's Mat into something dlib can deal with. Note that this just
// wraps the Mat object, it doesn't copy anything. So cimg is only valid as
// long as temp is valid. Also don't do anything to temp that would cause it
// to reallocate the memory which stores the image as that will make cimg
// contain dangling pointers. This basically means you shouldn't modify temp
// while using cimg.
cv_image<bgr_pixel> cimg(temp);
// Detect faces
std::vector<rectangle> faces = detector(cimg);
// Find the pose of each face.
std::vector<full_object_detection> shapes;
for (unsigned long i = 0; i < faces.size(); ++i)
shapes.push_back(pose_model(cimg, faces[i]));
// Display it all on the screen
win.clear_overlay();
win.set_image(cimg);
win.add_overlay(render_face_detections(shapes));
}
}
catch(serialization_error& e)
{
cout << "You need dlib's default face landmarking model file to run this example." << endl;
cout << "You can get it from the following URL: " << endl;
cout << " http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2" << endl;
cout << endl << e.what() << endl;
}
catch(exception& e)
{
cout << e.what() << endl;
}
}
I tried g++ webcam_face_pose_ex.cpp command but I get:
webcam_face_pose_ex.cpp:30:10: fatal error: 'dlib/opencv.h' file not found
#include <dlib/opencv.h>
^~~~~~~~~~~~~~~
1 error generated.
Was Wondering what I could do to fix this?
The Example File Is Not Meant to be Compiled Using g++
Read the following to learn a bit about the -I flag and #include statements:
The webcam_face_pose_ex.cpp is part of a larger project and you won't be able to compile it on its own because it depends on other files. The #include directive specifies that in order to compile this program, code from the file specified by #includemust be compiled first. This means the entire dlib must be downloaded before compiling webcam_face_pose_ex.cpp. This project also requires opencv2 so we can download it and place the opencv2 folder in the dlib project folder.
Now we can open terminal and change directory into the dlib project folder and compile the file using the following command:
g++ -I. examples/webcam_face_pose_ex.cpp
Note we're specifying the directory of where to find the files specified by #include using the -I parameter as -I. this means to search the current working directory for the files. There it will find the dlib folder and dlib/opencv.h.
How ever, this isn't enough. When you execute the command, you'll encounter an error opencv2/opencv_modules.hpp: No such file or directory.
Solution
The dlib project documentation states that the examples should be built using cmake. Make sure to use cmake to compile the examples.

Why cv::imread return NULL after include tensorflow's header

I am using the tensorflow c++ API in my code. And I found when I load image from files the image is NULL. Then I write a test code to find the reason.
Here is my test code:
#include "opencv2/opencv.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
using namespace cv;
using namespace std;
//#include "tensorflow/core/public/session.h"
//#include "tensorflow/core/protobuf/meta_graph.pb.h"
int main()
{
Mat imgtry = imread("lena.jpg");
printf("%dx%d", imgtry.cols, imgtry.rows );
return 0;
}
When I comment tensorflow's header, the output value is 255x255, but once I uncomment the header, the output value is 0x0. Why ???
The problem seems change slightly after I revised the sequence of link library. At first, I link the tensorflow_cc and tensorflow_frameworok and then the opencv's libriries. Now, I put the tensorflow's libraries after the opencv and the let corresponding include directory as the same sequence. Then I can read image normally even uncomment the code in the above code area. But new porblem occured.
#include "opencv2/opencv.hpp"
#include "opencv2/imgcodecs.hpp"
//it's ok.
#include "tensorflow/core/public/session.h"
#include "tensorflow/core/protobuf/meta_graph.pb.h"
using namespace std;
int main()
{
cv::Mat img;
img = cv::imread("lena.jpg");
if(img.empty() == true) {
cout << "Error!" << endl;
exit(1);
}
cout << "ok!" << endl;
//uncomment this, the img is always emtpy!!!
// tensorflow::SessionOptions sessOptions;
// sessOptions.config.mutable_gpu_options()->set_allow_growth(true);
// auto session = tensorflow::NewSession(sessOptions);
// if(session == nullptr) {
// cout << "Could not create Tensorflow session." << endl;
// exit(1);
// }
return 0;
}
It's a known bug
Feel free to update this Community Wiki answer with Workaround / Solution / Bug status / Etc...

Unhandled exception in Visual studio 2012 opencv

I configured Opencv 2.4.13 in my visual studio 2012. I used the pre-compiled version of opencv, so I didn't compile nothing. By the way, I setted everything ( I followed tutorial in internet) and my simple programs (such as "show an image") work well. So my OpenCv are installed and they are working.
Now, I try to execute this simple program: I read a video and then i take first frame and use SIFT detector and descriptor on it.
My visual studio stops to work when I arrive in SIFT detector line. This is my code:
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/nonfree/features2d.hpp> // SIFT
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <string>
#include <iomanip>
#include <stdlib.h>
#include "Histogram.hpp"
#include "Util.hpp"
using namespace std;
using namespace cv;
int main()
{
VideoCapture video;
Mat frame;
int i = 0;
SiftFeatureDetector siftDetector;
SiftDescriptorExtractor siftDescriptor;
vector<KeyPoint> siftKeypoints;
FileStorage fs("keypointDescriptors.yml", FileStorage::WRITE);
string frameName = "";
string frameStringNumber;
ostringstream convert;
Mat_<float> descriptors;
// Apro il video
try {
video.open("person15_walking_d1_uncomp.avi");
}
catch (Exception ex) {
cout << ex.msg;
return -1;
}
video.read(frame);
siftDetector.detect(frame, siftKeypoints);
siftDescriptor.compute(frame, siftKeypoints, descriptors);
waitKey(0);
return 0;
}
The error is:
Unhandled exception in 0x0085370A (opencv_imgproc2413d.dll) in ConsoleApplication4.exe: 0xC000001D: Illegal Instruction.

Trying to compile OpenCV program but returns "cannot find -lippicv" (Complete linux beginner)

So I have OpenCV 3.1.0 set up on my computer running on Ubuntu 16.04 and I'm trying to run some very simple code to try and test OpenCV and whilst it recognises the opencv #include files, I continue to have compiler errors.
Here is my C++ code:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
using namespace cv;
int main(int argc, char** argv) {
Mat color = imread("lena.jpg");
Mat gray = imread("lena.jpg",0);
imwrite("lenaGray.jpg", gray);
int myRow = color.cols-1;
int myCol = color.rows-1;
Vec3b pixel = color.at<Vec3b>(myRow, myCol);
cout << "Pixel value (B,G,R): (" << (int)pixel[0] << "," << (int)pixel[1] << "," << (int)pixel[2] << ")" << endl;
imshow("Lena BGR", color);
imshow("Lena Gray", gray);
waitKey(0);
return 0;
}
And I attempt to compile it on the Linux terminal as such:
g++ `pkg-config opencv --cflags --libs` main.cpp -o main
And this is the error that's returned:
/usr/bin/ld: cannot find -lippicv
collect2: error: ld returned 1 exit status
As the title said, I am a complete beginner at the Linux operating system whilst I am relatively competent at using the OpenCV library. I simply want to be able to use the OpenCV library and I am unable to with this error and I am very frustrated with it.
Thanks in advance for any help!