Raspberry Camera compile error: undefined reference to symbol - c++

I am trying to compile a program for the raspberry pi.
But when I run the build in Geany I got this error:
g++ $(pkg-config opencv4 --cflags --libs) -o g++ $(pkg-config raspicam --cflags --libs) -o camera_2 camera_2.cpp (in directory: /home/pi/Desktop)
/usr/bin/ld: /tmp/ccTDUfOT.o: undefined reference to symbol '_ZN2cv6imshowERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEERKNS_11_InputArrayE'
/usr/bin/ld: //usr/local/lib/libopencv_highgui.so.405: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status
Compilation failed.
The camera.cpp file looks like this:
#include <opencv2/opencv.hpp>
#include <raspicam_cv.h>
#include <iostream>
using namespace std;
using namespace cv;
using namespace raspicam;
Mat frame;
void Setup ( int argc,char **argv, RaspiCam_Cv &Camera )
{
Camera.set ( CAP_PROP_FRAME_WIDTH, ( "-w",argc,argv,400 ) );
Camera.set ( CAP_PROP_FRAME_HEIGHT, ( "-h",argc,argv,240 ) );
Camera.set ( CAP_PROP_BRIGHTNESS, ( "-br",argc,argv,50 ) );
Camera.set ( CAP_PROP_CONTRAST ,( "-co",argc,argv,50 ) );
Camera.set ( CAP_PROP_SATURATION, ( "-sa",argc,argv,50 ) );
Camera.set ( CAP_PROP_GAIN, ( "-g",argc,argv ,50 ) );
Camera.set ( CAP_PROP_FPS, ( "-fps",argc,argv,100));
}
int main(int argc,char **argv)
{
RaspiCam_Cv Camera;
Setup(argc, argv, Camera);
cout<<"Connecting to camera"<<endl;
if (!Camera.open())
{
cout<<"Failed to Connect"<<endl;
return -1;
}
cout<<"Camera Id = "<<Camera.getId()<<endl;
Camera.grab();
Camera.retrieve(frame);
imshow("frame", frame);
waitKey();
return 0;
}
So far I have figured that when I remove
Mat frame;
the error does not appear.
The pkg-config file looks like this:
prefix=/usr/local
exec_prefix=${prefix}
libdir=${exec_prefix}/lib
includedir_old=${prefix}/include/opencv4/opencv2
includedir_new=${prefix}/include/opencv4
Name: OpenCV
Description: Open Source Computer Vision Library
Version: 4.5.5
L: -Libs${exec_prefix}/lib -lopencv_calib3d -lopencv_core -lopencv_dnn -lopencv_features2d -lopencv_flann -lopencv_gapi -lopencv_highgui -lopencv_imgcodecs -lopencv_imgproc -lopencv_ml -lopencv_objdetect -lopencv_photo -lopencv_stitching -lopencv_video -lopencv_videoio
Libs.private: -ldl -lm -lpthread -lrt
Cflags: -I${includedir_old} -I${includedir_new}
The command in Geany looks like this:
g++ $(pkg-config opencv4 --cflags --libs) -o g++ $(pkg-config raspicam --cflags --libs) -o %e %f
Do you have any idea what is wrong and what I do have to change?
Thank you

The argument -o g++ is very weird because it will make an output file named g++, which is confusing because that's also the name of your compiler. You probably want to remove that since you already have a -o argument.
Secondly, the order of the different objects/libraries that are getting linked together often matters when you are linking a program. Try putting the calls to pkg-config at the end of the command.

I have solved the error.
I have added two libraries to the command:
g++ $(pkg-config opencv4 --cflags --libs) $(pkg-config raspicam --cflags --libs) -o %e %f -lopencv_highgui -lopencv_core
I wonder why the libraries do not work in the config file.

Related

Get a opencv_gpu function working in Qt5

