Qt with OpenCV: The program has unexpectedly finished - qt

I just installed Qt 5.15 and is testing how it works with opencv. I downloaded prebuild Opencv4.3, and set up a .pri file for being deployed in Qt.
The include and libs are as follows in the .pri file:
INCLUDEPATH += C:/opencv/opencv-4.3.0-prebuild/include
CONFIG(release, debug|release):{
LIBS += -LC:/opencv/opencv-4.3.0-prebuild/x64/vc14/lib \
-lopencv_world430
}
CONFIG(debug, debug|release):{
LIBS += -LC:/opencv/opencv-4.3.0-prebuild/x64/vc14/lib \
-lopencv_world430d
}
Then I run a simple image display domo:
#include "opencv2/opencv.hpp"
using namespace cv;
Mat img = imread("image.png");
if(img.empty())
{
qDebug()<<"Could not find the image";
}
else
{
namedWindow("Image");
imshow("Image", img);
}
The resulting error message: The program has unexpectedly finished. The process was ended forcefully.
Without linking with OpenCV, Qt itself works just fine.
What causes the problem?

It's not clear where is your example code is located. Is it in main?
Generally in OpenCV you also have an event loop (as in Qt) but it is hidden.
So if you want to actually see the namedWindow, you need to call cv::waitKey().
You can call it like cv::waitKey(1) if you do it periodically.
But generally you should do only the image processing in OpenCV, convert the cv::Mat to QImage, and show that in Qt.

I found this issue is due to an improper debugger set in the Qt Creator. Refer to the posts QtCreator no debugger set up (Windows). and Cannot run Qt example in Qt creator: The program has unexpectedly finished, and the official document https://doc.qt.io/qtcreator/creator-debugger-engines.html#supported-native-debugger-versions and https://doc.qt.io/qtcreator/creator-debugger-engines.html#debugging-tools-for-windows

For the crash,
My first guess is your environment variable is not set properly. Please check you assign the env. variables properly.
Writing imshow() in Qt won't work. As suggested by tr3w, you should convert to a qimage.
Mat img;
QImage img1 = QImage((uchar *) img.data,img.cols,img.rows,img.step,QImage::Format_Indexed8);
You can replace with your supported image format instead of indexed8.

I solved the problem as follows: I have added the paths to opencv's bin and lib files to PATH.

Related

Qt VS Tools Generating Incorrect MOC Command

I've been struggling all afternoon to track down an issue with the Qt VS Tools in Visual Studio 2013. I'm trying to update an existing .vcxproj file that used a home-grown mechanism for generating MOC, UIC, etc. files to use the Qt VS Tools mechanism instead.
The problem I'm having is in the MOC command that's getting generated for .h files that include the Q_OBJECT macro. A sample line (reduced for brevity) is here:
<Command Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">"$(QTDIR)\bin\moc.exe" "%(FullPath)" -o ".\GeneratedFiles\$(ConfigurationName)\moc_%(Filename).cpp" "-I$(QTDIR)\include\QtGui" "-I$(NOINHERIT)"</Command>
The problem is that NOINHERIT doesn't exist, so the "-I$(NOINHERIT)" gets evaluated to "-I" without a value, and the MOC compiler complains and doesn't generate the MOC file. I've tried cleaning up inherited paths, checking and unchecking the "Inherit from parent or project defaults", and the only change I sometimes see is that it has "-I" without the NOINHERIT macro.
Completely starting over with a new .vcxproj file is beginning to feel like my only hope, but that's a much larger task than I'd like to take since there's a significant number of them with interdependencies that I'd rather not create again.
I'm using the latest Qt VS Tools, which is version 2.3.2. Any ideas on how to resolve this?
Naturally, five minutes after I post, I found the issue. An included property file had this:
<AdditionalIncludeDirectories></AdditionalIncludeDirectories>
Rather than this, which solved the problem:
<AdditionalIncludeDirectories>%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
Interestingly, and for what it's worth, this did not work:
<AdditionalIncludeDirectories />
Add the %(AdditionalIncludeDirectories) at project->C/C++ -> General -> Additional Include Directories.
%(AdditionalIncludeDirectories) is added by default, but if for some reason, this is overwrite by mistake, then we will get an error as such.
Moc'ing XXXXXXX.h...
Missing value after '-I'.

