Something More for Research

Explorer of Research #HEMBAD

OpenCV with CUDA Installation and Setup in Windows

Posted by Hemprasad Y. Badgujar on June 20, 2014


Installation in Windows

The description here was tested on Windows 7 SP1. Nevertheless, it should also work on any other relatively modern version of Windows OS. If you encounter errors after following the steps described below, feel free to contact us via our OpenCV Q&A forum. We’ll do our best to help you out.

Note

To use the OpenCV library you have two options: Installation by Using the Pre-built Libraries or Installation by Making Your Own Libraries from the Source Files. While the first one is easier to complete, it only works if you are coding with the latest Microsoft Visual Studio IDE and doesn’t take advantage of the most advanced technologies we integrate into our library.

Installation by Using the Pre-built Libraries

  1. Launch a web browser of choice and go to our page on Sourceforge.

  2. Choose a build you want to use and download it.

  3. Make sure you have admin rights. Unpack the self-extracting archive.

  4. You can check the installation at the chosen path as you can see below.

    An example of how the installation directory should look in case of successful install.

  5. To finalize the installation go to the Set the OpenCV enviroment variable and add it to the systems path section.

Installation by Making Your Own Libraries from the Source Files

You may find the content of this tutorial also inside the following videos: Part 1 and Part 2, hosted on YouTube.

 

Warning

These videos above are long-obsolete and contain inaccurate information. Be careful, since solutions described in those videos are no longer supported and may even break your install.

If you are building your own libraries you can take the source files from our Git repository.

Building the OpenCV library from scratch requires a couple of tools installed beforehand:

  • An IDE of choice (preferably), or just a CC++ compiler that will actually make the binary files. Here we will use the Microsoft Visual Studio. However, you can use any other IDE that has a valid CC++ compiler.
  • CMake, which is a neat tool to make the project files (for your chosen IDE) from the OpenCV source files. It will also allow an easy configuration of the OpenCV build files, in order to make binary files that fits exactly to your needs.
  • Git to acquire the OpenCV source files. A good tool for this is TortoiseGit. Alternatively, you can just download an archived version of the source files from our page on Sourceforge

OpenCV may come in multiple flavors. There is a “core” section that will work on its own. Nevertheless, there is a couple of tools, libraries made by 3rd parties that offer services of which the OpenCV may take advantage. These will improve its capabilities in many ways. In order to use any of them, you need to download and install them on your system.

  • The Python libraries are required to build the Python interface of OpenCV. For now use the version 2.7.x. This is also a must if you want to build the OpenCV documentation.

    Python Download and install the scientific-oriented Python Distribution Python(x,y):

    http://ftp.ntua.gr/pub/devel/pythonxy/

    This distribution contains the MinGW compiler toolchain, which will be used by Cmake and Eclipse.

    Download and install the OpenCV plugin update as well:

    http://pythonxy.googlecode.com/files/
    Or

    Windows: Install Python and Sphinx

    Install Python

    Most Windows users do not have Python, so we begin with the installation of Python itself. If you have already installed Python, please skip this section.

    Go to http://python.org, the main download site for Python. Look at the left sidebar and under “Quick Links”, click “Windows Installer” to download.

    _images/pythonorg.png

    Note

    Currently, Python offers two major versions, 2.x and 3.x. Sphinx 1.3 can run under Python 2.6, 2.7, 3.2, 3.3, with the recommended version being 2.7. This chapter assumes you have installed Python 2.7.

    Follow the Windows installer for Python.

    _images/installpython.jpgAfter installation, you better add the Python executable directories to the environment variable PATH in order to run Python and package commands such as sphinx-build easily from the Command Prompt.

    • Right-click the “My Computer” icon and choose “Properties”

    • Click the “Environment Variables” button under the “Advanced” tab

    • If “Path” (or “PATH”) is already an entry in the “System variables” list, edit it. If it is not present, add a new variable called “PATH”.

    • Add these paths, separating entries by ”;”:

      • C:\Python27 – this folder contains the main Python executable
      • C:\Python27\Scripts – this folder will contain executables added by Python packages installed with easy_install (see below)

      This is for Python 2.7. If you use another version of Python or installed to a non-default location, change the digits “27” accordingly.

    • Now run the Command Prompt. After command prompt window appear, type python and Enter. If the Python installation was successful, the installed Python version is printed, and you are greeted by the prompt >>>. TypeCtrl+Z and Enter to quit.

    Install the easy_install command

    Python has a very useful easy_install command which can download and install 3rd-party libraries with a single command. This is provided by the “setuptools” project: https://pypi.python.org/pypi/setuptools.

    To install setuptools, download https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py and save it somewhere. After download, invoke the command prompt, go to the directory with ez_setup.py and run this command:

    C:\> python ez_setup.py
    

    Now setuptools and its easy_install command is installed. From there we can go to the Sphinx install.

    Installing Sphinx with easy_install

    If you finished the installation of setuptools, type this line in the command prompt:

    C:\> easy_install sphinx
    

    After installation, type sphinx-build on the command prompt. If everything worked fine, you will get a Sphinx version number and a list of options for this command.

  • Numpy is a scientific computing package for Python. Required for the Python interface.

Try the (unofficial) binaries in this site: http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy
You can get numpy 1.6.2 x64 with or without Intel MKL libs to Python 2.7

I suggest WinPython, a Python 2.7 distribution for Windows with both 32- and 64-bit versions.