I have an OpenSUSE 13.2 System with Qt5 and OpenCV installed with cudasupport. The Hardware is an Intel i5 processor with an integrated intel gpu chip and a NVidia GForce 940 M and i have tried to compile this file.
#include <iostream>
#include <time.h>
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/opencv.hpp"
#include "opencv2/gpu/gpu.hpp"
using namespace std;
int main()
{
try
{
cv::Mat dst_mat;
cv::Mat src_host = cv::imread("/home/peter/testCuda/testCuda/GothaOrangerie.JPG", CV_LOAD_IMAGE_GRAYSCALE);
cv::namedWindow("Result",cv::WINDOW_NORMAL);
cv::imshow("Result", src_host);
cv::waitKey();
cv::gpu::GpuMat dst, src;
src.upload(src_host);
clock_t t = clock();
cv::gpu::threshold(src, dst, 128.0, 255.0, CV_THRESH_BINARY);
t = clock() -t;
cv::Mat result_host(dst);
cout << ((float)t)/CLOCKS_PER_SEC << endl;
cv::imshow("Result", result_host);
cv::waitKey();
t = clock();
cv::threshold(src_host, dst_mat, 128.0, 255.0, CV_THRESH_BINARY);
t = clock() -t;
cout << ((float)t)/CLOCKS_PER_SEC << endl;
cv::imshow("Result", dst_mat);
cv::waitKey();
}
catch(const cv::Exception& ex)
{
cout << "Error: " << ex.what() << endl;
}
return 0;
}
The compilation in the shell with
g++ main.cpp -o threshold `pkg-config --cflags --libs opencv` -lopencv_gpu -L/usr/local/cuda-7.5/lib64
works pretty well i can run the small program without any issues. If i try it with the Qt5 IDE it returns me this error.
OpenCV Error: No GPU support (The library is compiled without CUDA support) in mallocPitch, file /home/abuild/rpmbuild/BUILD/opencv-2.4.9/modules/dynamicuda/include/opencv2/dynamicuda/dynamicuda.hpp, line 126
Error: /home/abuild/rpmbuild/BUILD/opencv-2.4.9/modules/dynamicuda/include/opencv2/dynamicuda/dynamicuda.hpp:126: error: (-216) The library is compiled without CUDA support in function mallocPitch
If i run the shellcompiled program with this command
optirun ./threshold
i get the same error.
The .pro File is
#-------------------------------------------------
#
# Project created by QtCreator 2015-10-15T04:02:07
#
#-------------------------------------------------
TARGET = testCuda
LIBS += -L/usr/lib64/
LIBS += -L/usr/local/cuda-7.5/lib64 -lopencv_gpu
LIBS += `pkg-config opencv --cflags --libs`
SOURCES += main.cpp
and the Qt compilation command is
22:58:12: Running steps for project testCuda...
22:58:12: Configuration unchanged, skipping qmake step.
22:58:12: Starting: "/usr/bin/make"
g++ -c -pipe -O2 -Wall -W -D_REENTRANT -DQT_NO_DEBUG -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED -I/usr/share/qt4/mkspecs/linux-g++ -I../testCuda -I/usr/include/QtCore -I/usr/include/QtGui -I/usr/include -I. -I../testCuda -I. -o main.o ../testCuda/main.cpp
g++ -Wl,-O1 -o testCuda main.o -L/usr/lib64 -L/usr/lib64/ -L/usr/local/cuda-7.5/lib64 -lopencv_gpu `pkg-config opencv --cflags --libs` -lQtGui -L/usr/lib64 -L/usr/X11R6/lib -lQtCore -lpthread
22:58:13: The process "/usr/bin/make" exited normally.
22:58:13: Elapsed time: 00:01.
Anybody an idea how to fix that?
Deinstalling the preinstalled libopencv-2.4.9 package solved it.

Using OpenCV in eclipse