Qt: Creating a directory via project file

I'm trying to have my compiled language files copied into my output directory during the build process. I've got the copying down, but not the creating of the directory. After a lot of googling I came up with this:
LANGDIR = $$OUT_PWD
win32:CONFIG(debug, release|debug):LANGDIR = $$LANGDIR/debug/lang
win32:CONFIG(release, release|debug):LANGDIR = $$LANGDIR/release/lang
makeLang.commands += $${QMAKE_MKDIR} $$shell_path($${LANGDIR})
first.depends = $(first) makeLang
export(first.depends)
export(makeLang.commands)
QMAKE_EXTRA_TARGETS += first makeLang
This does the job for the most part, however, when the directory lang already exists, the build process fails. I know QMAKE_CHK_DIR_EXISTS exists, but I have no clue how to use that as a conditional. I figured perhaps it's something like this !$${QMAKE_CHK_DIR_EXISTS} $$shell_path($${LANGDIR}) : $${QMAKE_MKDIR} $$shell_path($${LANGDIR}) but that just crashes jom.exe; didn't really expect that to work anyways.
I'm also open to suggestions for better ways to do what I'm trying to do. Ideally the whole thing should be platform independent so I can have artifacts generated in my CI pipeline that contain the language files.
You should use QMAKE_MKDIR_CMD which creates the directory only if it doesn't exist.

What are productive ways to debug Rcpp compiled code loaded in R (on OS X Mavericks)?

