How to link opencv in QtCreator and use Qt library - c++

This question must be duplicate many times, but it just doesn't work and sometimes it still remains unanswered. Sources of information are mainly these
http://www.laganiere.name/opencvCookbook/chap1s1_2.shtml
http://www.youtube.com/watch?v=dgcXYQijV6c
This is the summation of what I think one should/can do. (And now it works for me.) Hopefully I mentioned everything from the very beginning, the aim is to write a very clear tutorial.
Installation of OpenCV for QtCreator
I have already MS Visual Studio 2010 Professional installed. (I have a free licence as a student) - I think this is not necessary, just a mention
Download: Qt 5.0.1 for Windows 32-bit (MinGW 4.7, 823 MB)
2.1 Install: Warning, everything that Qt uses (e.g. OpenCV) must be in directories that don't contain white-spaces in their names. - i.e. "Program Files" is wrong. (But I don't want different program files to accumulate directly on C, so I've only made a folder "Programs" in which everything important is installed)
Download: cmake-2.8.10.2-win32-x86.exe - Install for all users (this can be in Program Files)
Download: OpenCV-2.4.0.exe, extract to: C:\Programs\opencv24 - it'll create a dir "opencv"; add another folder "opencv_bin". Now it looks like this:
C:\Programs\opencv24\opencv*
C:\Programs\opencv24\opencv_bin
Set PATH environment variable, so that there be a link to MinGW compiler. e.g. C:\Programs\Qt\Qt5.0.1\Tools\MinGW\bin;
Start cmake-gui.exe
6.1 source code: set the default dir for OpenCV; C:\Programs\opencv24\opencv
6.2 binaries: set the opencv_bin dir; C:\Programs\copencv24\opencv_bin
6.3 click configure:
Choose MinGW Makefiles and Specify native compilers, click next
Field C is for gcc.exe; C:/Programs/Qt/Qt5.0.1/Tools/MinGW/bin/gcc.exe
Field C++ is for g++.exe; C:/Programs/Qt/Qt5.0.1/Tools/MinGW/bin/g++.exe
Field fortran can be empty, click finish
6.4 Many red lines will appear To the search field enter one by one: WITH_QT, WITH_TBB, WITH_IPP, WITH_CUDA, CMAKE_BUILD_TYPE
WITH_QT - must be selected.
WITH_TBB, WITH_IPP, WITH_CUDA - must be unselected
CMAKE_BUILD_TYPE - click and enter a text "Debug" (without quotes).
Clear the text from the Search field.
6.5 click configure and keep clicking configure until all red lines are gone, then click generate and close cmake-gui.exe
Go to the terminal (~command prompt), cd to the directory where are the builds (opencv_bin) and type mingw32-make
When the process ends after a long time, type mingw32-make install
Add into Path variable the path to the QtCreator/bin C:\Programs\Qt\Qt5.0.1\Tools\QtCreator\bin
Now I have created a new console app in QtCreator.
//cvHello.pro
QT += core
QT -= gui
TARGET = cvHello
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
INCLUDEPATH += C:/Programs/opencv24/opencv_bin2/install/include
LIBS += "C:/Programs/opencv24/opencv_bin2/bin/*.dll"
SOURCES += main.cpp
OTHER_FILES += \
img.JPG
And the main file:
//main.cpp
#include <iostream>
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv/cv.h"
using namespace std;
int main()
{
cout << "Hello World!" << endl;
cv::Mat mat;
mat = cv::imread("img.JPG");
cvNamedWindow("hello");
cv::imshow("hello",mat);
cvWaitKey(0);
return 0;
}

Finally I am starting to be happy. When adjusting this question I had to try all the ways how to define LIBS. Listing them manually helped, at first I wrote them somehow wrong.
This is how it works finally:
LIBS += -LC:\\Programs\\opencv24\\opencv_bin2\\bin \
libopencv_core240d \
libopencv_highgui240d \
libopencv_imgproc240d \
libopencv_features2d240d \
libopencv_calib3d240d \

