[solved] Astonishingly weird behaviour of Qt Creator + OpenCV
-
Consider the following simple piece of C++ code that loads and displays an image with OpenCV, using imread():
#include <opencv2/highgui/highgui.hpp> int main() { auto image = cv::imread("Image_0.png", -1); cv::imshow("image", image); cv::waitKey(); }
and the relative .pro file:
TEMPLATE = app CONFIG += console c++11 CONFIG -= app_bundle CONFIG -= qt INCLUDEPATH += "C:/OpenCV-3.1.0/opencv/build/include" LIBS += "C:/OpenCV-3.1.0/opencv/build/x64/vc14/lib/opencv_world310d.lib" SOURCES += main.cpp
I build it and copy the image into the build folder. After that, if I try to run the program by double clicking on the .exe file, it runs normally and displays the image. BUT if I try to run it from the editor, with CTRL+R, I get an error from OpenCV:
OpenCV Error: Assertion failed (size.width>0 && size.height>0) in cv::imshow, file C:\buildslave64\win64_amdocl\master_PackSlave-win64-vc14-shared\opencv\modules\highgui\src\window.cpp, line 281
which meand that imread() didn't manage to open the file. Now, how is it possible that the program works correctly when I run the exe, but just won't work when I run it from the debugger? This is driving me a bit crazy.
Built with MSVC2015_64bit debug in Windows 10.
-
It works in both cases, just as you wrote it ;)
The problem here is the relative path you specified:Image_0.png
. This path is relative to the working directory of your app.
When you run by starting the exe it "works" because the working directory is in the same directory as your exe.
When you run from the IDE the working directory is the build directory (usually one folder up from your exe). There's no image there so it "doesn't work", or rather works but doesn't find an image.
You'll get the same problem if you, for example, run it from a command line from a different directory or create a shortcut with a different working directory set.For external resources such relative paths are evil. You can programatically obtain your exe location and construct an absolute path from your relative path at runtime. A second solution is to place the image in the resources and use resource path.
-
@Chris-Kawa Thank you, now it works. The solution was simple, but apparently I must understand better how the paths work. If you have any advice on where to start reading or you know any interesting online article/tutorial, please tell me :-)