This problem mainly occurs, when a library is not included.
When using qmake, your .pro file needs to be like this:
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
CONFIG += c++11
SOURCES += \
main.cpp \
dialog.cpp
HEADERS += \
dialog.h
FORMS += \
dialog.ui
#Added Lines for OpenCV
INCLUDEPATH += /usr/local/include/opencv4
LIBS += -L/usr/local/lib \
LIBS += -lopencv_core -lopencv_imgproc -lopencv_features2d -lopencv_highgui -lopencv_calib3d -lopencv_imgcodecs -lopencv_videoio
QMAKE_MACOSX_DEPLOYMENT_TARGET = 11.0
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
Notice that the library -lopencv_imgcodecs
is required if you are using imread
-and the library lopencv_videoio
is required when using videoCapture
.
THe following main.cpp can be used to check the setup using an image and imread:
#include "dialog.h"
#include <QApplication>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Dialog w;
cv::Mat image= cv::imread("/Users/apple/Desktop/dog.jpg");
// create image window named "My Image"
cv::namedWindow("My Image");
// show the image on window
cv::imshow("My Image", image);
// wait key for 5000 ms
cv::waitKey(5000);
w.show();
return a.exec();
}
this main.cpp file can be used to check Videocapture and setup:
#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/videoio.hpp"
#include <iostream>
using namespace cv;
using namespace std;
void drawText(Mat & image);
int main()
{
cout << "Built with OpenCV " << CV_VERSION << endl;
Mat image;
VideoCapture capture;
capture.open(0);
if(capture.isOpened())
{
cout << "Capture is opened" << endl;
for(;;)
{
capture >> image;
if(image.empty())
break;
drawText(image);
imshow("Sample", image);
if(waitKey(10) >= 0)
break;
}
}
else
{
cout << "No capture" << endl;
image = Mat::zeros(480, 640, CV_8UC1);
drawText(image);
imshow("Sample", image);
waitKey(0);
}
return 0;
}
void drawText(Mat & image)
{
putText(image, "Hello OpenCV",
Point(20, 50),
FONT_HERSHEY_COMPLEX, 1, // font face and scale
Scalar(255, 255, 255), // white
1, LINE_AA); // line thickness and type
}
If using Cmake instead of qmake, you can use the same main.cpp files.
The only thing you need to do is to add these lines to the bottom of CmakeList.txt
where opencv_test_102
is the name of the project folder.
#1 Specify OpenCV folder, and take care of dependencies and includes
set(OpenCV_DIR /usr/local/include/opencv4)
find_package(OpenCV REQUIRED)
include_directories(${OpenCV_INCLUDE_DIRS})
#2 Specify OpenCV library
target_link_libraries(opencv_test_102 PRIVATE ${OpenCV_LIBS})