The originally accepted answer did not work for me, I am running MSVC2013 Professional and QT5.9. I found SIMPLE and SUREFIRE CROSS-PLATFORM solution that should help anyone who is trying to link an external library (like openCV) with QT.
The steps listed below are found in the Qt5 documentation: http://doc.qt.io/qtcreator/creator-project-qmake-libraries.html under the "To Add Library" section.
Right click on the project file located in the 'project pane' on the left side of the creator... and select "Add Library..."
Follow the instructions of the wizard
Let me add some specificity from here:
Select "External Library"
For the "Library File" navigate to your opencv_worldXXX.lib file (or opencv_worldXXXd.lib file, you will notice that by specifying only one or the other the wizard has a checkbox which includes the other automatically) [ex. ...\opencv\build\x64\vc12\lib\opncv_world310.lib]
For the "Include Folder" navigate to the "include" folder within the build. [ex. ...\opencv\build\include]
Select your operating system, dynamic/static library (whichever is appropriate)
Hit NEXT, CLEAN UP, and RUN!

Related

Qt application throws "dyld: Symbol not found: __cg_jpeg_resync_to_restart"

I get well known dyld issue on OS X.
Qt.pro file:
INCLUDEPATH += /usr/local/Cellar/libpng/1.6.23/include /usr/local/Cellar/jpeg/8d/include
LIBS += -L/usr/local/Cellar/libpng/1.6.23/lib -L/usr/local/Cellar/jpeg/8d/lib -ljpeg -lpng -ljpeg -lz
In runtime my application throws:
dyld: Symbol not found: __cg_jpeg_resync_to_restart Referenced from:
/System/Library/Frameworks/ImageIO.framework/Versions/A/Resources/libTIFF.dylib
Expected in: /usr/local/Cellar/jpeg/8d/lib/libjpeg.8.dylib in
/System/Library/Frameworks/ImageIO.framework/Versions/A/Resources/libTIFF.dylib
I already got this before and I fixed it using this answer, but now it occurs again and this advice not works. How can I solve this problem?
This is only a QtCreator runtime issue. DanyAlejandro's answer (above) is partially correct.
Go to Projects -> Run -> "Run Environment" (show Details)
I would not recommend Unset, rather you should edit
Both: DYLD_LIBRARY_PATH and DYLD_FRAMEWORK_PATH
Add /System/Library/Frameworks/ImageIO.framework/Resources: to the beginning for both paths (colon delimited string)
Build project again - this will fix it for good
In my case, this error would only happen in Qt Creator on OSX ElCapitan (Compiling my OpenCV programs with CLion or XCode in OSX would work without doing anything), so I don't think it's correct to say that a change in the system configuration is mandatory (like your link suggests).
What I did, was to link each library file one by one (linking the dylib files one by one, with their full path). This way, I didn't have to mess with my files or do any extra configuration. For example:
LIBS += "/usr/local/lib/libopencv_core.dylib"
LIBS += "/usr/local/lib/libopencv_highgui.dylib"
Provided such files exist.
Edit: Another way to fix this problem (which further proves that this is only Qt Creator related) is to go to Projects -> Run -> "Run Environment" (show Details), select DYLD_LIBRARY_PATH and click Unset. After this, your project should compile as expected.
This question provides a screen shot of finding the setting to change:
I was looking everywhere except the correct spot. I'll walk you through it. You can click the images for bigger versions.
Within Qt Creator, there's a toolbar along the left side of the window. Welcome, Edit, Design, etc. One of the choices is Projects. Select that tab.
From there, there's a new navigation area near the left. Under Build and Run, your Desktop, there's a Run section.
That goes to the run settings, and in almost the exact center of that page are the Run settings in a grey box, and one of the items is the checkbox to turn off.

How to build Qt application using static linking

I am coming for Visual Studio word where you just change the project settings to static or dynamic linking so you application will not need framework dlls to run in on another machine. How do I do that in Qt?
I am following http://doc.qt.io/qt-5/windows-deployment.html but it is that helpful.
It says:
cd C:\path\to\Qt
configure -static <any other options you need>
But c:\Qt is a root folder (default in my case) and configure command is not recognized. I went to c:\Qt\5.3 and still the same case. Also what am I suppose to fill for < if anything? (I am not not filling it and hope it doesn’t mess up)
Do you really have to go command line to do that..is that the only way? I also read few say I need to add this line to .pro file
CONFIG += static
But this doesn’t do anything as well.
How do I link statically?
first of all make sure your Qt version is static .
then add CONFIG += static to your .pro file .

New to Xcode can't open files in c++?