I am trying to setup opencv in eclipse Luna. I have written a sample application as follows :
#include <cv.h>
#include <highgui.h>
#include<iostream>
using namespace cv;
int main( int argc, char** argv )
{
Mat image;
image = imread( argv[1], 1 );
if( argc != 2 || !image.data )
{
printf( "No image data \n" );
return -1;
}
namedWindow( "Display Image", CV_WINDOW_AUTOSIZE );
imshow( "Display Image", image );
waitKey(0);
return 0;
}
In my project properties i have included /usr/local/include/opencv in (Project->Properties->C/C++ Build->Settings->Tool Settings -> GCC C++ Compiler -> Includes -> Include Paths. )
and /usr/local/lib in (Project->Properties->C/C++ Build->Settings->Tool Settings -> GCC C++ Linker -> Libraries -> Library Search Path. )
My output of the command pkg-config --cflags opencv is -I/usr/local/include/opencv -I/usr/local/include
and the output of pkg-config --libs opencv is
-L/usr/local/lib -lopencv_stitching -lopencv_superres -lopencv_videostab -lopencv_viz -lopencv_adas -lopencv_bgsegm -lopencv_bioinspired -lopencv_ccalib -lopencv_datasets -lopencv_face -lopencv_latentsvm -lopencv_objdetect -lopencv_line_descriptor -lopencv_optflow -lopencv_reg -lopencv_rgbd -lopencv_saliency -lopencv_stereo -lopencv_surface_matching -lopencv_text -lopencv_tracking -lopencv_xfeatures2d -lopencv_shape -lopencv_video -lopencv_ximgproc -lopencv_calib3d -lopencv_features2d -lopencv_ml -lopencv_flann -lopencv_xobjdetect -lopencv_xphoto -lopencv_highgui -lopencv_videoio -lopencv_imgcodecs -lopencv_photo -lopencv_imgproc -lopencv_core -lopencv_hal
When I tried building my project i got the following errors.
‘imread’ was not declared in this scope
‘imshow’ was not declared in this scope
‘namedWindow’ was not declared in this scope
‘waitKey’ was not declared in this scope
Function 'imread' could not be resolved
Function 'imshow' could not be resolved
Function 'namedWindow' could not be resolved
Function 'waitKey' could not be resolved
Can anyone help me fixing the problem and explain what is that I was missing.
Try to change:
#include <cv.h>
#include <highgui.h>
To this:
#include <opencv2/opencv.hpp>
You also need to link the Libraries (GCC C++ Linker » Libraries):
opencv_core
opencv_imgcodecs
opencv_highgui
You didn't say which version you are using, but as you have -lopencv_imgcodecs, you are probably using OpenCV 3. If you prefer, follow the instructions here. Also change from CV_WINDOW_AUTOSIZE to WINDOW_AUTOSIZE.

C++ with Qt compile fail