It is also worth considering the Anaconda Python distribution. http://continuum.io/downloads

  • Intel © Threading Building Blocks (TBB) is used inside OpenCV for parallel code snippets. Using this will make sure that the OpenCV library will take advantage of all the cores you have in your systems CPU.

Introduction to TBB

Parallel computing in C++ is difficult because the language assumes a single thread model itself. That means C++ programmers have to deal with all the tedious work with multi-threading, are very easy to go wrong, and fall in bugs. Normally, not every programmer has to build a multi-threaded program from the scratch. In fact, one generally uses libraries to do so.

Low level libraries are raw thread libraries. Here one has to use the thread library to create and terminate a thread. A custom thread function must be written for the thread execution. POSIX pthread and Win32 thread are examples of raw thread libraries. (OS thread support can be considered as a library, because any API function of the OS is in a dynamic library.)

Higher level libraries abstract away the tricky thread from the programmer. Instead, these libraries allow programmers to focus on the work at hand that can be parallelized. For example, one can use a parallel_for to run a for loop when the loop does not have inter dependence across iterations, The thread library can automatically determine how many threads to create and how to schedule them, without user creating thread functions and threads. This only only makes the code concise, but also less error-prone and more efficient.

Intel TBB(Thread Building Blocks) and Microsoft PPL(Parallel Patterns Library) are two examples of such libraries in C++. Both of them uses C++ templates and run-time threading support. They are actually similar. I have not tried PPL, so this post is about TBB.


Using Open Source TBB

  • Download TBB
    • Go to TBB download page to download the open source binary releases. I choose Commercial Aligned Release, because this has the most stable releases. I downloaded tbb22_013oss, TBB 2.2 Update 3, specifically tbb22_013oss_win.zip for Windows. The release has the header files as well as the import library and DLL files prebuilt for Microsoft Visual C++ 8.0 and 9.0 on both x86(IA32) and x64(intel64). If you are aggressive and need the source code of TBB, you can try stable releases or development releases.
  • Install TBB
    • Extract the files in the zip file to a local directory, for example, C:\TBB. You should find tbb22_013oss under it. This is the installation directory, and doc, example, include etc should be directly under the installation folder.
    • Set a Windows environment variable TBB22_INSTALL_DIR to the above directory, e.g., C:\TBB\tbb22_013oss.
  • Develop with TBB
    • Add $(TBB22_INSTALL_DIR)\include to your C++ project’s additional include directories.
    • Add $(TBB22_INSTALL_DIR)\<arch>\<compiler>\lib (e.g., $(TBB22_INSTALL_DIR)\ia32\vc9\lib) to your project’s additional library directories.
    • Add to your project’s additional dependencies tbb.lib (Release) or tbb_debug.lib (Debug).
    • Write your C++ code to use TBB. See code below as an example.
  • Deploy with TBB
    • The TBB runtime is in TBB DLLs (tbb.dll/tbbmalloc.dll/tbbmalloc_proxy.dll for Release, tbb_debug.dll/tbbmalloc_debug.dll/tbbmalloc_proxy_debug.dll for Debug). They can be found in $(TBB22_INSTALL_DIR)\\\bin.
    • Your executable should have these DLLs in the same folder for execution.
  • Intel © Integrated Performance Primitives (IPP) may be used to improve the performance of color conversion, Haar training and DFT functions of the OpenCV library. Watch out, since this isn’t a free service.
  • OpenCV offers a somewhat fancier and more useful graphical user interface, than the default one by using the Qt framework. For a quick overview of what this has to offer look into the documentations highgui module, under the Qt New Functions section. Version 4.6 or later of the framework is required.

Download the Qt library source: http://releases.qt-project.org/qt4/source/qt-everywhere-opensource-src-4.8.2.zip

Extract it into a directory like C:\Qt

Open a shell, cd to the directory containing the extracted Qt files and enter the following command:

configure.exe -release -no-webkit -no-phonon -no-phonon-backend -no-script -no-scripttools
              -no-qt3support -no-multimedia -no-ltcg

This will take around 10 minutes. Then enter the next command that will take a lot longer (can easily take even more than a full hour):

make

Create a system environment variable QTDIR : C:\Qt\qt-everywhere-opensource-src-4.8.2

Add %QTDIR%\bin at the front of the system PATH.

JRE Java run time environment is needed for Eclipse to work.

Download and install it:

http://www.oracle.com/technetwork/java/javase/downloads/jre7-downloads-1637588.html

Installing Ant

The binary distribution of Ant consists of the following directory layout:

  ant
   +--- README, LICENSE, fetch.xml, other text files. //basic information
   +--- bin  // contains launcher scripts
   |
   +--- lib  // contains Ant jars plus necessary dependencies
   |
   +--- docs // contains documentation
   |      |
   |      +--- images  // various logos for html documentation
   |      |
   |      +--- manual  // Ant documentation (a must read ;-)
   |
   +--- etc // contains xsl goodies to:
            //   - create an enhanced report from xml output of various tasks.
            //   - migrate your build files and get rid of 'deprecated' warning
            //   - ... and more ;-)

Only the bin and lib directories are required to run Ant. To install Ant, choose a directory and copy the distribution files there. This directory will be known as ANT_HOME.

Windows 95, Windows 98 & Windows ME Note:
Note that current releases of Ant no longer support these systems. If you are using an older version of Ant, however, the script used to launch Ant will have problems if ANT_HOME is a long filename (i.e. a filename which is not of the format known as “8.3”). This is due to limitations in the OS’s handling of the "for" batch-file statement. It is recommended, therefore, that Ant be installed in a short, 8.3 path, such as C:\Ant.
On these systems you will also need to configure more environment space to cater for the environment variables used in the Ant launch script. To do this, you will need to add or update the following line in the config.sys file