I've been using windows in a class I've been taking but I am trying to run a basic code to figure out how to open/close/input/output from files on Xcode and the code I usually use on visual studios isn't working any idea why? thanks!
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream fin;
ofstream fout;
string input;
fin.open("inputFile.txt");
if(fin.fail())
cout << "File failed to open." << endl;
fin >> input;
fout.open("outputFile.txt");
fout << input;
}
Put your .txt files in the same directory where your main.cpp file is (or anywhere you like).
In Xcode go to Product > Scheme > Edit Scheme > Run (on the left) > Options (middle top)
Down under Options for "Working Directory" check “Use custom working directory” and set it to the directory where you .txt files are located.
To work with the files, you will have to specify just file names, e.g. in_file.open("inputFile.txt"); no path is necessary.
Here's a completely different approach: Have Xcode copy the input file for you.
Select your project in Xcode
Select Build Phases
Click the '+' button to create a new Build Phase
Select New Copy Files Build Phase
Select Products Directory
Click the '+' button to add your file
Click Add Other
Select your input file and click Open
Check the Copy items… checkbox and click Finish
Now every time you build your project, the input file will be copied to the same folder as the executable no matter where it is built. Of course, to see the output file, you'll still need to find the executable in Finder.
The answers don't really explain the problem so I thought I'd do that.
When you pass a relative path like "inputFile.txt" to file APIs, it's treated as relative to the working directory when the program is executed. This is the same as the 'working directory' when you use cmd.exe or Terminal.app or command lines in general. The Unix command pwd ("print working directory") displays the current working directory. On Windows running the command cd with no arguments performs the same function. (On Unix running cd with no arguments will change the working directory to the user's home directory.)
When you run a program from the command line, the command line shell sets the program's working directory. When you run a program from within an IDE, the IDE sets the working directory. Since, unlike on a command line, there's no obvious answer for what the IDE should set as the working directory, Visual Studio and Xcode set the working directory to different locations by default: Visual Studio sets the working directory to $(ProjectDir), the directory containing the Visual Studio project file; Xcode sets the working directory to the build products directory, i.e. the location the executable was written to.
Some possible solutions to your problem are:
Do not use a relative path, and therefore don't depend on the working directory. This isn't much help in making the program more portable, because the absolute paths will also differ between platforms, and so you will still have to 'configure' the program for each platform. In fact using an absolute path is worse, because it means your source code must differ, whereas it would be better to keep that difference confined to each platform's build configuration.
Configure the IDE to use your desired working directory. Visual Studio can be configured by right clicking the project, selecting Configuration Properties > Debugging > Working Directory, and setting the working directory to the desired path (potentially using Visual Studio build variables).
nepete's answer describes how to configure the working directly set by Xcode.
Configure the IDE's build process to copy your data files to an appropriate location. In Visual Studio you would do this in a C++ project by configuring the project's Properties > Configuration Properties > Build Events.
SSteve's answer covers how to configure additional build steps in Xcode.
I'm guessing you have inputFile.txt in the folder that contains your source code. That's not going to work. You need to put it in the folder that contains the generated executable. To find that folder, right-click on your app under Products and select Show In Finder.
This image shows what it looks like for a command line program. It also shows the Finder window that was opened. As you can see, it is a different folder than the one containing the source code.
As suggested by nepete, edit the scheme, but use $PROJECT_DIR as the custom working directory. Helps with moving the project around, or working in two different environments (e.g., home and office).
BTW. $PROJECT_DIR is one of the Xcode Environment Variables, and also helps with passing file names as command line arguments to programs (settable under "Arguments" in the scheme).
I've struggled with the same problem today. I wanted to add C code to my Swift project and my file pointer was always NULL.
Unfortunately, in XCode 9 for iOS app, I couldn't change the working directory. Changing Build phases didn't help me either. After 4+ hours of trial and error, that's what I've come up with finally and it works:
when copying files to XCode, I've chosen "Create groups", but I needed to choose "Create folder references":
I created a new objective-c file (.m) and copied all my C code there.
I left untouched .h files (XCode generated bridging header and my own .h file with public functions declaration). Now my project structure looked like this:
In my dict.m file in place of previous plain c fopen part:
FILE *dic = fopen("dictionary.txt", "r");
I added obj-C code:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"dictionary" ofType:#"txt"];
FILE *dic = fopen([filePath cStringUsingEncoding: NSUTF8StringEncoding], "r");
And it works now without any problem! It's just amazing!
ps I decided to write this answer in case it will help someone like me and will save them some time. If you know how to change working directory in XCode 9 for iOS, please, leave me a comment - now I am really curious why I can't find it.