I'm trying to compile the following short C++ program (not written by me) in Debian:
$ cat checksig.cpp
#include <QByteArray>
#include <QDebug>
#include <openssl/ec.h>
#include <openssl/evp.h>
#include <openssl/ecdsa.h>
#include <openssl/sha.h>
static EC_KEY* EC_KEY_pub_key ( const QByteArray& pub )
{
static EC_KEY* eckey = EC_KEY_new_by_curve_name ( NID_secp256k1 );
const quint8* ppub = (const quint8*)pub.constData ( );
o2i_ECPublicKey ( &eckey, &ppub, pub.size ( ) );
return eckey;
}
//--------------------------------------------------------------
int main(int argc, char *argv[])
{
const QByteArray data ( QByteArray::fromHex ( argv [1] ) );
const QByteArray sign ( QByteArray::fromHex ( argv [2] ) );
const QByteArray pubk ( QByteArray::fromHex ( argv [3] ) );
quint8 tmp [32];
::SHA256 ( (const quint8*)data.constData ( ), data.size ( ), tmp );
quint8 digest [32];
::SHA256 ( tmp, 32, digest );
qDebug ( ) << "data=" << QString ( data.toHex ( ) );
qDebug ( ) << "sign=" << QString ( sign.toHex ( ) );
qDebug ( ) << "pubk=" << QString ( pubk.toHex ( ) );
qDebug ( ) << "digest=" << QString ( QByteArray ( (const char*)digest, 32 ).toHex ( ) );
const bool v ( ::ECDSA_verify ( 0, digest, 32, (const quint8*)sign.constData ( ), sign.size ( ), EC_KEY_pub_key ( pubk ) ) );
qDebug ( ) << "result=" << v;
return 0;
}
But I don't think I'm using the right includes, or maybe I need to install more Qt libraries?
$ g++ -Wall checksig.cpp -o checksig -L /usr/include/i386-linux-gnu/qt5/QtCore/ -lQtCore -I /usr/include/i386-linux-gnu/qt5/QtCore/
In file included from /usr/include/i386-linux-gnu/qt5/QtCore/QByteArray:1:0,
from checksig.cpp:4:/usr/include/i386-linux-gnu/qt5/QtCore/qbytearray.h:45:30: fatal error: QtCore/qrefcount.h: No such file or directory
#include <QtCore/qrefcount.h>
^
and alternatively, using includes and libraries from one directory back:
g++ -Wall checksig.cpp -o checksig -L /usr/include/i386-linux-gnu/qt5/ -lQtCore -I /usr/include/i386-linux-gnu/qt5/
checksig.cpp:4:22: fatal error: QByteArray: No such file or directory
#include <QByteArray>
^
compilation terminated.
I'm new to C++. How can I compile this small program in a 1-liner?
As requested in the comments:
$ sudo apt-file search "QtCore/qrefcount.h"
qtbase5-dev: /usr/include/i386-linux-gnu/qt5/QtCore/qrefcount.h
thanks to Michael Popovich's answer i tried the following and got further. but now i have new errors:
$ g++ -Wall checksig.cpp -o checksig -L /usr/include/i386-linux-gnu/qt5/QtCore/ -lQtCore -I /usr/include/i386-linux-gnu/qt5/ -I /usr/include/i386-linux-gnu/qt5/QtCore/
In file included from /usr/include/i386-linux-gnu/qt5/QtCore/qatomic.h:42:0,
from /usr/include/i386-linux-gnu/qt5/QtCore/qrefcount.h:45,
from /usr/include/i386-linux-gnu/qt5/QtCore/qbytearray.h:45,
from /usr/include/i386-linux-gnu/qt5/QtCore/QByteArray:1,
from checksig.cpp:4:
/usr/include/i386-linux-gnu/qt5/QtCore/qglobal.h:1034:4: error: #error "You must build your code with position independent code if Qt was built with -reduce-relocations. " "Compile your code with -fPIC or -fPIE."
# error "You must build your code with position independent code if Qt was built with -reduce-relocations. "\
^
i have no idea if qt was built with -reduce-relocations i don't think i even installed it myself - it was probably pulled in as a dependency for another install.
anyway, trying with -fPIC and -fPIE:
$ g++ -Wall checksig.cpp -o checksig -L /usr/include/i386-linux-gnu/qt5/QtCore/ -lQtCore -I /usr/include/i386-linux-gnu/qt5/ -I /usr/include/i386-linux-gnu/qt5/QtCore/ -fPIC
/usr/bin/ld: cannot find -lQtCore
collect2: error: ld returned 1 exit status
$ g++ -Wall checksig.cpp -o checksig -L /usr/include/i386-linux-gnu/qt5/QtCore/ -lQtCore -I /usr/include/i386-linux-gnu/qt5/ -I /usr/include/i386-linux-gnu/qt5/QtCore/ -fPIE
/usr/bin/ld: cannot find -lQtCore
collect2: error: ld returned 1 exit status
I'd recommend to build Qt with either CMake or QMake, here is the solution with QMake:
checksig.pro:
QT += core
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = checksig
TEMPLATE = app
SOURCES += checksig.cpp
LIBS += -lssl -lcrypto
And compile like this:
qmake checksig.pro
make
Will compile a correct binary.
And if you really need some 1-liner:
g++ checksig.cpp -o checksig -fPIC -isystem /usr/include/x86_64-linux-gnu/qt5 -isystem /usr/include/x86_64-linux-gnu/qt5/QtCore -lssl -lcrypto -lQt5Core -lpthread
Check #find /usr/include/i386-linux-gnu/qt5/ -name qrefcount.h
Add result path to QtCore/ in your project or your system PATH

OpenCV compiling error on Beaglebone

