OpenCV 3.0.0 with cmake - where are the includes/libraries - c++

I compiled OpenCV 3.0.0 with TBB using Cmake and now I am unsure about where the include and library directories are (for VS 2012). I followed these instructions, however the library is not in the folder mentioned in the "set environment path" blurb (which is probably copied from an earlier version).
Am I right in assuming that the relevant folder is "OpenCV/Build" and "OpenCV/Source" no longer plays a role for new projects?
Are the needed includes and libraries in "OpenCV/Build/Install/include" and "OpenCV/Build/Install/x86/lib/vc11/lib" respectively? I added those, as well as the corresponding additional dependancies - my program
#include "opencv2/opencv.hpp"
int main( int argc, char** argv )
{
cv::Mat src = cv::imread( "C:\\pics\\test.tif",0);
cv::imshow("end",src);
return 0;
}
compiles, but crashes saying:
The program can't start because opencv_core300.dll is missing from your
computer. Try reinstalling the program to fix this problem.
What could be the reason?

Then you need to specify the libraries in which the linker should look into. To do this go to the Linker ‣ Input and under the “Additional Dependencies” entry add the name of all modules which you want to use:
Add the debug library names here.Like this.
The names of the libraries are as follow:
opencv_(The Name of the module)(The version Number of the library you use)d.lib
A full list, for the latest version would contain:
opencv_calib3d300d.lib
opencv_contrib300d.lib
opencv_core300d.lib
opencv_features2d300d.lib
opencv_flann300d.lib
opencv_gpu300d.lib
opencv_highgui300d.lib
opencv_imgproc300d.lib
opencv_legacy300d.lib
opencv_ml300d.lib
opencv_nonfree300d.lib
opencv_objdetect300d.lib
opencv_ocl300d.lib
opencv_photo300d.lib
opencv_stitching300d.lib
opencv_superres300d.lib
opencv_ts300d.lib
opencv_video300d.lib
opencv_videostab300d.lib
The letter d at the end just indicates that these are the libraries required for the debug. Now click ok to save and do the same with a new property inside the Release rule section. Make sure to omit the d letters from the library names and to save the property sheets with the save icon above them.
And the release ones.
You can find your property sheets inside your projects directory. At this point it is a wise decision to back them up into some special directory, to always have them at hand in the future, whenever you create an OpenCV project. Note that for Visual Studio 2010 the file extension is props, while for 2008 this is vsprops.
And the release ones.
Next time when you make a new OpenCV project just use the “Add Existing Property Sheet...” menu entry inside the Property Manager to easily add the OpenCV build rules.
Check this Official Instruction

Related

Calling MATLAB Engine error: libeng.dll is missing from your computer