Qt error: LNK1181: cannot open input file 'debug\main.obj'

Qt creator was working well, but suddenly shows a problem error: LNK1181: cannot open input file 'debug\main.obj'.
This problem shows always with any type of application either GUI or console.
I've uninstall the Qt, and install again, but the problem still exists.
I did not do anything in the Qt creator settings, I left the default settings.
The following application is simple console application occur the same problem in it.
//main.cpp
#include <QCoreApplication>
int main(int argc, char *argv[]){
QCoreApplication a(argc, argv);
return a.exec();
}
Note: I'm using Qt 5.1.1 for Windows 32-bit (VS 2010, OpenGL).
This problem also occurs if the path of your project (name of any folder) contains a white space.
This problem occurs also if you have in the .pro or .pri files something like:
HEADERS += \ \
or
SOURCES += \ \
Okay, we finally have a real answer for this generalized problem instead of the OP's typo problem if that didn't unblock you either.
Actual Problem (black-box perspective): The "Build directory" auto-filled entry breaks for projects inside whitespace directories. Qt Creator actually prohibits you and tells you not to use whitespace when making new Projects. You can still close a new project and re-name it to add whitespace, and Qt Creator will handle it gracefully. If you copy the build directory, even with whitespace in it, and paste that into the field replacing the broken auto-generated path (mine was using relative paths) then JOM will start working correctly, as QMake does not generate any errors. I can't speak for other Make tools.
Make or clone down your project with whitespace
Load it in Qt Creator
Run QMAKE
Select the "Project" button on the left-hand side
Make sure you're in the "Build" tab
Select "Browse", and then re-select the shadow directory QMAKE made
That should unblock you if it wasn't a simple issue for deleting the old QMAKE-generated folders, which is the most common problem people face with this specific error while developing within Qt Creator.
I got the error because of this:
HEADERS += \ \
$$PWD/QOakTreeViewRecursiveModel.h
instead of:
HEADERS += \
$$PWD/QOakTreeViewRecursiveModel.h
What worked for me:
Close the Qt Creator
Delete the [filename].pro.user file in your project directory
Open the project again and let Qt configure itself
Generally whenever I encounter an error like this, this is one of the first things I do as it solves a lot of problems with Qt.
Edit: This will of course reset your project build location.
The problem has been solved.
The cause of the problem was when creating a new project (GUI or Console), all source files that belong to this new project take a wrong extension ex: main.cp, but the correct extension is supposed to be ex: main.cpp.
And when changing all the source files extension from .cp to .cpp worked fine.
Or change the default source file extension from [Tools -> Option -> C++].
hmm If I remember correctly when I faced this kind of problems using your similar setup (QtCreator and Windows) running QMAKE & rebuilding the project again helped me solve this linker errors.
Run Clean and qMake and rebuild.
I has like this problem and this helped me.
I solved the problem by removing the big path and space names in the directories.
Try to create a folder in C:/ and copy or clone the project in this folder.
Remove all builder folders and configure the project again.
That solved it for me.

Boost in Netbeans 7.1.1