I installed Ubuntu 14.04 and Opencv using the steps mentioned here https://solarianprogrammer.com/2014/04/21/opencv-beaglebone-black-ubuntu/
I am trying to compile the following code (saved in text file named as test2.cpp. test2.cpp and lena.jpg were copied to beaglebone home folder) :
// Test to convert a color image to gray
// Build on Linux with:
// g++ test2.cpp -o test2 -lopencv_core -lopencv_imgproc -lopencv_highgui
#include <opencv2/opencv.hpp>
#include <iostream>
int main() {
// Load the image file and check for success
cv::Mat input = cv::imread("lena.jpg", 1);
if(!input.data) {
std::cout << "Unable to open the image file" << std::endl;
return -1;
}
// Convert the input file to gray
cv::Mat gray_image;
cvtColor(input, gray_image, cv::COLOR_BGR2GRAY);
// Save the result
cv::imwrite("lena_gray.jpg", gray_image);
return 0;
}
using g++ test2.cpp -o test2 -lopencv_core -lopencv_imgproc -lopencv_highgui
I also tried telling the compiler where the libraries are using -L /usr/local/lib . (the libopencv files were found there). But got the following error each time:
ubuntu#arm:~$ g++ test2.cpp -o test2 -lopencv_core -lopencv_imgproc -lopencv_highgui -L usr/local/lib
/tmp/cckXjOPd.o: In function `main':
test2.cpp:(.text+0x26): undefined reference to `cv::imread(cv::String const&, int)'
test2.cpp:(.text+0xf0): undefined reference to `cv::imwrite(cv::String const&, cv::_InputArray const&, std::vector<int, std::allocator<int=""> > const&)'
collect2: error: ld returned 1 exit status
Can someone help me out here? Any help would be appreciated.
I find it always convenient and safe to compile using:
g++ test2.cpp -o test2 `pkg-config --libs --cflags opencv`
Install pkg-config if not already present.

undefined reference to cv::calcOpticalFlow

EDIT
Hey,
For anyone else having a similar issue, I figured something of a work around out. If you just compile this using :
gcc `pkg-config --cflags opencv` CameraMotionTest.cpp `pkg-config --libs opencv` -o cammotion
instead of the makefile that I used, it compiles correctly. I'm not exactly sure what was wrong with the method I was using before still so if someone still wants to comment on that go ahead.
After doing this i found some other issues in the code that needed fixed as well but those didn't have anything to do with this question so I won't go into them here.
Thanks!
ORIGINAL
I am trying to compile a short code for camera motion estimation on Ubuntu using openCV but am running into and "undefined reference" error for one of the openCV functions (and only one). The error I get when I try to compile is as follows:
g++ CameraMotionTest.cpp -lopencv_video -lopencv_calib3d -lopencv_imgproc -lopencv_objdetect -lopencv_features2d -lopencv_core -lopencv_highgui -lopencv_videostab -lopencv_contrib -lopencv_flann -lopencv_legacy -lopencv_ml -lopencv_nonfree -lopencv_photo -lopencv_stitching -lopencv_superres -lopencv_ts -lopencv_gpu -lopencv_ocl -o CameraMotion
/tmp/ccdHB3Pr.o: In function `main':
CameraMotionTest.cpp:(.text+0x77f): undefined reference to `cv::calcOpticalFlowPyrLK(cv::_InputArray const&, cv::_InputArray const&, cv::_InputArray
const&, cv::_OutputArray const&, cv::_OutputArray const&, cv::_OutputArray const&, cv::Size_<int>, int, cv::TermCriteria, int, double)'
collect2: ld returned 1 exit status
make: *** [CameraMotion] Error 1
I am using this makefile to try and compile and run the program:
all: run
run: CameraMotion
./CameraMotion *.jpg
CameraMotion: CameraMotionTest.cpp
g++ CameraMotionTest.cpp -lopencv_video -lopencv_calib3d -lopencv_imgproc -lopencv_objdetect -lopencv_features2d -lopencv_core -lopencv_highgui -lopencv_videostab -lopencv_contrib -lopencv_flann -lopencv_legacy -lopencv_ml -lopencv_nonfree -lopencv_photo -lopencv_stitching -lopencv_superres -lopencv_ts -lopencv_gpu -lopencv_ocl -o CameraMotion
Finally, the code I am trying to compile is:
#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/video/tracking.hpp>
#include <opencv/cv.h>
#include <opencv/cxcore.h>
#include <iostream>
#include <stdio.h>
#include <fstream>
using namespace std;
using namespace cv;
int main(int argc, const char** argv){
//storing the image in a temporary variable
vector<Mat> img;
int noi=5;
for( int index=0; index<noi;index++){
img.push_back(imread(argv[index+1]));
}
Mat im1=img[0];
//converting image to grayscale
cvtColor(im1,im1,CV_RGB2GRAY);
//initializing variable
vector<Point2f> corners1, corners2;
//setting parameters for corner detection
int maxCorner=200;
double quality=0.01;
double minDist=20;
int blockSize=3;
double k=0.04;
Mat mask;
vector<uchar> status;
vector<float> track_err;
int maxlevel=3;
Mat im2=img[1];
TermCriteria termcrit(CV_TERMCRIT_ITER | CV_TERMCRIT_EPS,20,.03);
vector<Point2f> pointskept1,pointskept2;
vector<int>pointskeptindex;
Mat F,E,R,tran;
Matx33d W(0,-1,0,
1,0,0,
0,0,1);
Matx33d Winv(0,1,0,
-1,0,0,
0,0,1);
OutputArray statF=noArray();
float fx=951.302687761842550;
float fy=951.135570101293520;
float cx=484.046807724895250;
float cy=356.325026020307800;
float alpha=0;
float kmatdata[3][3]={{fx,fy*tan(alpha),cx},{0,fy,cy},{0,0,1}};
Mat K(3,3,CV_32FC1,kmatdata);
cout<<K<<endl;
ofstream myfile;
//collecting new images, determining corners, and calculating optical flow
for (int i=1; i<noi-1; i++) {
//capturing next image
//converting new image to grayscale
cvtColor(im2,im2,CV_RGB2GRAY);
//determining corner features
goodFeaturesToTrack(im1,corners1, maxCorner, quality, minDist, mask, blockSize, false,k);
goodFeaturesToTrack(im2,corners2, maxCorner, quality, minDist, mask, blockSize, false,k);
//calculating optical flow
calcOpticalFlowPyrLK(im1,im2,corners1,corners2,status,track_err,Size(10,10),maxlevel,termcrit,0.0001);
//filtering points
for(int t=0; t<status.size();i++){
if(status[t] && track_err[i]<12.0){
pointskeptindex.push_back(i);
pointskept1.push_back(corners1[i]);
pointskept2.push_back(corners2[i]);
} else {
status[i]=0;
}
}
F=findFundamentalMat(pointskept1,pointskept2,FM_RANSAC,1,0.99,statF);
E=K.t()*F*K;
SVD svd(E);
R=svd.u*Mat(W)*svd.vt;
tran=svd.u.col(2);
//renaming new image to image 1
im2.copyTo(im1);
im2=img[i+1];
myfile.open("output.txt", ios_base::app);
myfile<<"Rotation mat: ";
for(int l=0;l<R.rows;l++){
for(int m=0; m<R.cols; m++){
myfile<<R.at<float>(i,m)<<", ";
}
}
myfile<<"Translation vector: ";
for(int l=0; l<tran.rows;l++){
myfile<<tran.at<float>(l,1)<<", ";
}
myfile<<"\n";
myfile.close();
}
return 0;
}
Has anyone else run into a problem like this? I am assuming that there is just a linking error somewhere but I am quite frankly pretty new to opencv and c++ in general and i haven't been able to figure out what is wrong yet.
Thanks!
Andrew
For anyone else having a similar issue, I figured something of a work around out. If you just compile this using :
gcc `pkg-config --cflags opencv` CameraMotionTest.cpp `pkg-config --libs opencv` -o cammotion
instead of the makefile that I used, it compiles correctly. I'm not exactly sure what was wrong with the method I was using before still so if someone still wants to comment on that go ahead.
After doing this i found some other issues in the code that needed fixed as well but those didn't have anything to do with this question so I won't go into them here.
Thanks!
It seems that You have some problem with Your OpenCV instalation. To compile Your code, on OpenCV 2.4.9, it was enough to use
g++ t1.cpp -lopencv_video -lopencv_core -lopencv_objdetect -lopencv_imgproc -lopencv_highgui -lopencv_calib3d -o CameraMotion
You can also try using nm -g <library> | grep -i <function_name> to check if Your libopencv_video.so contains calcOpticalFlowPyrLK... (based on this answer).