shell=c:\command.com c:\ /p /e:32768

Setup

Before you can run Ant there is some additional set up you will need to do unless you are installing the RPM version from jpackage.org:

  • Add the bin directory to your path.
  • Set the ANT_HOME environment variable to the directory where you installed Ant. On some operating systems, Ant’s startup scripts can guess ANT_HOME (Unix dialects and Windows NT/2000), but it is better to not rely on this behavior.
  • Optionally, set the JAVA_HOME environment variable (see the Advanced section below). This should be set to the directory where your JDK is installed.

Operating System-specific instructions for doing this from the command line are in the Windows, Linux/Unix (bash), and Linux/Unix (csh) sections. Note that using this method, the settings will only be valid for the command line session you run them in.

Note: Do not install Ant’s ant.jar file into the lib/ext directory of the JDK/JRE. Ant is an application, whilst the extension directory is intended for JDK extensions. In particular there are security restrictions on the classes which may be loaded by an extension.

Windows Note:
The ant.bat script makes use of three environment variables – ANT_HOME, CLASSPATH and JAVA_HOME. Ensure that ANT_HOME and JAVA_HOME variables are set, and that they do not have quotes (either ‘ or “) and they do not end with \ or with /. CLASSPATH should be unset or empty.

Check Installation

You can check the basic installation with opening a new shell and typing ant. You should get a message like this

Buildfile: build.xml does not exist!
Build failed

So Ant works. This message is there because you need to write an individual buildfile for your project. With a ant -version you should get an output like

Apache Ant(TM) version 1.9.2 compiled on July 8 2013

If this does not work ensure your environment variables are set right. They must resolve to:

  • required: %ANT_HOME%\bin\ant.bat
  • optional: %JAVA_HOME%\bin\java.exe
  • required: %PATH%=…maybe-other-entries…;%ANT_HOME%\bin;…maybe-other-entries

ANT_HOME is used by the launcher script for finding the libraries. JAVA_HOME is used by the launcher for finding the JDK/JRE to use. (JDK is recommended as some tasks require the java tools.) If not set, the launcher tries to find one via the %PATH% environment variable. PATH is set for user convenience. With that set you can just start ant instead of always typing the/complete/path/to/your/ant/installation/bin/ant.

  • The latest CUDA Toolkit will allow you to use the power lying inside your GPU. This will drastically improve performance for some algorithms (e.g the HOG descriptor). Getting more and more of our algorithms to work on the GPUs is a constant effort of the OpenCV team.
  • OpenEXR source files are required for the library to work with this high dynamic range (HDR) image file format.
  • The OpenNI Framework contains a set of open source APIs that provide support for natural interaction with devices via methods such as voice command recognition, hand gestures and body motion tracking.
    OpenNI (Version 1.5.4.0 - May 7th 2012)
    ---------------------------------------
    
    Website: http://www.primesense.com
    Forum: http://groups.google.com/group/openni-dev
    Wiki: http://wiki.openni.org
    
    Binaries are available at:
    http://www.openni.org/Downloads/OpenNIModules.aspx
    (The "OpenNI Binaries" section)
    
    Sources are available at:
    https://github.com/OpenNI/OpenNI
    or
    https://github.com/OpenNI/OpenNI/tree/unstable
    for unstable branch
    
    Release Notes:
    --------------
    * At the moment, the default is to compile the code with SSE3 support (this is also true for the supplied binaries). 
      If you have a CPU without such support, please remove the sse compiler flags from the make files.
      (A good hint for this error is that you encounter an "illegal instructions" messages)
    * MacOSX: Only OSX 10.6 (Snow Leopard) and above with an Intel based CPU is currently supported.
    * MacOSX: Drawing the depth/image maps via the mono .NET wrapper can be slow and will cause the FPS to drop.
      
    Build Notes:
    ------------
    Windows:
    	Requirements:
    		1) Microsoft Visual Studio 2010
    		   From: http://msdn.microsoft.com/en-us/vstudio/bb984878.aspx
    		2) Python 2.6+/3.x
    		   From: http://www.python.org/download/
    		3) PyWin32
    		   From: http://sourceforge.net/projects/pywin32/files/pywin32/
    		   Please make sure you download the version that matches your exact python version.
    		4) WIX 3.5
    		   From: http://wix.codeplex.com/releases/view/60102
    		5) JDK 6.0
               From: http://www.oracle.com/technetwork/java/javase/downloads/jdk-6u32-downloads-1594644.html
    		   You must also define an environment variable called "JAVA_HOME" that points to the JDK installation directory.
    		   For example: set JAVA_HOME=c:\Program Files (x86)\Java\jdk1.6.0_32
    
    	Optional requirements (To build the USB device driver):
    		1) Microsoft WDK
    		   From: http://www.microsoft.com/en-us/download/details.aspx?displaylang=en&id=11800
    		   
    		The package already includes a precompiled and digitally signed 32/64 bit driver.
    	
    	Optional Requirements (To build the documentation):
    		1) Doxygen
    		   From: http://www.stack.nl/~dimitri/doxygen/download.html#latestsrc
    		2) GraphViz
    		   From: http://www.graphviz.org/Download_windows.php
    	
    	Building OpenNI:
    	    1) Uninstall the previous version.
    		2) Go to the directory: "Platform\Win32\CreateRedist".
    		   x86 32-bit - Run the script: "RedistMaker.bat y 32 y".
    		   x64 64-bit - Run the script: "RedistMaker.bat y 64 y".
    		   This will compile and prepare the redist exe files that includes everything.
    		3) Install the exe you've just made which is located in Platform\Win32\CreateRedist\FinalXX\OPENNI-WinXX-1.X.X.X.exe 
    		   (XX being the number of bits: 32 or 64)
    		   The installer will also create the necessary environment variables (OPEN_NI_xxx), add the DLLs to the system path and register the internal modules with NiReg.
    		   
    		The visual studio solution is located in: Platform\Win32\Build\OpenNI.sln.
    		
    		When doing development it is recommended that you change the environment variables to point to your development directory instead of the default C:\Program Files\OpenNI.
    		(This can save you lots back and forth file copying...)
    
    		Important: Please note that even though the directory is called Win32, you can also use it to compile it for 64-bit targets (Win64/AMD64/x64).
    	
    	Building the USB driver (Optional):
    		Simply go into the directory "OpenNI\Platform\Win32\Driver\Build" and run the "BuildAll.bat" script.
    		For your development convenience, you can also use the solution: "Platform\Win32\Driver\Build\psdrv3.sln" but official driver builds should only be made with the batch file above, that uses the proper DDK environment.
    		Note: The driver build tool requires a system environment variable called "DDKPATH" that points to the WDK installation dir (for example: "c:\WinDDK\7100.0.0"). To add an environment variable please follow these steps: Control Panel -> System -> Advanced -> Environment Variables -> New (at the "System Variables" tab).
  • Miktex is the best TEX implementation on the Windows OS. It is required to build the OpenCV documentation.
  • Sphinx is a python documentation generator and is the tool that will actually create the OpenCV documentation. This on its own requires a couple of tools installed, We will cover this in depth at the How to Install Sphinx section.