Trying to run the following:
#include<iostream>
#include<boost/filesystem/operations.hpp>
namespace bfs=boost::filesystem;
int main()
{
bfs::path p("second.cpp");
if(bfs::exists(p))
std::cout<<p.leaf()<<std::endl;
}
I got some errors in cygwin so I decided to try out netbeans, and used the following as a guide. I added all links and the following for filesystem Project -> properties -> Linker ->Libraries -> Add option -> Other -> -lfile_system as noted here. I have run a separate test using #include<boost/any.hpp> so I am not currently doubting that my boost is not installed correclty.
It seems weird to me that it is "file_system", so I also tried "filesystem" but to no avail.
When i hold Ctrl and click on #include<boost/filesystem/operations.hpp> my netbeans brings up my operations.hpp file so it seems okay (linked properly internally that it can "see" what I want it to see).
The solution to installing boost came in the following form:
1 - If you have any path variables that are being used for Visual Studio you should temporarily change the variable during installation. This is a good guide. Once that is done, this is one step completed.
2 - Download and install MinGW. This is a very easy process and you can find the installer files here.
Once you have done these things (if you are in the same situation as me), you will now be able to properly install boost.
Horay!
Using Boost with cygwin step by step
Create a new Project
It is better to take the names given here in this tutorial exactly. Later ask: It does not work, can then be easier to find.
I do not think I need to mention all T:\ must of course be replaced with your drive.
Project Name : Boost-cyg-Test
Now your Project should look like
Open main.cpp
Overwrite the generated code with the following. We want to that, first of all everything works without error.
Therefore, please do not use your own special code.
It is difficult to find a fault. Then told after several ask, to get:
I have used my own code
#include <iostream>
#include <boost/filesystem.hpp>
using namespace std;
using namespace boost::filesystem;
int main()
{
path p("second.cpp");
if (exists(p)) { std::cout<<p.leaf()<<std::endl; }
}
In this section we assume that "boost" is already compiled.
goto Tools -> Options
Your C++ Code Assistance options should look something like this.
If this is not so, we should let Netbeans create that for us.
Add New Tool Collection
After we have completed this dialog with OK, we should find the settings shown above. ( C++ Code Assistance options).
Copy all libs into the right place
Let's create a new folder 'boost'.
With a search tool, search in your compiled Boost folder for *.a
My Boost is compiled with the shared option so we find :
For our short App. we need only 2 files.
libboost_filesystem-gcc45-mt-d-1_53.dll.a
libboost_system-gcc45-mt-d-1_53.dll.a
But if we're at it to copy two files, we can copy all files.
So mark all found .a files and copy them into the directory just created
T:\cygwin\lib\boost .
Now we do the same with our .dll files.
Mark all .dll files and copy it in your ?:\cygwin\bin directory.
If you only have compiled static librarys, you can skip this point.
Now it's time to modify our project settings.
As you can see i put my source Boost folder into cygwin
and
As we have already noted above, we need two .a files.
with Add Library navigate to T:\cygwin\lib\boost and select
libboost_filesystem-gcc45-mt-d-1_53.dll.a
libboost_system-gcc45-mt-d-1_53.dll.a
Now you'll notice that this name was shortened by netbeans to:
boost_filesystem-gcc45-mt-d-1_53.dll
boost_system-gcc45-mt-d-1_53.dll
This is somewhat confusing. It looks as if a .dll is standing here. But it is really a .a file.
Set a breakpoint in main.cpp. Now we start debug.
I have marked the important part, the two libs, with an arrow.
All libs are found and after make has finished, stops at the breakpoint.
The output:
Build Boost for Cygwin
For all who want to create boost with shared library itself.
Download boost_1_53_0.zip
Create a folder in your ?:\cygwin directory.
boost_1_53_0
Extract the zip file into that directory.
It should look like:
open a cmd window, cd to boost_1_53_0 directory.
To have a clean build we need a PATH that have only the cygwin home and bin.
In the cmd type.
SET PATH=T:\cygwin;T:\cygwin\bin
and test the path.
PATH
Type
bootstrap.bat
Type
.\b2 --build-dir=T:\boost-cyg toolset=gcc variant=debug link=shared runtime-link=shared
After some time the build is finished.
Now you have the same environment that we have used in the tutorial.
If you get a Error : gcc not found
copy (not rename) in ?:\cygwin\bin folder, for example : (names may differ).
i686-pc-cygwin-gcc-4.5.3.exe to gcc.exe
and
i686-pc-cygwin-g++-4.exe to g++.exe
Hope it helps you.
Could you paste the error you get when compiling ?
I am not used to compile programs in a Windows environment, but I think as Jesse Good suggested in a comment that you have a linker error.
You may solve it by using -lboost_filesystem instead of lfile_system.
To find out how your libs are called, you get the name of your lib (on my unix environment I have libboost_filesystem.so), strip the "lib" prefix and the ".so" or ".a" suffix (must be different in a Windows environment).
if your boost installation is correct and you are sure about it then for Unable to resolve identifier try Code Assistance->Reparse Project from context menu of the project. It tries to recover broken code model by reparsing project from scratch. if that didn't workout try closing IDE and removing code model cache.
p.s. do you have compilation errors?