What is the most productive and quickest way to debug shared objects that are loaded into R, in particular on OS X Mavericks? I'm primarily interested in debugging compiled Rcpp code.
I have read the R externals on debugging compiled code (http://cran.r-project.org/doc/manuals/R-exts.html#Debugging-compiled-code) which favours using gdb, but gdb isn't officially supported on Mavericks. However, it seems that lldb is a viable alternative? I found the most useful resource for working out how to debug compiled code in R from Dirk's response to this post (Thanks Dirk!) (Debugging (line by line) of Rcpp-generated DLL under Windows).
I can successfully debug compiled Rcpp code by following the steps which I outline below explicitly step by step, which other Rcpp novices may find this useful (apologies for the length, but I figure it's better to be clear than to omit and be vague). But this development process is a bit tedious and time consuming.
Questions:
is there a faster and/or easier way to debug compiled Rcpp code, compared to what I do below?
I'm a big fan of Rstudio, and would love to incorporate debugging shared objects created from that IDE, so if anyone knows how to do this, I would be interested to know? Rstudio seems to use attributes, and it appears that step 4 below needs modification, because there doesn't seem to be a .cpp file in the temporary directory after compiling (in my example below, there is no "file5156292c0b48.cpp" file)
The steps:
1) (One off) Go to the directory ~/.R (a hidden directory with the .). Create a new file called "Makevars" and in it add the line CXXFLAGS=-g -O0 -Wall.
2) In the terminal, type R -d lldb to launch R. lldb will now start.
3) Type run at the lldb command line. This will start R.
4) Compile the Rcpp code and find the location of the compiled objects. Dirk's response to the above mentioned post shows one way to do this. Here is an example I'll use here. Run the following commands in R:
library(inline)
fun <- cxxfunction(signature(), plugin="Rcpp", verbose=TRUE, body='
int theAnswer = 1;
int theAnswer2 = 2;
int theAnswer3 = 3;
double theAnswer4 = 4.5;
return wrap(theAnswer4);
')
This creates a compiled shared object and other files which can be found by running setwd(tempdir()) and list.files() in R. There will be a .cpp file, like "file5156292c0b48.cpp" and .so file like "file5156292c0b48.so"
5) Load the shared object into R by running dyn.load("file5156292c0b48.so") at the R command line
6) Now we want to debug the C++ code in this .so object. Go back to lldb by hitting ctrl + c. Now I want to set a break point at a specific line in the file5156292c0b48.cpp file. I find the correct line number by opening another terminal and looking at the line number of interest in file5156292c0b48.cpp. Say it's line 31, which corresponds to the line int theAnswer = 1; above in my example. I then type at the lldb command line: breakpoint set -f file5156292c0b48.cpp -l 31. The debugger prints back that a break point has been set and some other stuff...
7) Go back to R by running cont in lldb (the R prompt doesn't automatically appear for me until I hit enter) and call the function. Run fun() at the R command line. Now I am debugging the shared object (hit n to go to next line, p [object name] to print variables etc)....
To debug simple Rcpp scripts like this, one thing you can do is create a .cpp application (with a main) that embeds R. This way you can debug it directly with Xcode which will give you a good debugging experience.
It gets more complicate when you start to want to debug packages.
This is tough. I tried Xcode and Eclipse with a standalone C++ application, but it was so difficult to get all the headers and libraries working. Furthermore, the RcppExport code calls your real R function through a pointer which seemed to really confuse Xcode, and I couldn't step into my function.
I ended up with (gdb or lldb):
In R:
R -d lldb
In debugger, set breakpoint:
b functionName
run
In R:
.Call(etc) # or just call your R code which invokes compiled C/C++ code
Then back in debugger once break happens, you can step, examine frames, etc.
This lldb/gdb command quick reference helped a lot.
Forget about trying to do this in a GUI at this point. Hopefully Rstudio will get this going.

Add LDFLAGS in qt .pro field

How to add LDFLAGS in qt .pro field?
consider Library folder and shared library(.so) is in a dir_path folder.
For example, adding this line is not solving the issue
LIBS+= -Ldir_path -llibrary_name
Any suggestions?
qmake has the QMAKE_LFLAGS variable for it.
You can read about qmake variables here.
Make sure that you use "TEMPLATE = app" to get the correct behavior. Using the "lib" template would ignore the LIBS variable.
use QMAKE_LDFLAGS for your requirement.

How does one compile single file Xcode 4?

While I used to compile a single source file with Cmd+K in prior versions of Xcode, how does one do the same in Xcode 4? (Note that this is different than preprocessing or showing the disassembly of the file.) If compiling from a command line is proposed then it must be such that the project's settings, include paths, preprocessor definitions, etc., are all included.
An example use case is where I make a header file change but only want to test the change's effect with respect to a single source file, not all of the files that depend upon that header.
The command has been moved to the Perform Action submenu. Look under
Product > Perform Action > Compile filename.cpp
To assign Cmd+K to it, go to
File > Preferences > Key Bindings > Product Menu group
and you'll find Compile File where you can assign a key. Cmd+K is assigned to Clear Console now by default, so be sure to remove that binding to avoid conflicts.
One way that I have found to do this is to using the following menu commands:
Product -> Generate Output -> Generate Preprocessed File
Product -> Generate Output -> Generate Assembly File
This may not be exactly what you want, but it will compile the single file.
When you build a project, xcode runs compilation command. You can check the log, search for your file and copy paste that command on Terminal. It'll compile only the file for which you copy/pasted on the terminal.
If your file is C (or C++) file, then simply open your terminal, go to the folder in which the file resides and type
gcc -o outputFile inputFile.c
I am not familar with Objective-c that much, but GCC might work since it's only a superset of C, just like C++.
Hope that was helpful :)
The keyboard shortcut Cmd+K on Xcode 3 and before has been remapped to Cmd+B on Xcode 4
Along the same lines, Cmd+Return was remapped to Cmd+R (in case you ever used that)
The common requirement for single file compilation is checking it for syntax errors. (atleast for me). Since xcode4 highlights syntax errors as you type. It seems apple removed that feature.

Resources