Now we will describe the steps to follow for a full build (using all the above frameworks, tools and libraries). If you do not need the support for some of these you can just freely skip this section.

Building the library

  1. Make sure you have a working IDE with a valid compiler. In case of the Microsoft Visual Studio just install it and make sure it starts up.

  2. Install CMake. Simply follow the wizard, no need to add it to the path. The default install options are OK.

  3. Download and install an up-to-date version of msysgit from its official site. There is also the portable version, which you need only to unpack to get access to the console version of Git. Supposing that for some of us it could be quite enough.

  4. Install TortoiseGit. Choose the 32 or 64 bit version according to the type of OS you work in. While installing, locate your msysgit (if it doesn’t do that automatically). Follow the wizard – the default options are OK for the most part.

  5. Choose a directory in your file system, where you will download the OpenCV libraries to. I recommend creating a new one that has short path and no special charachters in it, for example D:/OpenCV. For this tutorial I’ll suggest you do so. If you use your own path and know, what you’re doing – it’s OK.

    1. Clone the repository to the selected directory. After clicking Clone button, a window will appear where you can select from what repository you want to download source files (https://github.com/Itseez/opencv.git) and to what directory (D:/OpenCV).
    2. Push the OK button and be patient as the repository is quite a heavy download. It will take some time depending on your Internet connection.
  6. In this section I will cover installing the 3rd party libraries.

    1. Download the Python libraries and install it with the default options. You will need a couple other python extensions. Luckily installing all these may be automated by a nice tool called Setuptools. Download and install again.

    2. Installing Sphinx is easy once you have installed Setuptools. This contains a little application that will automatically connect to the python databases and download the latest version of many python scripts. Start up a command window (enter cmd into the windows start menu and press enter) and use the CD command to navigate to your Python folders Script sub-folder. Here just pass to the easy_install.exe as argument the name of the program you want to install. Add the sphinxargument.

      The Windows Command StartupHow to start the command window

      Note

      The CD navigation command works only inside a drive. For example if you are somewhere in the C: drive you cannot use it this to go to another drive (like for example D:). To do so you first need to change drives letters. For this simply enter the command D:. Then you can use the CD to navigate to specific folder inside the drive. Bonus tip: you can clear the screen by using the CLS command.

      This will also install its prerequisites Jinja2 and Pygments.

    3. The easiest way to install Numpy is to just download its binaries from the sourceforga page. Make sure your download and install exactly the binary for your python version (so for version 2.7).

    4. Download the Miktex and install it. Again just follow the wizard. At the fourth step make sure you select for the “Install missing packages on-the-fly” the Yesoption, as you can see on the image below. Again this will take quite some time so be patient.

      The Miktex Install Screen

    5. For the Intel © Threading Building Blocks (TBB) download the source files and extract it inside a directory on your system. For example let there beD:/OpenCV/dep. For installing the Intel © Integrated Performance Primitives (IPP) the story is the same. For exctracting the archives I recommend using the 7-Zip application.

      The Miktex Install Screen

    6. In case of the Eigen library it is again a case of download and extract to the D:/OpenCV/dep directory.

    7. Same as above with OpenEXR.

    8. For the OpenNI Framework you need to install both the development build and the PrimeSensor Module.

    9. For the CUDA you need again two modules: the latest CUDA Toolkit and the CUDA Tools SDK. Download and install both of them with a complete option by using the 32 or 64 bit setups according to your OS.

    10. In case of the Qt framework you need to build yourself the binary files (unless you use the Microsoft Visual Studio 2008 with 32 bit compiler). To do this go to theQt Downloads page. Download the source files (not the installers!!!):

      Download this Qt Package

      Compiling Qt 5 with Visual Studio 2012 (32 or 64 bit)

      Steps to do:
      1. Decide whether to compile 32bit or 64bit. If you’ll go with 32bit choose the following 32bit tools (the same with 64bit).
      2. Install Python http://www.python.org/getit
      3. Install Perl http://strawberryperl.com
      4. Download Jom http://qt-project.org/wiki/jom
      5. Download and extract Qt sources http://qt-project.org/downloads Search for the zip file: 6. Copy Jom files to the Qt sources directory.7. Restart computer.
      8. Make sure Python and Perl are accessible from command line:

      • python –version
      • perl -v

      9. Open Visual Studio 2012 tools command prompt. It can be found here: Start ->  Microsoft Visual Studio 2012:
      For 32 bit use VS2012 x86 Native Tools Command Prompt
      For 64 bit use VS2012 x64 Cross Tools Command Prompt
      10. Navigate to the Qt source directory and type:
      configure -developer-build -opensource -opengl desktop -nomake examples -nomake tests
      11. Type:
      jom
      12. Wait until the compilation is finished. It will take about 30-60 minutes.
      13. Once compiled do some cleanup. Following command will remove temporary files:
      jom clean

      Step 1: The Setup

      1. Download and install RapidEE here. RapidEE is a windows environment variables editor. It is extremely useful for the rest of this process (and just in general).
      2. Install the DirectX 11 SDK. It is now part of the Windows 8 SDK, so you first have to install the DirectX 10 SDK, which you can get here (but see warning in next sentence). If you have the Visual C++ 2010 Redistributable Package installed, and you probably do (it is automatically installed along with VS 2010), follow the steps outlined here to assist with the DirectX 10 installation. Once you have the DirectX 10 SDK installed, download and install the Windows 8 SDK here, which contains the DirectX 11 SDK. Yes, this is a pain, but unless you know you have the DirectX 11 SDK, the Qt build will fail.
      3. Install Python for Windows (I’ve heard 2.6+, working with 3.3) from Python.org
      4. Install Perl for Windows from ActiveState

      Extract it into a nice and short named directory like D:/OpenCV/dep/qt/ . Then you need to build it. Start up a Visual Studio Command Prompt (2010) by using the start menu search (or navigate through the start menu All Programs ‣ Microsoft Visual Studio 2010 ‣ Visual Studio Tools ‣ Visual Studio Command Prompt (2010)).The Visual Studio command prompt

    11. Now navigate to the extracted folder and enter inside it by using this console window. You should have a folder containing files like InstallMake and so on. Use the dir command to list fil
      l[-inside your current directory. Once arrived at this directory enter the following command:

      configure.exe -release -no-webkit -no-phonon -no-phonon-backend -no-script -no-scripttools -no-qt3support -no-multimedia -no-ltcg
      

      configure -release -developer-build -opensource -opengl desktop -nomake examples -nomake tests

      Completing this will take around 10-20 minutes. Then enter the next command that will take a lot longer (can easily take even more than a full hour):
      nmake
      

      After this set the Qt enviroment variables using the following command on Windows 7:

      setx -m QTDIR D:/OpenCV/dep/qt/qt-everywhere-opensource-src-4.7.3
      

      Also, add the built binary files path to the system path by using the Path Editor. In our case this is D:/OpenCV/dep/qt/qt-everywhere-opensource-src-4.7.3/bin.

      Note

      If you plan on doing Qt application development you can also install at this point the Qt Visual Studio Add-in. After this you can make and build Qt applications without using the Qt Creator. Everything is nicely integrated into Visual Studio.

  7. Now start the CMake (cmake-gui). You may again enter it in the start menu search or get it from the All Programs ‣ CMake 2.8 ‣ CMake (cmake-gui). First, select the directory for the source files of the OpenCV library (1). Then, specify a directory where you will build the binary files for OpenCV (2).

    Select the directoriesPress the Configure button to specify the compiler (and IDE) you want to use. Note that in case you can choose between different compilers for making either 64 bit or 32 bit libraries. Select the one you use in your application development.

    How CMake should look at build time.CMake will start out and based on your system variables will try to automatically locate as many packages as possible. You can modify the packages to use for the build in the WITH ‣ WITH_X menu points (where X is the package abbreviation). Here are a list of current packages you can turn on or off:

    The packages OpenCV may useSelect all the packages you want to use and press again the Configure button. For an easier overview of the build options make sure the Grouped option under the binary directory selection is turned on. For some of the packages CMake may not find all of the required files or directories. In case of these CMake will throw an error in its output window (located at the bottom of the GUI) and set its field values, to not found constants. For example:

    Constant for not found packagesError (warning) thrown in output window of the CMake GUIFor these you need to manually set the queried directories or files path. After this press again the Configure button to see if the value entered by you was accepted or not. Do this until all entries are good and you cannot see errors in the field/value or the output part of the GUI. Now I want to emphasize an option that you will definitely love: ENABLE ‣ ENABLE_SOLUTION_FOLDERS. OpenCV will create many-many projects and turning this option will make sure that they are categorized inside directories in the Solution Explorer. It is a must have feature, if you ask me.

    Set the Solution Folders and the parts you want to buildFurthermore, you need to select what part of OpenCV you want to build.

    • BUILD_DOCS -> It creates two projects for building the documentation of OpenCV (there will be a separate project for building the HTML and the PDF files). Note that these aren’t built together with the solution. You need to make an explicit build project command on these to do so.
    • BUILD_EXAMPLES -> OpenCV comes with many example applications from which you may learn most of the libraries capabilities. This will also come handy to easily try out if OpenCV is fully functional on your computer.
    • BUILD_PACKAGE -> Prior to version 2.3 with this you could build a project that will build an OpenCV installer. With this you can easily install your OpenCV flavor on other systems. For the latest source files of OpenCV it generates a new project that simply creates zip archive with OpenCV sources.
    • BUILD_SHARED_LIBS -> With this you can control to build DLL files (when turned on) or static library files (*.lib) otherwise.
    • BUILD_TESTS -> Each module of OpenCV has a test project assigned to it. Building these test projects is also a good way to try out, that the modules work just as expected on your system too.
    • BUILD_PERF_TESTS -> There are also performance tests for many OpenCV functions. If you’re concerned about performance, build them and run.
    • BUILD_opencv_python -> Self-explanatory. Create the binaries to useOpenCV from the Python language.While building VTK6.1 with Qt5.2.1 (MSVC2012_64_opengl prebuilt binary) using MSVC2012_x64 on Windows 8.1, I got the following error message:
      CMake Error at C:/Qt/Qt5.2.1/5.2.1/msvc2012_64_opengl/lib/cmake/Qt5Gui/Qt5GuiConfigExtras.cmake:16 (message):
      Failed to find “glu32” in “” with CMAKE_CXX_LIBRARY_ARCHITECTURE “”.
      Call Stack (most recent call first):
      C:/Qt/Qt5.2.1/5.2.1/msvc2012_64_opengl/lib/cmake/Qt5Gui/Qt5GuiConfigExtras.cmake:52 (_qt5gui_find_extra_libs)
      C:/Qt/Qt5.2.1/5.2.1/msvc2012_64_opengl/lib/cmake/Qt5Gui/Qt5GuiConfig.cmake:152 (include)
      C:/Qt/Qt5.2.1/5.2.1/msvc2012_64_opengl/lib/cmake/Qt5Widgets/Qt5WidgetsConfig.cmake:94 (find_package)
      GUISupport/Qt/CMakeLists.txt:58 (find_package)
      I checked VTK_GROUP_QT, Module_vtkGUISupportQt, Module_vtkGUISupportQtOpenGL, and set QT version to 5. CMake found the following three DIR’s:
       
      Qt5Core_DIR = C:/Qt/Qt5.2.1/5.2.1/msvc2012_64_opengl/lib/cmake/Qt5Core
      Qt5Gui_DIR = C:/Qt/Qt5.2.1/5.2.1/msvc2012_64_opengl/lib/cmake/Qt5Gui
      Qt5Widgets_DIR = C:/Qt/Qt5.2.1/5.2.1/msvc2012_64_opengl/lib/cmake/Qt5Widgets
      My problems was solved. On CMake, I added this entry:
      CMAKE_PREFIX_PATH: C:\Program Files (x86)\Windows Kits\8.0\Lib\win8\um\x64
      for my Windows 8.1 x64 version.

      File:Cmake-add-cache-entry-arrow.png

    Press again the Configure button and ensure no errors are reported. If this is the case you can tell CMake to create the project files by pushing the Generate button. Go to the build directory and open the created OpenCV solution. Depending on just how much of the above options you have selected the solution may contain quite a lot of projects so be tolerant on the IDE at the startup. Now you need to build both the Release and the Debug binaries. Use the drop-down menu on your IDE to change to another of these after building for one of them.

    Look here for changing the Build TypeIn the end you can observe the built binary files inside the bin directory:

    The Result of the build.For the documentation you need to explicitly issue the build commands on the doc project for the PDF files and on the doc_html for the HTML ones. Each of these will call Sphinx to do all the hard work. You can find the generated documentation inside the Build/Doc/_html for the HTML pages and within the Build/Doc the PDF manuals.

    The Documentation ProjectsTo collect the header and the binary files, that you will use during your own projects, into a separate directory (simillary to how the pre-built binaries ship) you need to explicitely build the Install project.

    The Install ProjectThis will create an Install directory inside the Build one collecting all the built binaries into a single place. Use this only after you built both the Release and Debugversions.

    To test your build just go into the Build/bin/Debug or Build/bin/Release directory and start a couple of applications like the contours.exe. If they run, you are done. Otherwise, something definitely went awfully wrong. In this case you should contact us at our Q&A forum. If everything is okay the contours.exe output should resemble the following image (if built with Qt support):

    A good output result

    Note

    If you use the GPU module (CUDA libraries) make sure you also upgrade to the latest drivers of your GPU. Error messages containing invalid entries in (or cannot find) the nvcuda.dll are caused mostly by old video card drivers. For testing the GPU (if built) run the performance_gpu.exe sample application.

Set the OpenCV enviroment variable and add it to the systems path

First we set an enviroment variable to make easier our work. This will hold the build directory of our OpenCV library that we use in our projects. Start up a command window and enter:

setx -m OPENCV_DIR D:\OpenCV\Build\x86\vc10     (suggested for Visual Studio 2010 - 32 bit Windows)
setx -m OPENCV_DIR D:\OpenCV\Build\x64\vc10     (suggested for Visual Studio 2010 - 64 bit Windows)

setx -m OPENCV_DIR D:\OpenCV\Build\x86\vc11     (suggested for Visual Studio 2012 - 32 bit Windows)
setx -m OPENCV_DIR D:\OpenCV\Build\x64\vc11     (suggested for Visual Studio 2012 - 64 bit Windows)

Here the directory is where you have your OpenCV binaries (extracted or built). You can have different platform (e.g. x64 instead of x86) or compiler type, so substitute appropriate value. Inside this you should have two folders called lib and bin. The -m should be added if you wish to make the settings computer wise, instead of user wise.

If you built static libraries then you are done. Otherwise, you need to add the bin folders path to the systems path. This is cause you will use the OpenCV library in form of“Dynamic-link libraries” (also known as DLL). Inside these are stored all the algorithms and information the OpenCV library contains. The operating system will load them only on demand, during runtime. However, to do this he needs to know where they are. The systems PATH contains a list of folders where DLLs can be found. Add the OpenCV library path to this and the OS will know where to look if he ever needs the OpenCV binaries. Otherwise, you will need to copy the used DLLs right beside the applications executable file (exe) for the OS to find it, which is highly unpleasent if you work on many projects. To do this start up again the Path Editor and add the following new entry (right click in the application to bring up the menu):

%OPENCV_DIR%\bin

Right click to insert new path manually.Add the entry.Save it to the registry and you are done. If you ever change the location of your build directories or want to try out your applicaton with a different build all you will need to do is to update the OPENCV_DIR variable via the setx command inside a command window.

build applications with OpenCV inside the Microsoft Visual Studio

Everything I describe here will apply to the C\C++ interface of OpenCV. I start out from the assumption that you have read and completed with success the Installation in Windows tutorial. Therefore, before you go any further make sure you have an OpenCV directory that contains the OpenCV header files plus binaries and you have set the environment variables as described here.

You should have a folder looking like this.

The OpenCV libraries, distributed by us, on the Microsoft Windows operating system are in a Dynamic Linked Libraries (DLL). These have the advantage that all the content of the library are loaded only at runtime, on demand, and that countless programs may use the same library file. This means that if you have ten applications using the OpenCV library, no need to have around a version for each one of them. Of course you need to have the dll of the OpenCV on all systems where you want to run your application.

Another approach is to use static libraries that have lib extensions. You may build these by using our source files as described in the Installation in Windows tutorial. When you use this the library will be built-in inside your exe file. So there is no chance that the user deletes them, for some reason. As a drawback your application will be larger one and as, it will take more time to load it during its startup.

To build an application with OpenCV you need to do two things:

  • Tell to the compiler how the OpenCV library looks. You do this by showing it the header files.

  • Tell to the linker from where to get the functions or data structures of OpenCV, when they are needed.

    If you use the lib system you must set the path where the library files are and specify in which one of them to look. During the build the linker will look into these libraries and add the definitions and implementation of all used functions and data structures to the executable file.

    If you use the DLL system you must again specify all this, however now for a different reason. This is a Microsoft OS specific stuff. It seems that the linker needs to know that where in the DLL to search for the data structure or function at the runtime. This information is stored inside lib files. Nevertheless, they aren’t static libraries. They are so called import libraries. This is why when you make some DLLs in Windows you will also end up with some lib extension libraries. The good part is that at runtime only the DLL is required.

To pass on all this information to the Visual Studio IDE you can either do it globally (so all your future projects will get these information) or locally (so only for you current project). The advantage of the global one is that you only need to do it once; however, it may be undesirable to clump all your projects all the time with all these information. In case of the global one how you do it depends on the Microsoft Visual Studio you use. There is a 2008 and previous versions and a 2010 way of doing it. Inside the global section of this tutorial I’ll show what the main differences are.

The base item of a project in Visual Studio is a solution. A solution may contain multiple projects. Projects are the building blocks of an application. Every project will realize something and you will have a main project in which you can put together this project puzzle. In case of the many simple applications (like many of the tutorials will be) you do not need to break down the application into modules. In these cases your main project will be the only existing one. Now go create a new solution inside Visual studio by going through the File ‣ New ‣ Project menu selection. Choose Win32 Console Application as type. Enter its name and select the path where to create it. Then in the upcoming dialog make sure you create an empty project.

Which options to select

The local method

Every project is built separately from the others. Due to this every project has its own rule package. Inside this rule packages are stored all the information the IDE needs to know to build your project. For any application there are at least two build modes: a Release and a Debug one. The Debug has many features that exist so you can find and resolve easier bugs inside your application. In contrast the Release is an optimized version, where the goal is to make the application run as fast as possible or to be as small as possible. You may figure that these modes also require different rules to use during build. Therefore, there exist different rule packages for each of your build modes. These rule packages are called inside the IDE as project properties and you can view and modify them by using the Property Manger. You can bring up this withView ‣ Property Pages. Expand it and you can see the existing rule packages (called Proporty Sheets).

An example of Property SheetThe really useful stuff of these is that you may create a rule package once and you can later just add it to your new projects. Create it once and reuse it later. We want to create a new Property Sheet that will contain all the rules that the compiler and linker needs to know. Of course we will need a separate one for the Debug and the Release Builds. Start up with the Debug one as shown in the image below:

Add a new Property SheetUse for example the OpenCV_Debug name. Then by selecting the sheet Right Click ‣ Properties. In the following I will show to set the OpenCV rules locally, as I find unnecessary to pollute projects with custom rules that I do not use it. Go the C++ groups General entry and under the “Additional Include Directories” add the path to your OpenCV include. If you don’t have “C/C++” group, you should add any .c/.cpp file to the project.

$(OPENCV_DIR)\..\..\include

Add the include dir like this.When adding third party libraries settings it is generally a good idea to use the power behind the environment variables. The full location of the OpenCV library may change on each system. Moreover, you may even end up yourself with moving the install directory for some reason. If you would give explicit paths inside your property sheet your project will end up not working when you pass it further to someone else who has a different OpenCV install path. Moreover, fixing this would require to manually modifying every explicit path. A more elegant solution is to use the environment variables. Anything that you put inside a parenthesis started with a dollar sign will be replaced at runtime with the current environment variables value. Here comes in play the environment variable setting we already made in our previous tutorial.

Next go to the Linker ‣ General and under the “Additional Library Directories” add the libs directory:

$(OPENCV_DIR)\lib

Add the library folder like this.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_calib3d249d.lib
opencv_contrib249d.lib
opencv_core249d.lib
opencv_features2d249d.lib
opencv_flann249d.lib
opencv_gpu249d.lib
opencv_highgui249d.lib
opencv_imgproc249d.lib
opencv_legacy249d.lib
opencv_ml249d.lib
opencv_nonfree249d.lib
opencv_objdetect249d.lib
opencv_ocl249d.lib
opencv_photo249d.lib
opencv_stitching249d.lib
opencv_superres249d.lib
opencv_ts249d.lib
opencv_video249d.lib
opencv_videostab249d.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.

opencv_calib3d249.lib
opencv_contrib249.lib
opencv_core249.lib
opencv_features2d249.lib
opencv_flann249.lib
opencv_gpu249.lib
opencv_highgui249.lib
opencv_imgproc249.lib
opencv_legacy249.lib
opencv_ml249.lib
opencv_nonfree249.lib
opencv_objdetect249.lib
opencv_ocl249.lib
opencv_photo249.lib
opencv_stitching249.lib
opencv_superres249.lib
opencv_ts249.lib
opencv_video249.lib
opencv_videostab249.lib

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.

Use this option.

The global method

In case you find to troublesome to add the property pages to each and every one of your projects you can also add this rules to a “global property page”. However, this applies only to the additional include and library directories. The name of the libraries to use you still need to specify manually by using for instance: a Property page.

In Visual Studio 2008 you can find this under the: Tools ‣ Options ‣ Projects and Solutions ‣ VC++ Directories.

VC++ Directories in VS 2008.In Visual Studio 2010 this has been moved to a global property sheet which is automatically added to every project you create:

VC++ Directories in VS 2010.The process is the same as described in case of the local approach. Just add the include directories by using the environment variable OPENCV_DIR.

Test it!

Now to try this out download our little test source code or get it from the sample code folder of the OpenCV sources. Add this to your project and build it. Here’s its content:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main( int argc, char** argv )
{
    if( argc != 2)
    {
     cout <<" Usage: display_image ImageToLoadAndDisplay" << endl;
     return -1;
    }

    Mat image;
    image = imread(argv[1], IMREAD_COLOR); // Read the file

    if(! image.data ) // Check for invalid input
    {
        cout << "Could not open or find the image" << std::endl ;
        return -1;
    }

    namedWindow( "Display window", WINDOW_AUTOSIZE ); // Create a window for display.
    imshow( "Display window", image ); // Show our image inside it.

    waitKey(0); // Wait for a keystroke in the window
    return 0;
}

You can start a Visual Studio build from two places. Either inside from the IDE (keyboard combination: Control-F5) or by navigating to your build directory and start the application with a double click. The catch is that these two aren’t the same. When you start it from the IDE its current working directory is the projects directory, while otherwise it is the folder where the application file currently is (so usually your build directory). Moreover, in case of starting from the IDE the console window will not close once finished. It will wait for a keystroke of yours.

This is important to remember when you code inside the code open and save commands. You’re resources will be saved ( and queried for at opening!!!) relatively to your working directory. This is unless you give a full, explicit path as parameter for the I/O functions. In the code above we open this OpenCV logo. Before starting up the application make sure you place the image file in your current working directory. Modify the image file name inside the code to try it out on other images too. Run it and voilá:

You should have this.

Command line arguments with Visual Studio

Throughout some of our future tutorials you’ll see that the programs main input method will be by giving a runtime argument. To do this you can just start up a commmand windows (cmd + Enter in the start menu), navigate to your executable file and start it with an argument. So for example in case of my upper project this would look like:

1
2
3
D:
CD OpenCV\MySolutionName\Release
MySolutionName.exe exampleImage.jpg

Here I first changed my drive (if your project isn’t on the OS local drive), navigated to my project and start it with an example image argument. While under Linux system it is common to fiddle around with the console window on the Microsoft Windows many people come to use it almost never. Besides, adding the same argument again and again while you are testing your application is, somewhat, a cumbersome task. Luckily, in the Visual Studio there is a menu to automate all this:

Visual Studio Command Line ArgumentsSpecify here the name of the inputs and while you start your application from the Visual Studio enviroment you have automatic argument passing.

Leave a comment

 
Extracts from a Personal Diary

dedicated to the life of a silent girl who eventually learnt to open up

Num3ri v 2.0

I miei numeri - seconda versione

ThuyDX

Just another WordPress.com site

Abraham Zamudio [Matematico]

Matematica Aplicada, Linux ,Programacion Cientifica , HIgh Performance COmputing, APrendizaje Automatico

josephdung

thoughts...

Tech_Raj

A great WordPress.com site

Travel tips

Travel tips

Experience the real life.....!!!

Shurwaat achi honi chahiye ...

Ronzii's Blog

Just your average geek's blog

Chetan Solanki

Helpful to u, if u need it.....

ScreenCrush

Explorer of Research #HEMBAD

managedCUDA

Explorer of Research #HEMBAD

siddheshsathe

A great WordPress.com site

Ari's

This is My Space so Dont Mess With IT !!

Business India 2.0

All about Business Travel 2.0 ideas,technology,ventures and the capital making its happen