I am struggling to call MATLAB from a simple .cpp program despite the many resources online for this problem.
My Objective:
Use Microsoft Visual Studio 2010 Professional 64-bit to build .cpp program that
calls MATLAB Engine for built-in functions and graphs (MATLAB R2013b 64-bit)
What I have done:
In the .cpp file property pages, I have:
1) Changed the platform to Active(x64)
2) Added the following paths to the VC++ Directories
Executable Directories: C:\Program Files\MATLAB\R2013b\bin
Include Directories: C:\Program Files\MATLAB\R2013b\extern\include
Reference Directories: C:\Program Files\MATLAB\R2013b\bin\win64
Library Directories: C:\Program Files\MATLAB\R2013b\extern\lib\win64\microsoft
Path Edits
3) Wrote the following program:
// mEng.cpp : Defines the entry point for the console application.
// libeng.dll is in C:\Program Files\MATLAB\R2013b\bin\win64
#include "stdafx.h"
#include <Engine.h>
#include <matrix.h>
#include <iostream>
#include <string>
#include <cmath>
#pragma comment (lib, "libmat.lib")
#pragma comment (lib, "libmx.lib")
#pragma comment (lib, "libmex.lib")
#pragma comment (lib, "libeng.lib")
#pragma comment (lib, "libut.lib")
using namespace std;
int main()
{
Engine *m_pEngine;
if (!(m_pEngine = engOpen("")))
{
fprintf(stderr, "\nCan't start MATLAB engine\n");
return EXIT_FAILURE;
}
//Now call the MATLAB script through MATLAB Engine
engEvalString(m_pEngine, "script");
cout << "Hit return to continue\n\n";
fgetc(stdin);
//Close the MATLAB Engine
engClose(m_pEngine);
return EXIT_SUCCESS;
}
Errors received:
“The program can’t start because libeng.dll is missing from your computer. Try reinstalling the program to fix this problem.”
I faced the same problem and spent one day to solve it.
So here is my answer.
Actually you overdefine different directories (see the "Path Edits" link).
It is enough to made just these:
Project Properties -> VC++ Directories -> Library Directories. Add here path C:\Program Files\MATLAB\R2016a\bin\win64 (version and path can differ, but the idea is to est path to the same folder of your MATLAB)
Project Properties -> C/C++ -> General -> Additional Include Directories. Add path C:\Program Files\MATLAB\R2016a\extern\include (your path of this folder)
Project Properties -> Linker -> General -> Additional Library Directories. Add path C:\Program Files\MATLAB\R2016a\extern\lib\win64\microsoft
Project Properties -> Linker -> Input -> Additional Dependencies. Add here: libeng.lib; libmx.lib;
And the last and the most important: add the path of MATLAB Engine dll libraries to your Windows. This step solve your problem. We can do it this way: My Computer -> right click: Settings. Opened window System. Left bottom corner: Advanced System Settings
Advanced Tab
In the Environment variables for your user press Create... button and add this one:
Variable name: PATH
Variable value: C:\Program Files\MATLAB\R2016a\bin\win64
This path is reference on where is your libeng.dll located.
Important moment: it can require to restart VS or even restart computer.
Hope it helps some people, who start to work in MATLAB and C++!
Follow my notes here:
https://www.mathworks.com/matlabcentral/answers/100603-how-can-i-compile-a-matlab-engine-application-using-microsoft-visual-studio-9-0-or-10-0
I would like to take this opportunity though to re-format the instructions given there:
To compile a MATLAB engine application in the Microsoft Visual Studio 9.0 (2008) or Microsoft Visual Studio 10.0 (2010) environments, perform the steps outlined below:
Open Microsoft Visual Studio and select
File->New->Project
and then select:
Visual C++ -> General -> Empty Project
Following this, enter the name of the project and its location in the
indicated text areas and click OK.
Note be very careful with this step as it will create the solution folder and
put a project folder in there, so you won't want to set this up, get it all
working and then change the folder as that will break the solution and you'll
have to start all over.
Right-click on the SOURCE FILES folder in the SOLUTION EXPLORER and click
Add -> "New Item..."
Choose "C++ file (.cpp)", enter the name of the file
(as enginedemo.cpp) as you wish. Click OK.
Copy the code from the source file: engwindemo.c, and paste it into this
file enginedemo.cpp. The file engwindemo.c may be obtained from the following
location:
$MATLABROOT/extern/examples/eng_mat
where $MATLABROOT is the MATLAB root directory, and may be determined by
entering the command:
matlabroot
at the MATLAB command prompt.
I'd suggest that at this point you open it in Notepad and if it has some
weird format, fix and save it so it looks like a normal C file when you open
it in Notepad (or gedit or whatever).
This is where things change in Visual Studio and I hope this extends somewhat
transparently to VS Code, Eclipse, or whatever IDE you'd like to use.
So I will re-number the property change section in roman numerals and fix the
order.
Also be sure to hit ENTER and then APPLY after making every change.
Make sure of the change before you go to the next section.
Double-check the spelling and MAKE SURE the directories exist on your
platform.
Go into the Solution Explorer view, Right click on the project name and
select PROPERTIES in the solution explorer to open the project properties.
Once this window has opened, make the following changes:
Go to the Configurations bar at the top of the property page.
You most definitely want to start with this setting.
Pick a configuration, debug or release, or "all configs" if you want the
changes to apply to BOTH debug and release, or you will have to do them all
over again for the other configuration. Which may not be such a bad idea, as
the individual release options are often more "optimized" versions of the
corresponding debug options. Note you can run
into serious trouble changing the property values while switching between
debug and release modes, don't be surprised if the IDE crashes, the solution
database gets corrupt, even the debug won't build and you have
to start all over. Get the debug to work first, back-up the entire solution,
then "clone" the debug settings to release, and then tweak the release
settings one at a time, making sure that the code still builds and runs
between each change.
If compiling to 64-bit Windows, change the target from x86 to x64 & use 64-
bit DLLs and library files.
If this is not in the Configuration options at the very top where it says
"Configuration Manager" (as in VS2015), then follow your IDE instructions...
as mentioned on the following link:
https://www.microsoft.com/en-us/download/details.aspx?id=55984
Under
Configuration Properties ->Debugging
Add the following Target path in the Environment:
(for 32 bit MATLAB)
PATH=$matlabroot\bin\win32
(for 64-bit MATLAB)
PATH=$matlabroot\bin\win64 If you want to use an absolute path instead,
use the following (with a semicolon at the end)
PATH=C:\Program Files\MATLAB\R2013a\bin\win32; (for 32 bit MATLAB)
PATH=C:\Program Files\MATLAB\R2013a\bin\win64; (for 64 bit MATLAB)
(probably can skip the "PATH=" here as it doesn't seem to remain there,
otherwise this is straight from the MATLAB reference )
Under C/C++ General, add the following directory to the field ADDITIONAL
INCLUDE DIRECTORIES:
$MATLABROOT\extern\include
i.e.
c:\Program Files\MATLAB\R2019a\extern\include;
Put a semicolon at the end of every line that you enter that is a path. after
the .lib files in that section also.
Under C/C++ Precompiled Headers, select "Not Using Precompiled Headers".
(in release mode this was set to "yes")
Under Linker General, add the library directory to the field ADDITIONAL
LIBRARY DIRECTORIES:
(For 32-bit Windows)
$MATLABROOT\extern\lib\win32\microsoft
(For 64-bit Windows)
$MATLABROOT\extern\lib\win64\microsoft
i.e.
c:\Program Files\MATLAB\Rxxxxx\extern\lib\win(32|64)\microsoft;
Under Linker Input, add the following library names to the field marked
ADDITIONAL DEPENDENCIES:
(use this string in front of whatever else is in there)
libeng.lib;libmat.lib;libmx.lib;
I don't know if the order really matters, but the original reference listed
them in reverse alphabetical order. "I've heard it both ways".
Ok, now you're done changing the VS project property pages, save the changes
(as you've done all along by clicking "Apply" after each change) and click
Ok. The property pages window will close. At this point your code will build
but still won't call Matlab. Back-up the solution again.
Now change the DOS/WINDOWS ENVIRONMENT PATH STRING.
I would save the solution, close VS, back it up, make the PATH changes and
reopen VS and try to build your program and run it and have it work.
The PATH string must be changed so that the bin\win(32:64) directory is the
first instance related to Matlab on the path.
Go in the "advanced system settings" \ Environment
To do this, check the Windows system path by clicking on Start -> Right click
on Computer -> Properties -> Advanced System Settings -> Environment
variables -> System Variables -> Open "Path" for editing.
and modify the PATH variable as so:
Make sure that the following directory is in the PATH:
(For 32-bit Windows)
$MATLABROOT\bin\win32
(For 64-bit Windows)
$MATLABROOT\bin\win64
It does not have to be the first directory in the path, but it needs to be
the first MATLAB directory in the path
PATH=c:\;....;c:\Program Files\MATLAB\Rxxxxx\bin\win(32/64);
The matlab.exe is in \bin; you might want that on the path also just not
before the \bin\win64 entry...
Note: If the machine has more than one MATLAB installed, the directory for
the target platform must be ahead of any other MATLAB directory (for
instance, when compiling a 64-bit application, the directory in the MATLAB
64-bit installation must be the first one on the PATH).
Also make sure that your target install of
MATLAB is registered as a COM server:
https://www.mathworks.com/help/matlab/ref/regmatlabserver.html
For Matlab 2020a & later, try comserver('query') and comserver('register').
For 2019 & earlier use regmatlabserver() (run Matlab as administrator).
Build and execute the application.
So I include a simple app that should demonstrate the functionality:
#include "stdafx.h"
#include "engine.h"
#include
using namespace std;
int main()
{
Engine *eng;
eng=engOpen(""); // put a breakpoint here
cout << "...now you see it...\n"
engClose(eng); // put a breakpoint here
cout << "...now you don't!\n"
return 0;
}

OpenCV - missing dlls?

I am a beginner learning OpenCV. I have the latest version (2.4.7.2 as of Dec, 2013) and am trying a simple code to load image. The code is OK, but when I compiled and then run the source code, it says that
"the program can't start because opencv_core247d.dll is missing."
I already tried changing the computer's environment and making all the corresponding path setting for my solution according to several suggestions. I tried rebooting the PC, adding the "missing file" to my source code's Debug file, tried getting around with CMake (fortunately though it failed to generate anything and I guess that goes for my next question); the problem persists.
So, is there any fool-proof and simple way of dealing with this problem? Thank you. Btw, here is my little source code:
# include "highgui.h"
int main (int argc, char** argv)
{
IplImage* img = cvLoadImage("D:\\OpenCV Test\\LoadImage\\fruits.jpg") ;
cvNamedWindow("Fuits", CV_WINDOW_AUTOSIZE) ;
cvShowImage("Fuits", img) ;
cvWaitKey(0) ;
cvDestroyWindow("Fruits") ;
cvReleaseImage (&img) ;
}
You are running into OpenCV dll issues, similar to here. Three ways to fix dll-related issues about OpenCV, also works for other dll related issues.
copy the required dlls into the same folder with your application. This is a little better because it kind of prepares you for when you'll need to deploy your application on systems that don't have OpenCV installed (for then don't forget to build the release version of your application).
add the dll path to Debugging Environment: Project –> Properties –> Configuration Properties –> Debugging –> Environment –> add dlls' paths here. The syntax is NAME=VALUE and macros can be used (for example, $(OutDir).
For example, to prepend C:\Windows\Temp to the PATH: PATH=C:\WINDOWS\Temp;%PATH%
Similarly, to append $(SolutionDir)\DLLS to the PATH: PATH=%PATH%;$(SolutionDir)\DLLS
add the dll path to Environment Variables (be careful that the path in there are separated by ;)
EDIT: Among the three methods, the first two will only work for this project (local) and the last one works for all projects in your PC (global).
i have problem .
i have win7-64bit and visual studio 2013 and opencv-3
the program can't start because opencv_word300d.dll is missing from your computer . try reinstalling the program to fix problem.
As a tip make sure the last three digits in your linker contain the same numbers as your actual dll files.
Ex: version 3.2.0 should be written 320.dll and so on
Make sure your environment variables are set properly (i.e., Path should have ../opencv/bin/) and then use these lines in your CMakeList file to generate the appropriate project files.
FIND_PACKAGE( OpenCV REQUIRED )
TARGET_LINK_LIBRARIES( myProject ${OpenCV_LIBS} )

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?

Eclipse CDT Can't Find include file unless full relative path is used

I've been using Eclipse for a while and this has me stymied. I created a library name ITS8410_LIB a few weeks ago and then let it sit while I worked on a supporting library called Reach_Lib. The directory include paths I added back when I first created the project work fine. Today I finished Reach_Lib and went to add its path to ITS8410_Lib. I used the project properties C++ settings to add a workspace path (like I've done many times before). I have only one build configuration. The path is shown in the image (the one highlighted in blue is the specific one I'm talking about in this question).
When I go to include the file in the source neither Eclipse (I see the yellow question mark) nor the compiler (I get a compiler error) can locate the file. If I add the a directory path using the full absolute path syntax the results are the same. I can modify the source code and specify the #include via a full relative path from the current directory, and it is found. Eclipse just won't use the path specified in the project settings. This same Reach_Lib has an associated unit test project and the path is specified with a workspace setting from there and it works fine.
Directory paths that were added before today appear fine. Paths (there are two libs showing this behavior) I add today just seem to be ignored. I took a look at the compiler settings (see image below) and the path specified to the compiler appears to be OK.
Running under Windows7 64 bit (but using a 32 bit version of Eclipse Indigo).
I have tried:
rebuilding indices
Exiting and restarting Eclipse multiple times
workspace and absolute file paths
modifying the order of the include paths
different .h include files in project
Update
I took a look into the .cproject file and while I don't know much about what these files are supposed to look like I think I have a problem. Maybe the question is: How do I tell Eclipse to rebuild the .cproject file? I appear to have two similar sections and Eclipse is getting confused. I can see different version numbers tagged as suffixes. It appears to me that the visual editors are letting me modify one section but the IDE and compiler only care about the other section. Here's the relevant portions
...
<folderInfo id="nbeclipse.toolchain.nbl.rel.396284009." name="/" resourcePath="">
<toolChain id="nbeclipse.toolchain.nbl.rel.tc.1465290409" name="NetBurner Device Library" superClass="nbeclipse.toolchain.nbl.rel.tc">
<targetPlatform id="nbeclipse.toolchain.nbl.rel.tc.targetPlatform.283367649" isAbstract="false" name="NetBurner Module Library" superClass="nbeclipse.toolchain.nbl.rel.tc.targetPlatform"/>
<builder buildPath="${workspace_loc:/ITS8410_Lib/Release}" id="nbeclipse.toolchain.nbl.rel.tc.builder.2064025940" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="Release ELF builder (MINGW)" superClass="nbeclipse.toolchain.nbl.rel.tc.builder"/>
<tool id="nbeclipse.toolchain.nbl.rel.tc.gcc.278195048" name="GNU C Compiler" superClass="nbeclipse.toolchain.nbl.rel.tc.gcc">
<inputType id="nbeclipse.toolchain.nbl.rel.tc.gcc.input.1060035859" name="GNU C Input" superClass="nbeclipse.toolchain.nbl.rel.tc.gcc.input"/>
</tool>
<tool id="nbeclipse.toolchain.nbl.rel.tc.gpp.767008127" name="GNU C++ Compiler" superClass="nbeclipse.toolchain.nbl.rel.tc.gpp">
<option id="nbeclipse.toolchain.super.gcc.directories.includepaths.1666029541" name="Include paths (-I)" superClass="nbeclipse.toolchain.super.gcc.directories.includepaths" valueType="includePath">
**inside here is an option list with all my include paths**
...
</folderInfo>
Then right after the folderInfo close tag another folderInfo section starts
<folderInfo id="nbeclipse.toolchain.nbl.rel.396284009.2022231003" name="/" resourcePath="src">
<toolChain id="nbeclipse.toolchain.nbl.rel.tc.1982112905" name="NetBurner Device Library" superClass="nbeclipse.toolchain.nbl.rel.tc" unusedChildren="">
<targetPlatform id="nbeclipse.toolchain.nbl.rel.tc.targetPlatform" isAbstract="false" name="NetBurner Module Library" superClass="nbeclipse.toolchain.nbl.rel.tc.targetPlatform"/>
<tool id="nbeclipse.toolchain.nbl.rel.tc.gcc.1671008421" name="GNU C Compiler" superClass="nbeclipse.toolchain.nbl.rel.tc.gcc.278195048">
<inputType id="nbeclipse.toolchain.nbl.rel.tc.gcc.input.436341699" name="GNU C Input" superClass="nbeclipse.toolchain.nbl.rel.tc.gcc.input"/>
</tool>
<tool id="nbeclipse.toolchain.nbl.rel.tc.gpp.498310867" name="GNU C++ Compiler" superClass="nbeclipse.toolchain.nbl.rel.tc.gpp.767008127">
**the newly added paths don't show up here, if I add them manually things start working**
The key to the answer was posted by dbrank0 but he didn't promote it to an answer so I just upvoted the comment. Something went wrong in the .cproject file and editing it manually fixed the problem.
Try to replace relative workspace path to real path (add same include as filesystem) in include directories project settings.
full absolute path is okay at any time.
when use the relative directory you should be careful.
in eclipse the current directory is not the same as run directory.
string strRunDir, strCurDir;
strRunDir = AfxGetApp()->m_pszExeName;
strCurDir = GetCurrentDirectory(...);
and strRunDir != strCurDir;
when you want to use the relative directory, you should reference to the runDir;

How to get a python .pyd for Windows from c/c++ source code? (update: brisk now in Python in case that's what you want)

How to get from C/C++ extension source code to a pyd file for windows (or other item that I could import to Python)?
edit: The specific library that I wanted to use (BRISK) was included in OpenCV 2.4.3 so my need for this skill went away for the time being. In case you came here looking for BRISK, here is a simple BRISK in Python demo that I posted.
I have the Brisk source code (download) that I would like to build and use in my python application. I got as far as generating a brisk.pyd file... but it was 0 bytes. If there is a better / alternative way to aiming for a brisk.pyd file, then of course I am open to that as well.
edit: Please ignore all the attempts in my original question below and see my answer which was made possible by obmarg's detailed walkthrough
Where am I going wrong?
Distutils without library path: First I tried to build the source as is with distutils and the following setup.py (I have just started learning distutils so this is a shot in the dark). The structure of the BRISK source code is at the bottom of this question for reference.
from distutils.core import setup, Extension
module1 = Extension('brisk',
include_dirs = ['include', 'C:/opencv2.4/build/include', 'C:/brisk/thirdparty/agast/include'],
#libraries = ['agast_static', 'brisk_static'],
#library_dirs = ['win32/lib'],
sources = ['src/brisk.cpp'])
setup (name = 'BriskPackage',
ext_modules = [module1])
That instantly gave me the following lines and a 0 byte brisk.pyd somewhere in the build folder. So close?
running build
running build_ext
Distutils with library path: Scratch that attempt. So I added the two library lines that are commented out in the above setup.py. That seemed to go ok until I got this linking error:
creating build\lib.win32-2.7
C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\BIN\link.exe /DLL /nologo /INCREMENTAL:NO /LIBPATH:win32/lib /LIB
PATH:C:\Python27_32bit\libs /LIBPATH:C:\Python27_32bit\PCbuild agast_static.lib brisk_static.lib /EXPORT:initbrisk build
\temp.win32-2.7\Release\src/brisk.obj /OUT:build\lib.win32-2.7\brisk.pyd /IMPLIB:build\temp.win32-2.7\Release\src\brisk.
lib /MANIFESTFILE:build\temp.win32-2.7\Release\src\brisk.pyd.manifest
LINK : error LNK2001: unresolved external symbol initbrisk
build\temp.win32-2.7\Release\src\brisk.lib : fatal error LNK1120: 1 unresolved externals
error: command '"C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\BIN\link.exe"' failed with exit status 1120
Uncontrolled flailing: I thought maybe the libraries needed to be built, so I did a crash course (lots of crashing) with cmake + mingw - mingw + vc++ express 2010 as follows:
cmake gui: source: c:/brisk, build: c:/brisk/build
cmake gui: configure for Visual Studio 10
cmake gui: use default options and generate (CMAKE_BACKWARDS_COMPATIBILITY, CMAKE_INSTALL_PREFIX, EXECUTABLE_OUTPUT_PATH, LIBRARY_OUTPUT_PATH)
VC++ Express 10: Change to Release and build the solution generated by cmake and get about 20 pages of what look like non-critical warnings followed by all succeeded. Note - no dlls are generated by this. It does generate the following libraries of similar size to the ones included with the download:
win32/lib/Release/
agast_static.lib
brisk_static.lib
Further flailing.
Relevant BRISK source file structure for reference:
build/ (empty)
include/brisk/
brisk.h
hammingsse.hpp
src
brisk.cpp
demo.cpp
thirdparty/agast/
include/agast/
agast5_8.h ....
cvWrapper.h
src/
agast5_8.cc ...
CMakeLists.txt
win32/
bin/
brisk.mexw32
opencv_calib3d220.dll ...
lib/
agast_static.lib
brisk_static.lib
CMakeLists.txt
FindOpenCV.cmake
Makefile
Are you sure that this brisk library even exports python bindings? I can't see any reference to it in the source code - it doesn't even seem to import python header files. This would certainly explain why you've not had much success so far - you can't just compile plain C++ code and expect python to interface with it.
I think your second distutils example is closest to correct - it's obviously compiling things and getting to the linker stage, but then you encounter this error. That error just means it can't find a function named initbrisk which I'm guessing would be the top level init function for the module. Again this suggests that you're trying to compile a python module from code that isn't meant for it.
If you want to wrap the C++ code in a python wrapper yourself you could have a look at the official documentation on writing c/c++ extensions. Alternatively you could have a look into boost::python, SIP or shiboken which try to somewhat (or completely) automate the process of making python extensions from C++ code.
EDIT: Since you seem to have made a decent amount of effort to solve the problem yourself and have posted a good question, I've decided to give a more detailed response on how to go about doing this.
Quick Tutorial On Wrapping C++ Libraries Using boost::python
Personally I've only ever used boost::python for stuff like this, so I'll try and give you a good summary of how to go about doing that. I'm going to assume that you're using Visual C++ 2010. I'm also going to assume that you've got a 32bit version of python installed, as I believe the boost pro libraries only provide 32bit binaries.
Installing boost
First you'll need to grab a copy of the boost library. The easiest way to do this is to download an installer from the boost pro website. These should install all the header files and binary files that are required for using the boost c++ library on windows. Take note of where you install these files to, as you'll need them later on - it might be best to install to a path without a space in it. For easyness I'm going to assume you put these files in C:\boost but you can substitute that for the path you actually used.
Alternatively, you can follow these instructions to build boost from source. I'm not 100% sure, but it might be the case that you need to do this in order to get a version of boost::python that is compatible with the version of python you have installed.
Setting up a visual studio project
Next, you'll want to setup a visual studio project for brisk.pyd. If you open visual studio, go to New -> Project then find the option for Win32 Project. Set up your location etc. and click ok. In the wizard that appears select a DLL project type, and then tick the empty project checkbox.
Now that you've created your project, you'll need to set up the include & library paths to allow you to use python, boost::python and the brisk.lib file.
In Visual Studios solution explorer, right click on your project, and select properties from the menu that appears. This should open up the property pages for your project. Go to the Linker -> General section and look for the Additional Library Directories section. You'll need to fill this in with the paths to the .lib files for boost, python and your brisk_static.lib. Generally these can be found in lib (or libs) subdirectories of
wherever you've installed the libraries. Paths are seperated with semicolons. I've attached a screenshot of my settings below:
Next, you'll need to get visual studio to link to the .lib files. These sections can be found in the Additional Dependencies field of the Linker -> Input section of the properties. Again it's a semicolon delimited list. You should need to add in libraries for python (in my case this is python27.lib but this will vary by version) and brisk_static.lib. These do not require the full path as you added that in the previous stage. Again, here's a screenshot:
You may also need to add the boost_python library file but I think boost uses some header file magic to save you the trouble. If I'm incorrect then have a look in you boost library path for a file named similar to boost_python-vc100-mt.lib and add that in.
Finally, you'll need to setup the include paths to allow your project to include the relevant C++ header files. To get the relevant settings to appear in project properties, you'll need to add a .cpp file to your project. Right click the source files folder in your solution explorer, and then go to add new item. Select a C++ File (.cpp) and name it main.cpp (or whatever else you want).
Next, go back to your project properties and go to C/C++ -> General. Under the additional libraries directory you need to add the include paths for brisk, python and boost. Again, semicolons for seperators, and again here's a screenshot:
I suspect that you might need to update these settings to include the opencv2 & agast libraries as well but I'll leave that as a task for you to figure out - it should be much the same process.
Wrapping existing c++ classes with boost::python.
Now comes the slightly trickier bit - actually writing C++ to wrap your brisk library in boost python. You can find a tutorial for this here but i'll try and go over it a bit as well.
This will be taking place in the main.cpp file you created earlier. First, add the relevant include statements you'll need at the top of the file:
#include <brisk/brisk.h>
#include <Python.h>
#include <boost/python.hpp>
Next, you'll need to declare your python module. I'm assuming you'd want this to be called brisk, so you do something like this:
BOOST_PYTHON_MODULE(brisk)
{
}
This should tell boost::python to create a python module named brisk.
Next it's just a case of going through all the classes & structs that you want to wrap and declaring boost python classes with them. The declerations of the classes should all be contained in brisk.h. You should only wrap the public members of a class, not any protected or private members. As a quick example, I've done a couple of the structs here:
BOOST_PYTHON_MODULE(brisk)
{
using namespace boost::python;
class_< cv::BriskPatternPoint >( "BriskPatternPoint" )
.def_readwrite("x", &cv::BriskPatternPoint::x)
.def_readwrite("y", &cv::BriskPatternPoint::y)
.def_readwrite("sigma", &cv::BriskPatternPoint::sigma);
class< cv::BriskScaleSpace >( "BriskScaleSpace", init< uint8_t >() )
.def( "constructPyramid", &cv::BriskScaleSpace::constructPyramid );
}
Here I have wrapped the cv::BriskPatternPoint structure and the cv::BriskScaleSpace class. Some quick explanations:
class_< cv::BriskPatternPoint >( "BriskPatternPoint" ) tells boost::python to declare a class, using the cv::BriskPatternPoint C++ class, and expose it as BriskPatternPoint in python.
.def_readwrite("y", &cv::BriskPatternPoint::y) adds a readable & writeable property to the BriskPatternPoint class. The property is named y, and will map to the BriskPatternPoint::y c++ field.
class< cv::BriskScaleSpace >( "BriskScaleSpace", init< uint8_t >() ) declares another class, this time BriskScaleSpace but also provides a constructor that accepts a uint8_t (an unsigned byte - which should just map to an integer in python, but I'd be careful to not pass in one greater than 255 bytes - I don't know what would happen in that situation)
The following .def line just declares a function - boost::python should (I think) be able to determine the argument types of functions automatically, so you don't need to provide them.
It's probably worth noting that I haven't actually compiled any of these examples - they might well not work at all.
Anyway, to get this fully working in python it should just be a case of doing similar for every structure, class, property & function that you want accessible from python - which is potentially quite a time consuming task!
If you want to see another example of this in action, I did this here to wrap up this class
Building & using the extension
Visual studio should take care of building the extension - then using it is just a case of taking the .DLL and renaming it to .pyd (you can get VS to do this for you, but I'll leave that up to you).
Then you just need to copy your python file to somewhere on your python path (site-packages for example), import it and use it!
import brisk
patternPoint = brisk.BriskPatternPoint()
....
Anyway, I have spent a good hour or so writing this out - so I'm going to stop here. Apologies if I've left anything out or if anything isn't clear, but I'm doing this mostly from memory. Hopefully it's been of some help to you. If you need anything clarified please just leave a comment, or ask another question.
In case someone needs it, this what I have so far. Basically a BriskFeatureDetector that can be created in Python and then have detect called. Most of this is just confirming/copying what obmarg showed me, but I have added the details that get all the way to the pyd library.
The detect method is still incomplete for me though since it does not convert data types. Anyone who knows a good way to improve this, please do! I did find, for example, this library which seems to convert a numpy ndarray to a cv::Mat, but I don't have the time to figure out how to integrate it now. There are also other data types that need to be converted.
Install OpenCV 2.2
for the setup below, I installed to C:\opencv2.2
Something about the API or implementation has changed by version 2.4 that gave me problems (maybe the new Algorithm object?) so I stuck with 2.2 which BRISK was developed with.
Install Boost with Boost Python
for the setup below, I installed to C:\boost\boost_1_47
Create a Visual Studio 10 Project:
new project --> win32
for the setup below, I named it brisk
next --> DLL application type; empty project --> finished
at the top, change from Debug Win32 to Release Win32
Create main.cpp in Source Files
Do this before the project settings so the C++ options become available in the project settings
#include <boost/python.hpp>
#include <opencv2/opencv.hpp>
#include <brisk/brisk.h>
BOOST_PYTHON_MODULE(brisk)
{
using namespace boost::python;
//this long mess is the only way I could get the overloaded signatures to be accepted
void (cv::BriskFeatureDetector::*detect_1)(const cv::Mat&,
std::vector<cv::KeyPoint, std::allocator<cv::KeyPoint>>&,
const cv::Mat&) const
= &cv::BriskFeatureDetector::detect;
void (cv::BriskFeatureDetector::*detect_vector)(const std::vector<cv::Mat, std::allocator<cv::Mat>>&,
std::vector< std::vector< cv::KeyPoint, std::allocator<cv::KeyPoint>>, std::allocator< std::vector<cv::KeyPoint, std::allocator<cv::KeyPoint>>>>&,
const std::vector<cv::Mat, std::allocator<cv::Mat>>&) const
= &cv::BriskFeatureDetector::detect;
class_< cv::BriskFeatureDetector >( "BriskFeatureDetector", init<int, int>())
.def( "detect", detect_1)
;
}
Project Settings (right-click on the project --> properties):
Includes / Headers
Configuration Properties --> C/C++ --> General
add to Additional Include Directories (adjust to your own python / brisk / etc. base paths):
C:\opencv2.2\include;
C:\boost\boost_1_47;
C:\brisk\include;C:\brisk\thirdparty\agast\include;
C:\python27\include;
Libraries (linker)
Configuration Properties --> Linker --> General
add to Additional Library Directories (adjust to your own python / brisk / etc. base paths):
C:\opencv2.2\lib;
C:\boost\boost_1_47\lib;
C:\brisk\win32\lib;
C:\python27\Libs;
Configuration Properties --> Linker --> Input
add to Additional Dependencies (adjust to your own python / brisk / etc. base paths):
opencv_imgproc220.lib;opencv_core220.lib;opencv_features2d220.lib;
agast_static.lib; brisk_static.lib;
python27.lib;
.pyd output instead of .dll
Configuration Properties --> General
change Target Extension to .pyd
Build and rename if necessary
Right-click on the solution and build/rebuild
you may need to rename the output from "Brisk.pyd" to "brisk.pyd" or else python will give you errors about not being able to load the DLL
Make brisk.pyd available to python by putting it in site packages or by putting a .pth file that links to its path
Update Path environment variable
In windows settings, make sure the following are included in your path (again, adjust to your paths):
`C:\boost\boost_1_47\lib;C:\brisk\win32\bin`