Doxygen tutorials: basic structure

This commit is contained in:
Maksim Shabunin
2014-11-27 15:39:05 +03:00
parent 220f671655
commit 8375182e34
99 changed files with 17805 additions and 0 deletions

View File

@@ -0,0 +1,254 @@
OpenCV4Android SDK {#tutorial_O4A_SDK}
==================
This tutorial was designed to help you with installation and configuration of OpenCV4Android SDK.
This guide was written with MS Windows 7 in mind, though it should work with GNU Linux and Apple Mac
OS as well.
This tutorial assumes you have the following software installed and configured:
- JDK
- Android SDK and NDK
- Eclipse IDE
- ADT and CDT plugins for Eclipse
If you need help with anything of the above, you may refer to our @ref android_dev_intro guide.
If you encounter any error after thoroughly following these steps, feel free to contact us via
[OpenCV4Android](https://groups.google.com/group/android-opencv/) discussion group or OpenCV [Q&A
forum](http://answers.opencv.org). We'll do our best to help you out.
Tegra Android Development Pack users
------------------------------------
You may have used [Tegra Android Development
Pack](http://developer.nvidia.com/tegra-android-development-pack) (**TADP**) released by **NVIDIA**
for Android development environment setup.
Beside Android development tools the TADP 2.0 includes OpenCV4Android SDK, so it can be already
installed in your system and you can skip to @ref Running_OpenCV_Samples section of this tutorial.
More details regarding TADP can be found in the @ref android_dev_intro guide.
General info
------------
OpenCV4Android SDK package enables development of Android applications with use of OpenCV library.
The structure of package contents looks as follows:
OpenCV-2.4.9-android-sdk
|_ apk
| |_ OpenCV_2.4.9_binary_pack_armv7a.apk
| |_ OpenCV_2.4.9_Manager_2.18_XXX.apk
|
|_ doc
|_ samples
|_ sdk
| |_ etc
| |_ java
| |_ native
| |_ 3rdparty
| |_ jni
| |_ libs
| |_ armeabi
| |_ armeabi-v7a
| |_ x86
|
|_ LICENSE
|_ README.android
- `sdk` folder contains OpenCV API and libraries for Android:
- `sdk/java` folder contains an Android library Eclipse project providing OpenCV Java API that can
be imported into developer's workspace;
- `sdk/native` folder contains OpenCV C++ headers (for JNI code) and native Android libraries
(\*.so and \*.a) for ARM-v5, ARM-v7a and x86 architectures;
- `sdk/etc` folder contains Haar and LBP cascades distributed with OpenCV.
- `apk` folder contains Android packages that should be installed on the target Android device to
enable OpenCV library access via OpenCV Manager API (see details below).
On production devices that have access to Google Play Market (and Internet) these packages will
be installed from Market on the first start of an application using OpenCV Manager API. But
devkits without Market or Internet connection require this packages to be installed manually.
Install the Manager.apk and optional binary_pack.apk if it needed. See @ref manager_selection
for details.
@note Installation from Internet is the preferable way since OpenCV team may publish updated
versions of this packages on the Market. \* `samples` folder contains sample applications projects
and their prebuilt packages (APK). Import them into Eclipse workspace (like described below) and
browse the code to learn possible ways of OpenCV use on Android.
- `doc` folder contains various OpenCV documentation in PDF format. It's also available online at
<http://docs.opencv.org>.
@note The most recent docs (nightly build) are at <http://docs.opencv.org/2.4>. Generally, it's more
up-to-date, but can refer to not-yet-released functionality. .. TODO: I'm not sure that this is the
best place to talk about OpenCV Manager
Starting from version 2.4.3 OpenCV4Android SDK uses OpenCV Manager API for library initialization.
OpenCV Manager is an Android service based solution providing the following benefits for OpenCV
applications developers:
- Compact apk-size, since all applications use the same binaries from Manager and do not store
native libs within themselves;
- Hardware specific optimizations are automatically enabled on all supported platforms;
- Automatic updates and bug fixes;
- Trusted OpenCV library source. All packages with OpenCV are published on Google Play;
For additional information on OpenCV Manager see the:
- Slides_
- Reference Manual_
Manual OpenCV4Android SDK setup
-------------------------------
### Get the OpenCV4Android SDK
1. Go to the [OpenCV download page on
SourceForge](http://sourceforge.net/projects/opencvlibrary/files/opencv-android/) and download
the latest available version. Currently it's `OpenCV-2.4.9-android-sdk.zip`_.
2. Create a new folder for Android with OpenCV development. For this tutorial we have unpacked
OpenCV SDK to the `C:\\Work\\OpenCV4Android\\` directory.
@note Better to use a path without spaces in it. Otherwise you may have problems with ndk-build. \#.
Unpack the SDK archive into the chosen directory.
You can unpack it using any popular archiver (e.g with 7-Zip_):
![image](images/android_package_7zip.png)
On Unix you can use the following command:
@code{.bash}
unzip ~/Downloads/OpenCV-2.4.9-android-sdk.zip
@endcode
### Import OpenCV library and samples to the Eclipse
1. Start Eclipse and choose your workspace location.
We recommend to start working with OpenCV for Android from a new clean workspace. A new Eclipse
workspace can for example be created in the folder where you have unpacked OpenCV4Android SDK
package:
![image](images/eclipse_1_choose_workspace.png)
2. Import OpenCV library and samples into workspace.
OpenCV library is packed as a ready-for-use [Android Library
Project](http://developer.android.com/guide/developing/projects/index.html#LibraryProjects). You
can simply reference it in your projects.
Each sample included into the `OpenCV-2.4.9-android-sdk.zip` is a regular Android project that
already references OpenCV library. Follow the steps below to import OpenCV and samples into the
workspace:
@note OpenCV samples are indeed **dependent** on OpenCV library project so don't forget to import it to your workspace as well.
- Right click on the Package Explorer window and choose Import... option from the context
menu:
![image](images/eclipse_5_import_command.png)
- In the main panel select General --\> Existing Projects into Workspace and press Next
button:
![image](images/eclipse_6_import_existing_projects.png)
- In the Select root directory field locate your OpenCV package folder. Eclipse should
automatically locate OpenCV library and samples:
![image](images/eclipse_7_select_projects.png)
- Click Finish button to complete the import operation.
After clicking Finish button Eclipse will load all selected projects into workspace, and you
have to wait some time while it is building OpenCV samples. Just give a minute to Eclipse to
complete initialization.
![image](images/eclipse_cdt_cfg4.png)
Once Eclipse completes build you will have the clean workspace without any build errors:
![image](images/eclipse_10_crystal_clean.png)
### Running OpenCV Samples
At this point you should be able to build and run the samples. Keep in mind, that face-detection and
Tutorial 2 - Mixed Processing include some native code and require Android NDK and NDK/CDT plugin
for Eclipse to build working applications. If you haven't installed these tools, see the
corresponding section of @ref Android_Dev_Intro.
**warning**
Please consider that some samples use Android Java Camera API, which is accessible
with an AVD. But most of samples use OpenCV Native Camera which **may not work** with an
emulator.
@note Recent *Android SDK tools, revision 19+* can run ARM v7a OS images but they available not for
all Android versions. Well, running samples from Eclipse is very simple:
- Connect your device with adb tool from Android SDK or create an emulator with camera support.
- See [Managing Virtual
Devices](http://developer.android.com/guide/developing/devices/index.html) document for help
with Android Emulator.
- See [Using Hardware Devices](http://developer.android.com/guide/developing/device.html) for
help with real devices (not emulators).
- Select project you want to start in Package Explorer and just press Ctrl + F11 or select option
Run --\> Run from the main menu, or click Run button on the toolbar.
@note Android Emulator can take several minutes to start. So, please, be patient. \* On the first
run Eclipse will ask you about the running mode for your application:
![image](images/eclipse_11_run_as.png)
- Select the Android Application option and click OK button. Eclipse will install and run the
sample.
Chances are that on the first launch you will not have the [OpenCV
Manager](https://docs.google.com/a/itseez.com/presentation/d/1EO_1kijgBg_BsjNp2ymk-aarg-0K279_1VZRcPplSuk/present#slide=id.p)
package installed. In this case you will see the following message:
![image](images/android_emulator_opencv_manager_fail.png)
To get rid of the message you will need to install OpenCV Manager and the appropriate
OpenCV binary pack. Simply tap Yes if you have *Google Play Market* installed on your
device/emulator. It will redirect you to the corresponding page on *Google Play Market*.
If you have no access to the *Market*, which is often the case with emulators - you will need to
install the packages from OpenCV4Android SDK folder manually. See @ref manager_selection for
details.
@code{.sh}
<Android SDK path>/platform-tools/adb install <OpenCV4Android SDK path>/apk/OpenCV_2.4.9_Manager_2.18_armv7a-neon.apk
@endcode
@note armeabi, armv7a-neon, arm7a-neon-android8, mips and x86 stand for platform targets:
- armeabi is for ARM v5 and ARM v6 architectures with Android API 8+,
- armv7a-neon is for NEON-optimized ARM v7 with Android API 9+,
- arm7a-neon-android8 is for NEON-optimized ARM v7 with Android API 8,
- mips is for MIPS architecture with Android API 9+,
- x86 is for Intel x86 CPUs with Android API 9+.
If using hardware device for testing/debugging, run the following command to learn its CPU
architecture:
@code{.sh}
adb shell getprop ro.product.cpu.abi
@endcode
If you're using an AVD emulator, go Window \> AVD Manager to see the list of availible devices.
Click Edit in the context menu of the selected device. In the window, which then pop-ups, find
the CPU field.
You may also see section @ref manager_selection for details.
When done, you will be able to run OpenCV samples on your device/emulator seamlessly.
- Here is Sample - image-manipulations sample, running on top of stock camera-preview of the
emulator.
![image](images/emulator_canny.png)
What's next
-----------
Now, when you have your instance of OpenCV4Adroid SDK set up and configured, you may want to proceed
to using OpenCV in your own application. You can learn how to do that in a separate @ref
dev_with_OCV_on_Android tutorial.

View File

@@ -0,0 +1,518 @@
Introduction into Android Development {#tutorial_android_dev_intro}
=====================================
This guide was designed to help you in learning Android development basics and setting up your
working environment quickly. It was written with Windows 7 in mind, though it would work with Linux
(Ubuntu), Mac OS X and any other OS supported by Android SDK.
If you encounter any error after thoroughly following these steps, feel free to contact us via
[OpenCV4Android](https://groups.google.com/group/android-opencv/) discussion group or OpenCV [Q&A
forum](http://answers.opencv.org). We'll do our best to help you out.
Preface
-------
Android is a Linux-based, open source mobile operating system developed by Open Handset Alliance led
by Google. See the [Android home site](http://www.android.com/about/) for general details.
Development for Android significantly differs from development for other platforms. So before
starting programming for Android we recommend you make sure that you are familiar with the following
key topis:
1. [Java](http://en.wikipedia.org/wiki/Java_(programming_language)) programming language that is
the primary development technology for Android OS. Also, you can find [Oracle docs on
Java](http://docs.oracle.com/javase/) useful.
2. [Java Native Interface (JNI)](http://en.wikipedia.org/wiki/Java_Native_Interface) that is a
technology of running native code in Java virtual machine. Also, you can find [Oracle docs on
JNI](http://docs.oracle.com/javase/7/docs/technotes/guides/jni/) useful.
3. [Android
Activity](http://developer.android.com/training/basics/activity-lifecycle/starting.html) and its
lifecycle, that is an essential Android API class.
4. OpenCV development will certainly require some knowlege of the [Android
Camera](http://developer.android.com/guide/topics/media/camera.html) specifics.
Quick environment setup for Android development
-----------------------------------------------
If you are making a clean environment install, then you can try [Tegra Android Development
Pack](https://developer.nvidia.com/tegra-android-development-pack) (**TADP**) released by
**NVIDIA**.
@note Starting the *version 2.0* the TADP package includes *OpenCV for Tegra* SDK that is a regular
*OpenCV4Android SDK* extended with Tegra-specific stuff. When unpacked, TADP will cover all of the
environment setup automatically and you can skip the rest of the guide.
If you are a beginner in Android development then we also recommend you to start with TADP.
@note *NVIDIA*'s Tegra Android Development Pack includes some special features for *NVIDIA*s Tegra
platform_ but its use is not limited to *Tegra* devices only. \* You need at least *1.6 Gb* free
disk space for the install.
- TADP will download Android SDK platforms and Android NDK from Google's server, so Internet
connection is required for the installation.
- TADP may ask you to flash your development kit at the end of installation process. Just skip
this step if you have no Tegra Development Kit_.
- (UNIX) TADP will ask you for *root* in the middle of installation, so you need to be a member of
*sudo* group.
Manual environment setup for Android development
------------------------------------------------
### Development in Java
You need the following software to be installed in order to develop for Android in Java:
1. **Sun JDK 6** (Sun JDK 7 is also possible)
Visit [Java SE Downloads page](http://www.oracle.com/technetwork/java/javase/downloads/) and
download an installer for your OS.
Here is a detailed JDK (Java Development Kit) [installation
guide](http://source.android.com/source/initializing.html#installing-the-jdk) for Ubuntu and Mac
OS (only JDK sections are applicable for OpenCV)
@note OpenJDK is not suitable for Android development, since Android SDK supports only Sun JDK. If you use Ubuntu, after installation of Sun JDK you should run the following command to set Sun java environment:
@code{.bash}
sudo update-java-alternatives --set java-6-sun
@endcode
1. **Android SDK**
Get the latest Android SDK from <http://developer.android.com/sdk/index.html>
Here is Google's [install guide](http://developer.android.com/sdk/installing.html) for the SDK.
@note You can choose downloading **ADT Bundle package** that in addition to Android SDK Tools
includes Eclipse + ADT + NDK/CDT plugins, Android Platform-tools, the latest Android platform and
the latest Android system image for the emulator - this is the best choice for those who is setting
up Android development environment the first time!
@note If you are running x64 version of Ubuntu Linux, then you need ia32 shared libraries for use on amd64 and ia64 systems to be installed. You can install them with the following command:
@code{.bash}
sudo apt-get install ia32-libs
@endcode
For Red Hat based systems the following command might be helpful:
@code{.bash}
sudo yum install libXtst.i386
@endcode
1. **Android SDK components**
You need the following SDK components to be installed:
- *Android SDK Tools, revision 20* or newer.
Older revisions should also work, but they are not recommended.
- *SDK Platform Android 3.0* (API 11).
The minimal platform supported by OpenCV Java API is **Android 2.2** (API 8). This is also
the minimum API Level required for the provided samples to run. See the
\<uses-sdk android:minSdkVersion="8"/\> tag in their **AndroidManifest.xml** files. But for
successful compilation the **target** platform should be set to Android 3.0 (API 11) or
higher. It will not prevent them from running on Android 2.2.
![image](images/android_sdk_and_avd_manager.png)
See [Adding Platforms and
Packages](http://developer.android.com/sdk/installing/adding-packages.html) for help with
installing/updating SDK components.
2. **Eclipse IDE**
Check the [Android SDK System Requirements](http://developer.android.com/sdk/requirements.html)
document for a list of Eclipse versions that are compatible with the Android SDK. For OpenCV
2.4.x we recommend **Eclipse 3.7 (Indigo)** or **Eclipse 4.2 (Juno)**. They work well for OpenCV
under both Windows and Linux.
If you have no Eclipse installed, you can get it from the [official
site](http://www.eclipse.org/downloads/).
3. **ADT plugin for Eclipse**
These instructions are copied from [Android Developers
site](http://developer.android.com/sdk/installing/installing-adt.html), check it out in case of
any ADT-related problem.
Assuming that you have Eclipse IDE installed, as described above, follow these steps to download
and install the ADT plugin:
1. Start Eclipse, then select Help --\> Install New Software...
2. Click Add (in the top-right corner).
3. In the Add Repository dialog that appears, enter "ADT Plugin" for the Name and the following
URL for the Location:
<https://dl-ssl.google.com/android/eclipse/>
4. Click OK
@note If you have trouble acquiring the plugin, try using "http" in the Location URL, instead of "https" (https is preferred for security reasons).
1. In the Available Software dialog, select the checkbox next to Developer Tools and click
Next.
2. In the next window, you'll see a list of the tools to be downloaded. Click Next.
@note If you also plan to develop native C++ code with Android NDK don't forget to enable NDK Plugins installations as well.
![image](images/eclipse_inst_adt.png)
1. Read and accept the license agreements, then click Finish.
@note If you get a security warning saying that the authenticity or validity of the software can't be established, click OK.
1. When the installation completes, restart Eclipse.
### Native development in C++
You need the following software to be installed in order to develop for Android in C++:
1. **Android NDK**
To compile C++ code for Android platform you need Android Native Development Kit (*NDK*).
You can get the latest version of NDK from the [download
page](http://developer.android.com/tools/sdk/ndk/index.html). To install Android NDK just
extract the archive to some folder on your computer. Here are [installation
instructions](http://developer.android.com/tools/sdk/ndk/index.html#Installing).
@note Before start you can read official Android NDK documentation which is in the Android NDK
archive, in the folder `docs/`. The main article about using Android NDK build system is in the
`ANDROID-MK.html` file. Some additional information you can find in the `APPLICATION-MK.html`,
`NDK-BUILD.html` files, and `CPU-ARM-NEON.html`, `CPLUSPLUS-SUPPORT.html`, `PREBUILTS.html`. \#.
**CDT plugin for Eclipse**
If you selected for installation the NDK plugins component of Eclipse ADT plugin (see the picture
above) your Eclipse IDE should already have CDT plugin (that means C/C++ Development Tooling).
There are several possible ways to integrate compilation of C++ code by Android NDK into Eclipse
compilation process. We recommend the approach based on Eclipse CDT(C/C++ Development Tooling)
Builder.
Android application structure
-----------------------------
Usually source code of an Android application has the following structure:
- `root folder of the project/`
- `jni/`
- `libs/`
- `res/`
- `src/`
- `AndroidManifest.xml`
- `project.properties`
- `... other files ...`
Where:
- the `src` folder contains Java code of the application,
- the `res` folder contains resources of the application (images, xml files describing UI layout,
etc),
- the `libs` folder will contain native libraries after a successful build,
- and the `jni` folder contains C/C++ application source code and NDK's build scripts `Android.mk`
and `Application.mk` producing the native libraries,
- `AndroidManifest.xml` file presents essential information about application to the Android
system (name of the Application, name of main application's package, components of the
application, required permissions, etc).
It can be created using Eclipse wizard or android tool from Android SDK.
- `project.properties` is a text file containing information about target Android platform and
other build details. This file is generated by Eclipse or can be created with android tool
included in Android SDK.
@note Both `AndroidManifest.xml` and `project.properties` files are required to compile the C++ part
of the application, since Android NDK build system relies on them. If any of these files does not
exist, compile the Java part of the project before the C++ part.
`Android.mk` and `Application.mk` scripts
-----------------------------------------
The script `Android.mk` usually has the following structure:
@code{.make}
LOCAL_PATH := \f$(call my-dir)
include \f$(CLEAR_VARS)
LOCAL_MODULE := <module_name>
LOCAL_SRC_FILES := <list of .c and .cpp project files>
<some variable name> := <some variable value>
...
<some variable name> := <some variable value>
include \f$(BUILD_SHARED_LIBRARY)
@endcode
This is the minimal file `Android.mk`, which builds C++ source code of an Android application. Note
that the first two lines and the last line are mandatory for any `Android.mk`.
Usually the file `Application.mk` is optional, but in case of project using OpenCV, when STL and
exceptions are used in C++, it also should be created. Example of the file `Application.mk`:
@code{.make}
APP_STL := gnustl_static
APP_CPPFLAGS := -frtti -fexceptions
APP_ABI := all
@endcode
@note We recommend setting APP_ABI := all for all targets. If you want to specify the target
explicitly, use armeabi for ARMv5/ARMv6, armeabi-v7a for ARMv7, x86 for Intel Atom or mips for MIPS.
Building application native part from command line
--------------------------------------------------
Here is the standard way to compile C++ part of an Android application:
**warning**
We strongly reccomend using cmd.exe (standard Windows console) instead of Cygwin on
**Windows**. Use the latter if only you're absolutely sure about, what you're doing. Cygwin is
not really supported and we are unlikely to help you in case you encounter some problems with
it. So, use it only if you're capable of handling the consequences yourself.
1. Open console and go to the root folder of an Android application
@code{.bash}
cd <root folder of the project>/
@endcode
2. Run the following command
@code{.bash}
<path_where_NDK_is_placed>/ndk-build
@endcode
@note On Windows we recommend to use ndk-build.cmd in standard Windows console (cmd.exe) rather than the similar bash script in Cygwin shell.
![image](images/ndk_build.png)
1. After executing this command the C++ part of the source code is compiled.
After that the Java part of the application can be (re)compiled (using either *Eclipse* or *Ant*
build tool).
@note Some parameters can be set for the ndk-build:
**Example 1**: Verbose compilation
@code{.bash}
<path_where_NDK_is_placed>/ndk-build V=1
@endcode
**Example 2**: Rebuild all
@code{.bash}
<path_where_NDK_is_placed>/ndk-build -B
@endcode
Building application native part from *Eclipse* (CDT Builder)
-------------------------------------------------------------
There are several possible ways to integrate compilation of native C++ code by Android NDK into
Eclipse build process. We recommend the approach based on Eclipse CDT(C/C++ Development Tooling)
Builder.
**important**
OpenCV for Android package since version 2.4.2 contains sample projects
pre-configured CDT Builders. For your own projects follow the steps below.
1. Define the NDKROOT environment variable containing the path to Android NDK in your system (e.g.
"X:\\\\Apps\\\\android-ndk-r8" or "/opt/android-ndk-r8").
**On Windows** an environment variable can be set via
My Computer -\> Properties -\> Advanced -\> Environment variables. On Windows 7 it's also
possible to use [setx](http://ss64.com/nt/setx.html) command in a console session.
**On Linux** and **MacOS** an environment variable can be set via appending a
"export VAR_NAME=VAR_VALUE" line to the `"~/.bashrc"` file and logging off and then on.
@note It's also possible to define the NDKROOT environment variable within Eclipse IDE, but it
should be done for every new workspace you create. If you prefer this option better than setting
system environment variable, open Eclipse menu
Window -\> Preferences -\> C/C++ -\> Build -\> Environment, press the Add... button and set variable
name to NDKROOT and value to local Android NDK path. \#. After that you need to **restart Eclipse**
to apply the changes.
1. Open Eclipse and load the Android app project to configure.
2. Add C/C++ Nature to the project via Eclipse menu
New -\> Other -\> C/C++ -\> Convert to a C/C++ Project.
![image](images/eclipse_cdt_cfg1.png)
And:
![image](images/eclipse_cdt_cfg2.png)
3. Select the project(s) to convert. Specify "Project type" = Makefile project, "Toolchains" =
Other Toolchain.
![image](images/eclipse_cdt_cfg3.png)
4. Open Project Properties -\> C/C++ Build, uncheck Use default build command, replace "Build
command" text from "make" to
"\\f${NDKROOT}/ndk-build.cmd" on Windows,
"\\f${NDKROOT}/ndk-build" on Linux and MacOS.
![image](images/eclipse_cdt_cfg4.png)
5. Go to Behaviour tab and change "Workbench build type" section like shown below:
![image](images/eclipse_cdt_cfg5.png)
6. Press OK and make sure the ndk-build is successfully invoked when building the project.
![image](images/eclipse_cdt_cfg6.png)
7. If you open your C++ source file in Eclipse editor, you'll see syntax error notifications. They
are not real errors, but additional CDT configuring is required.
![image](images/eclipse_cdt_cfg7.png)
8. Open Project Properties -\> C/C++ General -\> Paths and Symbols and add the following
**Include** paths for **C++**:
# for NDK r8 and prior:
\f${NDKROOT}/platforms/android-9/arch-arm/usr/include
\f${NDKROOT}/sources/cxx-stl/gnu-libstdc++/include
\f${NDKROOT}/sources/cxx-stl/gnu-libstdc++/libs/armeabi-v7a/include
\f${ProjDirPath}/../../sdk/native/jni/include
# for NDK r8b and later:
\f${NDKROOT}/platforms/android-9/arch-arm/usr/include
\f${NDKROOT}/sources/cxx-stl/gnu-libstdc++/4.6/include
\f${NDKROOT}/sources/cxx-stl/gnu-libstdc++/4.6/libs/armeabi-v7a/include
\f${ProjDirPath}/../../sdk/native/jni/include
The last path should be changed to the correct absolute or relative path to OpenCV4Android SDK
location.
This should clear the syntax error notifications in Eclipse C++ editor.
![image](images/eclipse_cdt_cfg8.png)
Debugging and Testing
---------------------
In this section we will give you some easy-to-follow instructions on how to set up an emulator or
hardware device for testing and debugging an Android project.
### AVD
AVD (*Android Virtual Device*) is not probably the most convenient way to test an OpenCV-dependent
application, but sure the most uncomplicated one to configure.
1. Assuming you already have *Android SDK* and *Eclipse IDE* installed, in Eclipse go
Window -\> AVD Manager.
2. Press the New button in AVD Manager window.
3. Create new Android Virtual Device window will let you select some properties for your new
device, like target API level, size of SD-card and other.
![image](images/AVD_create.png)
4. When you click the Create AVD button, your new AVD will be availible in AVD Manager.
5. Press Start to launch the device. Be aware that any AVD (a.k.a. Emulator) is usually much slower
than a hardware Android device, so it may take up to several minutes to start.
6. Go Run -\> Run/Debug in Eclipse IDE to run your application in regular or debugging mode.
Device Chooser will let you choose among the running devices or to start a new one.
### Hardware Device
If you have an Android device, you can use it to test and debug your applications. This way is more
authentic, though a little bit harder to set up. You need to make some actions for Windows and Linux
operating systems to be able to work with Android devices. No extra actions are required for Mac OS.
See detailed information on configuring hardware devices in subsections below.
You may also consult the official [Android Developers site
instructions](http://developer.android.com/tools/device.html) for more information.
#### Windows host computer
1. Enable USB debugging on the Android device (via Settings menu).
2. Attach the Android device to your PC with a USB cable.
3. Go to Start Menu and **right-click** on Computer. Select Manage in the context menu. You may be
asked for Administrative permissions.
4. Select Device Manager in the left pane and find an unknown device in the list. You may try
unplugging it and then plugging back in order to check whether it's your exact equipment appears
in the list.
![image](images/usb_device_connect_01.png)
5. Try your luck installing Google USB drivers without any modifications: **right-click** on the
unknown device, select Properties menu item --\> Details tab --\> Update Driver button.
![image](images/usb_device_connect_05.png)
6. Select Browse computer for driver software.
![image](images/usb_device_connect_06.png)
7. Specify the path to `<Android SDK folder>/extras/google/usb_driver/` folder.
![image](images/usb_device_connect_07.png)
8. If you get the prompt to install unverified drivers and report about success - you've finished
with USB driver installation.
![image](images/usb_device_connect_08.png)
\` \`
![image](images/usb_device_connect_09.png)
9. Otherwise (getting the failure like shown below) follow the next steps.
![image](images/usb_device_connect_12.png)
10. Again **right-click** on the unknown device, select Properties --\> Details --\> Hardware Ids
and copy the line like USB\\VID_XXXX&PID_XXXX&MI_XX.
![image](images/usb_device_connect_02.png)
11. Now open file `<Android SDK folder>/extras/google/usb_driver/android_winusb.inf`. Select either
Google.NTx86 or Google.NTamd64 section depending on your host system architecture.
![image](images/usb_device_connect_03.png)
12. There should be a record like existing ones for your device and you need to add one manually.
![image](images/usb_device_connect_04.png)
13. Save the `android_winusb.inf` file and try to install the USB driver again.
![image](images/usb_device_connect_05.png)
\` \`
![image](images/usb_device_connect_06.png)
\` \`
![image](images/usb_device_connect_07.png)
14. This time installation should go successfully.
![image](images/usb_device_connect_08.png)
\` \`
![image](images/usb_device_connect_09.png)
15. And an unknown device is now recognized as an Android phone.
![image](images/usb_device_connect_10.png)
16. Successful device USB connection can be verified in console via adb devices command.
![image](images/usb_device_connect_11.png)
17. Now, in Eclipse go Run -\> Run/Debug to run your application in regular or debugging mode.
Device Chooser will let you choose among the devices.
#### Linux host computer
By default Linux doesn't recognize Android devices, but it's easy to fix this issue. On Ubuntu Linux
you have to create a new **/etc/udev/rules.d/51-android.rules** configuration file that contains
information about your Android device. You may find some Vendor ID's
[here](http://developer.android.com/tools/device.html#VendorIds) or execute lsusb command to view
VendorID of plugged Android device. Here is an example of such file for LG device:
@code{.guess}
SUBSYSTEM=="usb", ATTR{idVendor}=="1004", MODE="0666", GROUP="plugdev"
@endcode
Then restart your adb server (even better to restart the system), plug in your Android device and
execute adb devices command. You will see the list of attached devices:
![image](images/usb_device_connect_ubuntu.png)
#### Mac OS host computer
No actions are required, just connect your device via USB and run adb devices to check connection.
What's next
-----------
Now, when you have your development environment set up and configured, you may want to proceed to
installing OpenCV4Android SDK. You can learn how to do that in a separate @ref O4A_SDK tutorial.

View File

@@ -0,0 +1,371 @@
Android Development with OpenCV {#tutorial_dev_with_OCV_on_Android}
===============================
This tutorial has been created to help you use OpenCV library within your Android project.
This guide was written with Windows 7 in mind, though it should work with any other OS supported by
OpenCV4Android SDK.
This tutorial assumes you have the following installed and configured:
- JDK
- Android SDK and NDK
- Eclipse IDE
- ADT and CDT plugins for Eclipse
If you need help with anything of the above, you may refer to our @ref android_dev_intro guide.
This tutorial also assumes you have OpenCV4Android SDK already installed on your development machine
and OpenCV Manager on your testing device correspondingly. If you need help with any of these, you
may consult our @ref O4A_SDK tutorial.
If you encounter any error after thoroughly following these steps, feel free to contact us via
[OpenCV4Android](https://groups.google.com/group/android-opencv/) discussion group or OpenCV [Q&A
forum](http://answers.opencv.org) . We'll do our best to help you out.
Using OpenCV Library Within Your Android Project
------------------------------------------------
In this section we will explain how to make some existing project to use OpenCV. Starting with 2.4.2
release for Android, *OpenCV Manager* is used to provide apps with the best available version of
OpenCV. You can get more information here: @ref Android_OpenCV_Manager and in these
[slides](https://docs.google.com/a/itseez.com/presentation/d/1EO_1kijgBg_BsjNp2ymk-aarg-0K279_1VZRcPplSuk/present#slide=id.p).
### Java
#### Application Development with Async Initialization
Using async initialization is a **recommended** way for application development. It uses the OpenCV
Manager to access OpenCV libraries externally installed in the target system.
1. Add OpenCV library project to your workspace. Use menu
File -\> Import -\> Existing project in your workspace.
Press Browse button and locate OpenCV4Android SDK (`OpenCV-2.4.9-android-sdk/sdk`).
![image](images/eclipse_opencv_dependency0.png)
2. In application project add a reference to the OpenCV Java SDK in
Project -\> Properties -\> Android -\> Library -\> Add select OpenCV Library - 2.4.9.
![image](images/eclipse_opencv_dependency1.png)
In most cases OpenCV Manager may be installed automatically from Google Play. For the case, when
Google Play is not available, i.e. emulator, developer board, etc, you can install it manually using
adb tool. See @ref manager_selection for details.
There is a very base code snippet implementing the async initialization. It shows basic principles.
See the "15-puzzle" OpenCV sample for details.
@code{.java}
public class Sample1Java extends Activity implements CvCameraViewListener {
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
@Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Log.i(TAG, "OpenCV loaded successfully");
mOpenCvCameraView.enableView();
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
@Override
public void onResume()
{
super.onResume();
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_6, this, mLoaderCallback);
}
...
}
@endcode
It this case application works with OpenCV Manager in asynchronous fashion. OnManagerConnected
callback will be called in UI thread, when initialization finishes. Please note, that it is not
allowed to use OpenCV calls or load OpenCV-dependent native libs before invoking this callback. Load
your own native libraries that depend on OpenCV after the successful OpenCV initialization. Default
BaseLoaderCallback implementation treat application context as Activity and calls Activity.finish()
method to exit in case of initialization failure. To override this behavior you need to override
finish() method of BaseLoaderCallback class and implement your own finalization method.
#### Application Development with Static Initialization
According to this approach all OpenCV binaries are included into your application package. It is
designed mostly for development purposes. This approach is deprecated for the production code,
release package is recommended to communicate with OpenCV Manager via the async initialization
described above.
1. Add the OpenCV library project to your workspace the same way as for the async initialization
above. Use menu File -\> Import -\> Existing project in your workspace, press Browse button and
select OpenCV SDK path (`OpenCV-2.4.9-android-sdk/sdk`).
![image](images/eclipse_opencv_dependency0.png)
2. In the application project add a reference to the OpenCV4Android SDK in
Project -\> Properties -\> Android -\> Library -\> Add select OpenCV Library - 2.4.9;
![image](images/eclipse_opencv_dependency1.png)
3. If your application project **doesn't have a JNI part**, just copy the corresponding OpenCV
native libs from `<OpenCV-2.4.9-android-sdk>/sdk/native/libs/<target_arch>` to your project
directory to folder `libs/<target_arch>`.
In case of the application project **with a JNI part**, instead of manual libraries copying you
need to modify your Android.mk file: add the following two code lines after the
"include \\f$(CLEAR_VARS)" and before
"include path_to_OpenCV-2.4.9-android-sdk/sdk/native/jni/OpenCV.mk"
@code{.make}
OPENCV_CAMERA_MODULES:=on
OPENCV_INSTALL_MODULES:=on
@endcode
The result should look like the following:
@code{.make}
include \f$(CLEAR_VARS)
# OpenCV
OPENCV_CAMERA_MODULES:=on
OPENCV_INSTALL_MODULES:=on
include ../../sdk/native/jni/OpenCV.mk
@endcode
After that the OpenCV libraries will be copied to your application `libs` folder during the JNI
build.v
Eclipse will automatically include all the libraries from the `libs` folder to the application
package (APK).
4. The last step of enabling OpenCV in your application is Java initialization code before calling
OpenCV API. It can be done, for example, in the static section of the Activity class:
@code{.java}
static {
if (!OpenCVLoader.initDebug()) {
// Handle initialization error
}
}
@endcode
If you application includes other OpenCV-dependent native libraries you should load them
**after** OpenCV initialization:
@code{.java}
static {
if (!OpenCVLoader.initDebug()) {
// Handle initialization error
} else {
System.loadLibrary("my_jni_lib1");
System.loadLibrary("my_jni_lib2");
}
}
@endcode
### Native/C++
To build your own Android application, using OpenCV as native part, the following steps should be
taken:
1. You can use an environment variable to specify the location of OpenCV package or just hardcode
absolute or relative path in the `jni/Android.mk` of your projects.
2. The file `jni/Android.mk` should be written for the current application using the common rules
for this file.
For detailed information see the Android NDK documentation from the Android NDK archive, in the
file `<path_where_NDK_is_placed>/docs/ANDROID-MK.html`.
3. The following line:
@code{.make}
include C:\Work\OpenCV4Android\OpenCV-2.4.9-android-sdk\sdk\native\jni\OpenCV.mk
@endcode
Should be inserted into the `jni/Android.mk` file **after** this line:
@code{.make}
include \f$(CLEAR_VARS)
@endcode
4. Several variables can be used to customize OpenCV stuff, but you **don't need** to use them when
your application uses the async initialization via the OpenCV Manager API.
@note These variables should be set **before** the "include .../OpenCV.mk" line:
@code{.make}
OPENCV_INSTALL_MODULES:=on
@endcode
Copies necessary OpenCV dynamic libs to the project libs folder in order to include them
into the APK.
@code{.make}
OPENCV_CAMERA_MODULES:=off
@endcode
Skip native OpenCV camera related libs copying to the project libs folder.
@code{.make}
OPENCV_LIB_TYPE:=STATIC
@endcode
Perform static linking with OpenCV. By default dynamic link is used and the project JNI lib
depends on libopencv_java.so.
1. The file `Application.mk` should exist and should contain lines:
@code{.make}
APP_STL := gnustl_static
APP_CPPFLAGS := -frtti -fexceptions
@endcode
Also, the line like this one:
@code{.make}
APP_ABI := armeabi-v7a
@endcode
Should specify the application target platforms.
In some cases a linkage error (like
`"In function 'cv::toUtf16(std::basic_string<...>... undefined reference to 'mbstowcs'"`)
happens when building an application JNI library, depending on OpenCV. The following line in the
`Application.mk` usually fixes it:
@code{.make}
APP_PLATFORM := android-9
@endcode
2. Either use @ref manual \<NDK_build_cli\> ndk-build invocation or @ref setup Eclipse CDT
Builder \<CDT_Builder\> to build native JNI lib before (re)building the Java part and creating
an APK.
Hello OpenCV Sample
-------------------
Here are basic steps to guide you trough the process of creating a simple OpenCV-centric
application. It will be capable of accessing camera output, processing it and displaying the result.
1. Open Eclipse IDE, create a new clean workspace, create a new Android project
File --\> New --\> Android Project
2. Set name, target, package and minSDKVersion accordingly. The minimal SDK version for build with
OpenCV4Android SDK is 11. Minimal device API Level (for application manifest) is 8.
3. Allow Eclipse to create default activity. Lets name the activity HelloOpenCvActivity.
4. Choose Blank Activity with full screen layout. Lets name the layout HelloOpenCvLayout.
5. Import OpenCV library project to your workspace.
6. Reference OpenCV library within your project properties.
![image](images/dev_OCV_reference.png)
7. Edit your layout file as xml file and pass the following layout there:
@code{.xml}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:opencv="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<org.opencv.android.JavaCameraView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:visibility="gone"
android:id="@+id/HelloOpenCvView"
opencv:show_fps="true"
opencv:camera_id="any" />
</LinearLayout>
@endcode
8. Add the following permissions to the `AndroidManifest.xml` file:
@code{.xml}
</application>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" android:required="false"/>
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/>
<uses-feature android:name="android.hardware.camera.front" android:required="false"/>
<uses-feature android:name="android.hardware.camera.front.autofocus" android:required="false"/>
@endcode
9. Set application theme in AndroidManifest.xml to hide title and system buttons.
@code{.xml}
<application
android:icon="@drawable/icon"
android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >
@endcode
10. Add OpenCV library initialization to your activity. Fix errors by adding requited imports.
@code{.java}
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
@Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Log.i(TAG, "OpenCV loaded successfully");
mOpenCvCameraView.enableView();
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
@Override
public void onResume()
{
super.onResume();
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_6, this, mLoaderCallback);
}
@endcode
11. Defines that your activity implements CvCameraViewListener2 interface and fix activity related
errors by defining missed methods. For this activity define onCreate, onDestroy and onPause and
implement them according code snippet bellow. Fix errors by adding requited imports.
@code{.java}
private CameraBridgeViewBase mOpenCvCameraView;
@Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "called onCreate");
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.HelloOpenCvLayout);
mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.HelloOpenCvView);
mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
mOpenCvCameraView.setCvCameraViewListener(this);
}
@Override
public void onPause()
{
super.onPause();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
public void onDestroy() {
super.onDestroy();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
public void onCameraViewStarted(int width, int height) {
}
public void onCameraViewStopped() {
}
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
return inputFrame.rgba();
}
@endcode
12. Run your application on device or emulator.
Lets discuss some most important steps. Every Android application with UI must implement Activity
and View. By the first steps we create blank activity and default view layout. The simplest
OpenCV-centric application must implement OpenCV initialization, create its own view to show preview
from camera and implements CvCameraViewListener2 interface to get frames from camera and process it.
First of all we create our application view using xml layout. Our layout consists of the only one
full screen component of class org.opencv.android.JavaCameraView. This class is implemented inside
OpenCV library. It is inherited from CameraBridgeViewBase, that extends SurfaceView and uses
standard Android camera API. Alternatively you can use org.opencv.android.NativeCameraView class,
that implements the same interface, but uses VideoCapture class as camera access back-end.
opencv:show_fps="true" and opencv:camera_id="any" options enable FPS message and allow to use any
camera on device. Application tries to use back camera first.
After creating layout we need to implement Activity class. OpenCV initialization process has been
already discussed above. In this sample we use asynchronous initialization. Implementation of
CvCameraViewListener interface allows you to add processing steps after frame grabbing from camera
and before its rendering on screen. The most important function is onCameraFrame. It is callback
function and it is called on retrieving frame from camera. The callback input is object of
CvCameraViewFrame class that represents frame from camera.
@note Do not save or use CvCameraViewFrame object out of onCameraFrame callback. This object does
not have its own state and its behavior out of callback is unpredictable! It has rgba() and gray()
methods that allows to get frame as RGBA and one channel gray scale Mat respectively. It expects
that onCameraFrame function returns RGBA frame that will be drawn on the screen.

View File

@@ -0,0 +1,580 @@
Introduction to OpenCV Development with Clojure {#tutorial_clojure_dev_intro}
===============================================
As of OpenCV 2.4.4, OpenCV supports desktop Java development using nearly the same interface as for
Android development.
[Clojure](http://clojure.org/) is a contemporary LISP dialect hosted by the Java Virtual Machine and
it offers a complete interoperability with the underlying JVM. This means that we should even be
able to use the Clojure REPL (Read Eval Print Loop) as and interactive programmable interface to the
underlying OpenCV engine.
What we'll do in this tutorial
------------------------------
This tutorial will help you in setting up a basic Clojure environment for interactively learning
OpenCV within the fully programmable CLojure REPL.
### Tutorial source code
You can find a runnable source code of the sample in the `samples/java/clojure/simple-sample` folder
of the OpenCV repository. After having installed OpenCV and Clojure as explained in the tutorial,
issue the following command to run the sample from the command line.
@code{.bash}
cd path/to/samples/java/clojure/simple-sample
lein run
@endcode
Preamble
--------
For detailed instruction on installing OpenCV with desktop Java support refer to the [corresponding
tutorial](http://docs.opencv.org/2.4.4-beta/doc/tutorials/introduction/desktop_java/java_dev_intro.html).
If you are in hurry, here is a minimum quick start guide to install OpenCV on Mac OS X:
NOTE 1: I'm assuming you already installed [xcode](https://developer.apple.com/xcode/),
[jdk](http://www.oracle.com/technetwork/java/javase/downloads/index.html) and
[Cmake](http://www.cmake.org/cmake/resources/software.html).
@code{.bash}
cd ~/
mkdir opt
git clone https://github.com/Itseez/opencv.git
cd opencv
git checkout 2.4
mkdir build
cd build
cmake -DBUILD_SHARED_LIBS=OFF ..
...
...
make -j8
# optional
# make install
@endcode
Install Leiningen
-----------------
Once you installed OpenCV with desktop java support the only other requirement is to install
[Leiningeng](https://github.com/technomancy/leiningen) which allows you to manage the entire life
cycle of your CLJ projects.
The available [installation guide](https://github.com/technomancy/leiningen#installation) is very
easy to be followed:
1. [Download the script](https://raw.github.com/technomancy/leiningen/stable/bin/lein)
2. Place it on your \\f$PATH (cf. \~/bin is a good choice if it is on your path.)
3. Set the script to be executable. (i.e. chmod 755 \~/bin/lein).
If you work on Windows, follow [this instruction](https://github.com/technomancy/leiningen#windows)
You now have both the OpenCV library and a fully installed basic Clojure environment. What is now
needed is to configure the Clojure environment to interact with the OpenCV library.
Install the localrepo Leiningen plugin
--------------------------------------
The set of commands (tasks in Leiningen parlance) natively supported by Leiningen can be very easily
extended by various plugins. One of them is the
[lein-localrepo](https://github.com/kumarshantanu/lein-localrepo) plugin which allows to install any
jar lib as an artifact in the local maven repository of your machine (typically in the
\~/.m2/repository directory of your username).
We're going to use this lein plugin to add to the local maven repository the opencv components
needed by Java and Clojure to use the opencv lib.
Generally speaking, if you want to use a plugin on project base only, it can be added directly to a
CLJ project created by lein.
Instead, when you want a plugin to be available to any CLJ project in your username space, you can
add it to the profiles.clj in the \~/.lein/ directory.
The lein-localrepo plugin will be useful to me in other CLJ projects where I need to call native
libs wrapped by a Java interface. So I decide to make it available to any CLJ project:
@code{.bash}
mkdir ~/.lein
@endcode
Create a file named profiles.clj in the \~/.lein directory and copy into it the following content:
@code{.clojure}
{:user {:plugins [[lein-localrepo "0.5.2"]]}}
@endcode
Here we're saying that the version release "0.5.2" of the lein-localrepo plugin will be available to
the :user profile for any CLJ project created by lein.
You do not need to do anything else to install the plugin because it will be automatically
downloaded from a remote repository the very first time you issue any lein task.
Install the java specific libs as local repository
--------------------------------------------------
If you followed the standard documentation for installing OpenCV on your computer, you should find
the following two libs under the directory where you built OpenCV:
- the build/bin/opencv-247.jar java lib
- the build/lib/libopencv_java247.dylib native lib (or .so in you built OpenCV a GNU/Linux OS)
They are the only opencv libs needed by the JVM to interact with OpenCV.
### Take apart the needed opencv libs
Create a new directory to store in the above two libs. Start by copying into it the opencv-247.jar
lib.
@code{.bash}
cd ~/opt
mkdir clj-opencv
cd clj-opencv
cp ~/opt/opencv/build/bin/opencv-247.jar .
@endcode
First lib done.
Now, to be able to add the libopencv_java247.dylib shared native lib to the local maven repository,
we first need to package it as a jar file.
The native lib has to be copied into a directories layout which mimics the names of your operating
system and architecture. I'm using a Mac OS X with a X86 64 bit architecture. So my layout will be
the following:
@code{.bash}
mkdir -p native/macosx/x86_64
@endcode
Copy into the x86_64 directory the libopencv_java247.dylib lib.
@code{.bash}
cp ~/opt/opencv/build/lib/libopencv_java247.dylib native/macosx/x86_64/
@endcode
If you're running OpenCV from a different OS/Architecture pair, here is a summary of the mapping you
can choose from.
@code{.bash}
OS
Mac OS X -> macosx
Windows -> windows
Linux -> linux
SunOS -> solaris
Architectures
amd64 -> x86_64
x86_64 -> x86_64
x86 -> x86
i386 -> x86
arm -> arm
sparc -> sparc
@endcode
### Package the native lib as a jar
Next you need to package the native lib in a jar file by using the jar command to create a new jar
file from a directory.
@code{.bash}
jar -cMf opencv-native-247.jar native
@endcode
Note that ehe M option instructs the jar command to not create a MANIFEST file for the artifact.
Your directories layout should look like the following:
@code{.bash}
tree
.
|__ native
|   |__ macosx
|   |__ x86_64
|   |__ libopencv_java247.dylib
|
|__ opencv-247.jar
|__ opencv-native-247.jar
3 directories, 3 files
@endcode
### Locally install the jars
We are now ready to add the two jars as artifacts to the local maven repository with the help of the
lein-localrepo plugin.
@code{.bash}
lein localrepo install opencv-247.jar opencv/opencv 2.4.7
@endcode
Here the localrepo install task creates the 2.4.7. release of the opencv/opencv maven artifact from
the opencv-247.jar lib and then installs it into the local maven repository. The opencv/opencv
artifact will then be available to any maven compliant project (Leiningen is internally based on
maven).
Do the same thing with the native lib previously wrapped in a new jar file.
@code{.bash}
lein localrepo install opencv-native-247.jar opencv/opencv-native 2.4.7
@endcode
Note that the groupId, opencv, of the two artifacts is the same. We are now ready to create a new
CLJ project to start interacting with OpenCV.
### Create a project
Create a new CLJ project by using the lein new task from the terminal.
@code{.bash}
# cd in the directory where you work with your development projects (e.g. ~/devel)
lein new simple-sample
Generating a project called simple-sample based on the 'default' template.
To see other templates (app, lein plugin, etc), try `lein help new`.
@endcode
The above task creates the following simple-sample directories layout:
@code{.bash}
tree simple-sample/
simple-sample/
|__ LICENSE
|__ README.md
|__ doc
|   |__ intro.md
|
|__ project.clj
|__ resources
|__ src
|   |__ simple_sample
|   |__ core.clj
|__ test
|__ simple_sample
|__ core_test.clj
6 directories, 6 files
@endcode
We need to add the two opencv artifacts as dependencies of the newly created project. Open the
project.clj and modify its dependencies section as follows:
@code{.bash}
(defproject simple-sample "0.1.0-SNAPSHOT"
description "FIXME: write description"
url "http://example.com/FIXME"
license {:name "Eclipse Public License"
url "http://www.eclipse.org/legal/epl-v10.html"}
dependencies [[org.clojure/clojure "1.5.1"]
[opencv/opencv "2.4.7"] ; added line
[opencv/opencv-native "2.4.7"]]) ;added line
@endcode
Note that The Clojure Programming Language is a jar artifact too. This is why Clojure is called an
hosted language.
To verify that everything went right issue the lein deps task. The very first time you run a lein
task it will take sometime to download all the required dependencies before executing the task
itself.
@code{.bash}
cd simple-sample
lein deps
...
@endcode
The deps task reads and merges from the project.clj and the \~/.lein/profiles.clj files all the
dependencies of the simple-sample project and verifies if they have already been cached in the local
maven repository. If the task returns without messages about not being able to retrieve the two new
artifacts your installation is correct, otherwise go back and double check that you did everything
right.
### REPLing with OpenCV
Now cd in the simple-sample directory and issue the following lein task:
@code{.bash}
cd simple-sample
lein repl
...
...
nREPL server started on port 50907 on host 127.0.0.1
REPL-y 0.3.0
Clojure 1.5.1
Docs: (doc function-name-here)
(find-doc "part-of-name-here")
Source: (source function-name-here)
Javadoc: (javadoc java-object-or-class-here)
Exit: Control+D or (exit) or (quit)
Results: Stored in vars *1, *2, *3, an exception in *e
user=>
@endcode
You can immediately interact with the REPL by issuing any CLJ expression to be evaluated.
@code{.clojure}
user=> (+ 41 1)
42
user=> (println "Hello, OpenCV!")
Hello, OpenCV!
nil
user=> (defn foo [] (str "bar"))
#'user/foo
user=> (foo)
"bar"
@endcode
When ran from the home directory of a lein based project, even if the lein repl task automatically
loads all the project dependencies, you still need to load the opencv native library to be able to
interact with the OpenCV.
@code{.clojure}
user=> (clojure.lang.RT/loadLibrary org.opencv.core.Core/NATIVE_LIBRARY_NAME)
nil
@endcode
Then you can start interacting with OpenCV by just referencing the fully qualified names of its
classes.
NOTE 2: [Here](http://docs.opencv.org/java/) you can find the full OpenCV Java API.
@code{.clojure}
user=> (org.opencv.core.Point. 0 0)
#<Point {0.0, 0.0}>
@endcode
Here we created a two dimensions opencv Point instance. Even if all the java packages included
within the java interface to OpenCV are immediately available from the CLJ REPL, it's very annoying
to prefix the Point. instance constructors with the fully qualified package name.
Fortunately CLJ offer a very easy way to overcome this annoyance by directly importing the Point
class.
@code{.clojure}
user=> (import 'org.opencv.core.Point)
org.opencv.core.Point
user=> (def p1 (Point. 0 0))
#'user/p1
user=> p1
#<Point {0.0, 0.0}>
user=> (def p2 (Point. 100 100))
#'user/p2
@endcode
We can even inspect the class of an instance and verify if the value of a symbol is an instance of a
Point java class.
@code{.clojure}
user=> (class p1)
org.opencv.core.Point
user=> (instance? org.opencv.core.Point p1)
true
@endcode
If we now want to use the opencv Rect class to create a rectangle, we again have to fully qualify
its constructor even if it leaves in the same org.opencv.core package of the Point class.
@code{.clojure}
user=> (org.opencv.core.Rect. p1 p2)
#<Rect {0, 0, 100x100}>
@endcode
Again, the CLJ importing facilities is very handy and let you to map more symbols in one shot.
@code{.clojure}
user=> (import '[org.opencv.core Point Rect Size])
org.opencv.core.Size
user=> (def r1 (Rect. p1 p2))
#'user/r1
user=> r1
#<Rect {0, 0, 100x100}>
user=> (class r1)
org.opencv.core.Rect
user=> (instance? org.opencv.core.Rect r1)
true
user=> (Size. 100 100)
#<Size 100x100>
user=> (def sq-100 (Size. 100 100))
#'user/sq-100
user=> (class sq-100)
org.opencv.core.Size
user=> (instance? org.opencv.core.Size sq-100)
true
@endcode
Obviously you can call methods on instances as well.
@code{.clojure}
user=> (.area r1)
10000.0
user=> (.area sq-100)
10000.0
@endcode
Or modify the value of a member field.
@code{.clojure}
user=> (set! (.x p1) 10)
10
user=> p1
#<Point {10.0, 0.0}>
user=> (set! (.width sq-100) 10)
10
user=> (set! (.height sq-100) 10)
10
user=> (.area sq-100)
100.0
@endcode
If you find yourself not remembering a OpenCV class behavior, the REPL gives you the opportunity to
easily search the corresponding javadoc documention:
@code{.clojure}
user=> (javadoc Rect)
"http://www.google.com/search?btnI=I%27m%20Feeling%20Lucky&q=allinurl:org/opencv/core/Rect.html"
@endcode
### Mimic the OpenCV Java Tutorial Sample in the REPL
Let's now try to port to Clojure the [opencv java tutorial
sample](http://docs.opencv.org/2.4.4-beta/doc/tutorials/introduction/desktop_java/java_dev_intro.html).
Instead of writing it in a source file we're going to evaluate it at the REPL.
Following is the original Java source code of the cited sample.
@code{.java}
import org.opencv.core.Mat;
import org.opencv.core.CvType;
import org.opencv.core.Scalar;
class SimpleSample {
static{ System.loadLibrary("opencv_java244"); }
public static void main(String[] args) {
Mat m = new Mat(5, 10, CvType.CV_8UC1, new Scalar(0));
System.out.println("OpenCV Mat: " + m);
Mat mr1 = m.row(1);
mr1.setTo(new Scalar(1));
Mat mc5 = m.col(5);
mc5.setTo(new Scalar(5));
System.out.println("OpenCV Mat data:\n" + m.dump());
}
}
@endcode
### Add injections to the project
Before start coding, we'd like to eliminate the boring need of interactively loading the native
opencv lib any time we start a new REPL to interact with it.
First, stop the REPL by evaluating the (exit) expression at the REPL prompt.
@code{.clojure}
user=> (exit)
Bye for now!
@endcode
Then open your project.clj file and edit it as follows:
@code{.clojure}
(defproject simple-sample "0.1.0-SNAPSHOT"
...
injections [(clojure.lang.RT/loadLibrary org.opencv.core.Core/NATIVE_LIBRARY_NAME)])
@endcode
Here we're saying to load the opencv native lib anytime we run the REPL in such a way that we have
not anymore to remember to manually do it.
Rerun the lein repl task
@code{.bash}
lein repl
nREPL server started on port 51645 on host 127.0.0.1
REPL-y 0.3.0
Clojure 1.5.1
Docs: (doc function-name-here)
(find-doc "part-of-name-here")
Source: (source function-name-here)
Javadoc: (javadoc java-object-or-class-here)
Exit: Control+D or (exit) or (quit)
Results: Stored in vars *1, *2, *3, an exception in *e
user=>
@endcode
Import the interested OpenCV java interfaces.
@code{.clojure}
user=> (import '[org.opencv.core Mat CvType Scalar])
org.opencv.core.Scalar
@endcode
We're going to mimic almost verbatim the original OpenCV java tutorial to:
- create a 5x10 matrix with all its elements intialized to 0
- change the value of every element of the second row to 1
- change the value of every element of the 6th column to 5
- print the content of the obtained matrix
@code{.clojure}
user=> (def m (Mat. 5 10 CvType/CV_8UC1 (Scalar. 0 0)))
#'user/m
user=> (def mr1 (.row m 1))
#'user/mr1
user=> (.setTo mr1 (Scalar. 1 0))
#<Mat Mat [ 1*10*CV_8UC1, isCont=true, isSubmat=true, nativeObj=0x7fc9dac49880, dataAddr=0x7fc9d9c98d5a ]>
user=> (def mc5 (.col m 5))
#'user/mc5
user=> (.setTo mc5 (Scalar. 5 0))
#<Mat Mat [ 5*1*CV_8UC1, isCont=false, isSubmat=true, nativeObj=0x7fc9d9c995a0, dataAddr=0x7fc9d9c98d55 ]>
user=> (println (.dump m))
[0, 0, 0, 0, 0, 5, 0, 0, 0, 0;
1, 1, 1, 1, 1, 5, 1, 1, 1, 1;
0, 0, 0, 0, 0, 5, 0, 0, 0, 0;
0, 0, 0, 0, 0, 5, 0, 0, 0, 0;
0, 0, 0, 0, 0, 5, 0, 0, 0, 0]
nil
@endcode
If you are accustomed to a functional language all those abused and mutating nouns are going to
irritate your preference for verbs. Even if the CLJ interop syntax is very handy and complete, there
is still an impedance mismatch between any OOP language and any FP language (bein Scala a mixed
paradigms programming language).
To exit the REPL type (exit), ctr-D or (quit) at the REPL prompt.
@code{.clojure}
user=> (exit)
Bye for now!
@endcode
### Interactively load and blur an image
In the next sample you will learn how to interactively load and blur and image from the REPL by
using the following OpenCV methods:
- the imread static method from the Highgui class to read an image from a file
- the imwrite static method from the Highgui class to write an image to a file
- the GaussianBlur static method from the Imgproc class to apply to blur the original image
We're also going to use the Mat class which is returned from the imread method and accpeted as the
main argument to both the GaussianBlur and the imwrite methods.
### Add an image to the project
First we want to add an image file to a newly create directory for storing static resources of the
project.
![image](images/lena.png)
@code{.bash}
mkdir -p resources/images
cp ~/opt/opencv/doc/tutorials/introduction/desktop_java/images/lena.png resource/images/
@endcode
### Read the image
Now launch the REPL as usual and start by importing all the OpenCV classes we're going to use:
@code{.clojure}
lein repl
nREPL server started on port 50624 on host 127.0.0.1
REPL-y 0.3.0
Clojure 1.5.1
Docs: (doc function-name-here)
(find-doc "part-of-name-here")
Source: (source function-name-here)
Javadoc: (javadoc java-object-or-class-here)
Exit: Control+D or (exit) or (quit)
Results: Stored in vars *1, *2, *3, an exception in *e
user=> (import '[org.opencv.core Mat Size CvType]
'[org.opencv.imgcodecs Imgcodecs]
'[org.opencv.imgproc Imgproc])
org.opencv.imgproc.Imgproc
@endcode
Now read the image from the resources/images/lena.png file.
@code{.clojure}
user=> (def lena (Highgui/imread "resources/images/lena.png"))
#'user/lena
user=> lena
#<Mat Mat [ 512*512*CV_8UC3, isCont=true, isSubmat=false, nativeObj=0x7f9ab3054c40, dataAddr=0x19fea9010 ]>
@endcode
As you see, by simply evaluating the lena symbol we know that lena.png is a 512x512 matrix of
CV_8UC3 elements type. Let's create a new Mat instance of the same dimensions and elements type.
@code{.clojure}
user=> (def blurred (Mat. 512 512 CvType/CV_8UC3))
#'user/blurred
user=>
@endcode
Now apply a GaussianBlur filter using lena as the source matrix and blurred as the destination
matrix.
@code{.clojure}
user=> (Imgproc/GaussianBlur lena blurred (Size. 5 5) 3 3)
nil
@endcode
As a last step just save the blurred matrix in a new image file.
@code{.clojure}
user=> (Highgui/imwrite "resources/images/blurred.png" blurred)
true
user=> (exit)
Bye for now!
@endcode
Following is the new blurred image of Lena.
![image](images/blurred.png)
Next Steps
----------
This tutorial only introduces the very basic environment set up to be able to interact with OpenCV
in a CLJ REPL.
I recommend any Clojure newbie to read the [Clojure Java Interop
chapter](http://clojure.org/java_interop) to get all you need to know to interoperate with any plain
java lib that has not been wrapped in Clojure to make it usable in a more idiomatic and functional
way within Clojure.
The OpenCV Java API does not wrap the highgui module functionalities depending on Qt (e.g.
namedWindow and imshow. If you want to create windows and show images into them while interacting
with OpenCV from the REPL, at the moment you're left at your own. You could use Java Swing to fill
the gap.
### License
Copyright © 2013 Giacomo (Mimmo) Cosenza aka Magomimmo
Distributed under the BSD 3-clause License, the same of OpenCV.

View File

@@ -0,0 +1,90 @@
Cross compilation for ARM based Linux systems {#tutorial_arm_crosscompile_with_cmake}
=============================================
This steps are tested on Ubuntu Linux 12.04, but should work for other Linux distributions. I case
of other distributions package names and names of cross compilation tools may differ. There are
several popular EABI versions that are used on ARM platform. This tutorial is written for *gnueabi*
and *gnueabihf*, but other variants should work with minimal changes.
Prerequisites
-------------
- Host computer with Linux;
- Git;
- CMake 2.6 or higher;
- Cross compilation tools for ARM: gcc, libstc++, etc. Depending on target platform you need to
choose *gnueabi* or *gnueabihf* tools. Install command for *gnueabi*:
@code{.bash}
sudo apt-get install gcc-arm-linux-gnueabi
@endcode
Install command for *gnueabihf*:
@code{.bash}
sudo apt-get install gcc-arm-linux-gnueabihf
@endcode
- pkgconfig;
- Python 2.6 for host system;
- [optional] ffmpeg or libav development packages for armeabi(hf): libavcodec-dev,
libavformat-dev, libswscale-dev;
- [optional] GTK+2.x or higher, including headers (libgtk2.0-dev) for armeabi(hf);
- [optional] libdc1394 2.x;
- [optional] libjpeg-dev, libpng-dev, libtiff-dev, libjasper-dev for armeabi(hf).
Getting OpenCV Source Code
--------------------------
You can use the latest stable OpenCV version available in *sourceforge* or you can grab the latest
snapshot from our [Git repository](https://github.com/Itseez/opencv.git).
### Getting the Latest Stable OpenCV Version
- Go to our [page on Sourceforge](http://sourceforge.net/projects/opencvlibrary);
- Download the source tarball and unpack it.
### Getting the Cutting-edge OpenCV from the Git Repository
Launch Git client and clone [OpenCV repository](http://github.com/itseez/opencv)
In Linux it can be achieved with the following command in Terminal:
@code{.bash}
cd ~/<my_working _directory>
git clone https://github.com/Itseez/opencv.git
@endcode
Building OpenCV
---------------
1. Create a build directory, make it current and run the following command:
@code{.bash}
cmake [<some optional parameters>] -DCMAKE_TOOLCHAIN_FILE=<path to the OpenCV source directory>/platforms/linux/arm-gnueabi.toolchain.cmake <path to the OpenCV source directory>
@endcode
Toolchain uses *gnueabihf* EABI convention by default. Add -DSOFTFP=ON cmake argument to switch
on softfp compiler.
@code{.bash}
cmake [<some optional parameters>] -DSOFTFP=ON -DCMAKE_TOOLCHAIN_FILE=<path to the OpenCV source directory>/platforms/linux/arm-gnueabi.toolchain.cmake <path to the OpenCV source directory>
@endcode
For example:
@code{.bash}
cd ~/opencv/platforms/linux
mkdir -p build_hardfp
cd build_hardfp
cmake -DCMAKE_TOOLCHAIN_FILE=../arm-gnueabi.toolchain.cmake ../../..
@endcode
2. Run make in build (\<cmake_binary_dir\>) directory:
@code{.bash}
make
@endcode
@note
Optionally you can strip symbols info from the created library via install/strip make target.
This option produces smaller binary (\~ twice smaller) but makes further debugging harder.
### Enable hardware optimizations
Depending on target platform architecture different instruction sets can be used. By default
compiler generates code for armv5l without VFPv3 and NEON extensions. Add -DENABLE_VFPV3=ON to
cmake command line to enable code generation for VFPv3 and -DENABLE_NEON=ON for using NEON SIMD
extensions.
TBB is supported on multi core ARM SoCs also. Add -DWITH_TBB=ON and -DBUILD_TBB=ON to enable it.
Cmake scripts download TBB sources from official project site
[](http://threadingbuildingblocks.org/) and build it.

View File

@@ -0,0 +1,373 @@
Introduction to Java Development {#tutorial_java_dev_intro}
================================
As of OpenCV 2.4.4, OpenCV supports desktop Java development using nearly the same interface as for
Android development. This guide will help you to create your first Java (or Scala) application using
OpenCV. We will use either [Apache Ant](http://ant.apache.org/) or [Simple Build Tool
(SBT)](http://www.scala-sbt.org/) to build the application.
If you want to use Eclipse head to @ref Java_Eclipse. For further reading after this guide, look at
the @ref Android_Dev_Intro tutorials.
What we'll do in this guide
---------------------------
In this guide, we will:
- Get OpenCV with desktop Java support
- Create an Ant or SBT project
- Write a simple OpenCV application in Java or Scala
The same process was used to create the samples in the `samples/java` folder of the OpenCV
repository, so consult those files if you get lost.
Get proper OpenCV
-----------------
Starting from version 2.4.4 OpenCV includes desktop Java bindings.
### Download
The most simple way to get it is downloading the appropriate package of **version 2.4.4 or higher**
from the [OpenCV SourceForge repository](http://sourceforge.net/projects/opencvlibrary/files/).
@note Windows users can find the prebuilt files needed for Java development in the
`opencv/build/java/` folder inside the package. For other OSes it's required to build OpenCV from
sources. Another option to get OpenCV sources is to clone [OpenCV git
repository](https://github.com/Itseez/opencv/). In order to build OpenCV with Java bindings you need
JDK (Java Development Kit) (we recommend [Oracle/Sun JDK 6 or
7](http://www.oracle.com/technetwork/java/javase/downloads/)), [Apache Ant](http://ant.apache.org/)
and Python v2.6 or higher to be installed.
### Build
Let's build OpenCV:
@code{.bash}
git clone git://github.com/Itseez/opencv.git
cd opencv
git checkout 2.4
mkdir build
cd build
@endcode
Generate a Makefile or a MS Visual Studio\* solution, or whatever you use for building executables
in your system:
@code{.bash}
cmake -DBUILD_SHARED_LIBS=OFF ..
@endcode
or
@code{.bat}
cmake -DBUILD_SHARED_LIBS=OFF -G "Visual Studio 10" ..
@endcode
@note When OpenCV is built as a set of **static** libraries (-DBUILD_SHARED_LIBS=OFF option) the
Java bindings dynamic library is all-sufficient, i.e. doesn't depend on other OpenCV libs, but
includes all the OpenCV code inside. Examine the output of CMake and ensure java is one of the
modules "To be built". If not, it's likely you're missing a dependency. You should troubleshoot by
looking through the CMake output for any Java-related tools that aren't found and installing them.
![image](images/cmake_output.png)
@note If CMake can't find Java in your system set the JAVA_HOME environment variable with the path to installed JDK before running it. E.g.:
@code{.bash}
export JAVA_HOME=/usr/lib/jvm/java-6-oracle
cmake -DBUILD_SHARED_LIBS=OFF ..
@endcode
Now start the build:
@code{.bash}
make -j8
@endcode
or
@code{.bat}
msbuild /m OpenCV.sln /t:Build /p:Configuration=Release /v:m
@endcode
Besides all this will create a jar containing the Java interface (`bin/opencv-244.jar`) and a native
dynamic library containing Java bindings and all the OpenCV stuff (`lib/libopencv_java244.so` or
`bin/Release/opencv_java244.dll` respectively). We'll use these files later.
Java sample with Ant
--------------------
@note The described sample is provided with OpenCV library in the `opencv/samples/java/ant`
folder. \* Create a folder where you'll develop this sample application.
- In this folder create the `build.xml` file with the following content using any text editor:
@code{.xml}
<project name="SimpleSample" basedir="." default="rebuild-run">
<property name="src.dir" value="src"/>
<property name="lib.dir" value="\f${ocvJarDir}"/>
<path id="classpath">
<fileset dir="\f${lib.dir}" includes="**/*.jar"/>
</path>
<property name="build.dir" value="build"/>
<property name="classes.dir" value="\f${build.dir}/classes"/>
<property name="jar.dir" value="\f${build.dir}/jar"/>
<property name="main-class" value="\f${ant.project.name}"/>
<target name="clean">
<delete dir="\f${build.dir}"/>
</target>
<target name="compile">
<mkdir dir="\f${classes.dir}"/>
<javac includeantruntime="false" srcdir="\f${src.dir}" destdir="\f${classes.dir}" classpathref="classpath"/>
</target>
<target name="jar" depends="compile">
<mkdir dir="\f${jar.dir}"/>
<jar destfile="\f${jar.dir}/\f${ant.project.name}.jar" basedir="\f${classes.dir}">
<manifest>
<attribute name="Main-Class" value="\f${main-class}"/>
</manifest>
</jar>
</target>
<target name="run" depends="jar">
<java fork="true" classname="\f${main-class}">
<sysproperty key="java.library.path" path="\f${ocvLibDir}"/>
<classpath>
<path refid="classpath"/>
<path location="\f${jar.dir}/\f${ant.project.name}.jar"/>
</classpath>
</java>
</target>
<target name="rebuild" depends="clean,jar"/>
<target name="rebuild-run" depends="clean,run"/>
</project>
@endcode
@note This XML file can be reused for building other Java applications. It describes a common folder structure in the lines 3 - 12 and common targets for compiling and running the application.
When reusing this XML don't forget to modify the project name in the line 1, that is also the
name of the main class (line 14). The paths to OpenCV jar and jni lib are expected as parameters
("\\f${ocvJarDir}" in line 5 and "\\f${ocvLibDir}" in line 37), but you can hardcode these paths for
your convenience. See [Ant documentation](http://ant.apache.org/manual/) for detailed
description of its build file format.
- Create an `src` folder next to the `build.xml` file and a `SimpleSample.java` file in it.
-
Put the following Java code into the `SimpleSample.java` file:
@code{.java}
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.CvType;
import org.opencv.core.Scalar;
class SimpleSample {
static{ System.loadLibrary(Core.NATIVE_LIBRARY_NAME); }
public static void main(String[] args) {
System.out.println("Welcome to OpenCV " + Core.VERSION);
Mat m = new Mat(5, 10, CvType.CV_8UC1, new Scalar(0));
System.out.println("OpenCV Mat: " + m);
Mat mr1 = m.row(1);
mr1.setTo(new Scalar(1));
Mat mc5 = m.col(5);
mc5.setTo(new Scalar(5));
System.out.println("OpenCV Mat data:\n" + m.dump());
}
}
@endcode
-
Run the following command in console in the folder containing `build.xml`:
@code{.bash}
ant -DocvJarDir=path/to/dir/containing/opencv-244.jar -DocvLibDir=path/to/dir/containing/opencv_java244/native/library
@endcode
For example:
@code{.bat}
ant -DocvJarDir=X:\opencv-2.4.4\bin -DocvLibDir=X:\opencv-2.4.4\bin\Release
@endcode
The command should initiate [re]building and running the sample. You should see on the
screen something like this:
![image](images/ant_output.png)
SBT project for Java and Scala
------------------------------
Now we'll create a simple Java application using SBT. This serves as a brief introduction to those
unfamiliar with this build tool. We're using SBT because it is particularly easy and powerful.
First, download and install [SBT](http://www.scala-sbt.org/) using the instructions on its [web
site](http://www.scala-sbt.org/).
Next, navigate to a new directory where you'd like the application source to live (outside `opencv`
dir). Let's call it "JavaSample" and create a directory for it:
@code{.bash}
cd <somewhere outside opencv>
mkdir JavaSample
@endcode
Now we will create the necessary folders and an SBT project:
@code{.bash}
cd JavaSample
mkdir -p src/main/java # This is where SBT expects to find Java sources
mkdir project # This is where the build definitions live
@endcode
Now open `project/build.scala` in your favorite editor and paste the following. It defines your
project:
@code{.scala}
import sbt._
import Keys._
object JavaSampleBuild extends Build {
def scalaSettings = Seq(
scalaVersion := "2.10.0",
scalacOptions ++= Seq(
"-optimize",
"-unchecked",
"-deprecation"
)
)
def buildSettings =
Project.defaultSettings ++
scalaSettings
lazy val root = {
val settings = buildSettings ++ Seq(name := "JavaSample")
Project(id = "JavaSample", base = file("."), settings = settings)
}
}
@endcode
Now edit `project/plugins.sbt` and paste the following. This will enable auto-generation of an
Eclipse project:
@code{.scala}
addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.1.0")
@endcode
Now run sbt from the `JavaSample` root and from within SBT run eclipse to generate an eclipse
project:
@code{.bash}
sbt # Starts the sbt console
eclipse # Running "eclipse" from within the sbt console
@endcode
You should see something like this:
![image](images/sbt_eclipse.png)
You can now import the SBT project to Eclipse using Import ... -\> Existing projects into workspace.
Whether you actually do this is optional for the guide; we'll be using SBT to build the project, so
if you choose to use Eclipse it will just serve as a text editor.
To test that everything is working, create a simple "Hello OpenCV" application. Do this by creating
a file `src/main/java/HelloOpenCV.java` with the following contents:
@code{.java}
public class HelloOpenCV {
public static void main(String[] args) {
System.out.println("Hello, OpenCV");
}
@endcode
}
Now execute run from the sbt console, or more concisely, run sbt run from the command line:
@code{.bash}
sbt run
@endcode
You should see something like this:
![image](images/sbt_run.png)
### Running SBT samples
Now we'll create a simple face detection application using OpenCV.
First, create a `lib/` folder and copy the OpenCV jar into it. By default, SBT adds jars in the lib
folder to the Java library search path. You can optionally rerun sbt eclipse to update your Eclipse
project.
@code{.bash}
mkdir lib
cp <opencv_dir>/build/bin/opencv_<version>.jar lib/
sbt eclipse
@endcode
Next, create the directory `src/main/resources` and download this Lena image into it:
![image](images/lena.png)
Make sure it's called `"lena.png"`. Items in the resources directory are available to the Java
application at runtime.
Next, copy `lbpcascade_frontalface.xml` from `opencv/data/lbpcascades/` into the `resources`
directory:
@code{.bash}
cp <opencv_dir>/data/lbpcascades/lbpcascade_frontalface.xml src/main/resources/
@endcode
Now modify src/main/java/HelloOpenCV.java so it contains the following Java code:
@code{.java}
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.objdetect.CascadeClassifier;
//
// Detects faces in an image, draws boxes around them, and writes the results
// to "faceDetection.png".
//
class DetectFaceDemo {
public void run() {
System.out.println("\nRunning DetectFaceDemo");
// Create a face detector from the cascade file in the resources
// directory.
CascadeClassifier faceDetector = new CascadeClassifier(getClass().getResource("/lbpcascade_frontalface.xml").getPath());
Mat image = Imgcodecs.imread(getClass().getResource("/lena.png").getPath());
// Detect faces in the image.
// MatOfRect is a special container class for Rect.
MatOfRect faceDetections = new MatOfRect();
faceDetector.detectMultiScale(image, faceDetections);
System.out.println(String.format("Detected %s faces", faceDetections.toArray().length));
// Draw a bounding box around each face.
for (Rect rect : faceDetections.toArray()) {
Imgproc.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0));
}
// Save the visualized detection.
String filename = "faceDetection.png";
System.out.println(String.format("Writing %s", filename));
Imgcodecs.imwrite(filename, image);
}
}
public class HelloOpenCV {
public static void main(String[] args) {
System.out.println("Hello, OpenCV");
// Load the native library.
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
new DetectFaceDemo().run();
}
}
@endcode
Note the call to System.loadLibrary(Core.NATIVE_LIBRARY_NAME). This command must be executed
exactly once per Java process prior to using any native OpenCV methods. If you don't call it, you
will get UnsatisfiedLink errors. You will also get errors if you try to load OpenCV when it has
already been loaded.
Now run the face detection app using \`sbt run\`:
@code{.bash}
sbt run
@endcode
You should see something like this:
![image](images/sbt_run_face.png)
It should also write the following image to `faceDetection.png`:
![image](images/faceDetection.png)
You're done! Now you have a sample Java application working with OpenCV, so you can start the work
on your own. We wish you good luck and many years of joyful life!

View File

@@ -0,0 +1,140 @@
Load and Display an Image {#tutorial_display_image}
=========================
Goal
----
In this tutorial you will learn how to:
- Load an image (using @ref cv::imread )
- Create a named OpenCV window (using @ref cv::namedWindow )
- Display an image in an OpenCV window (using @ref cv::imshow )
Source Code
-----------
Download the source code from
[here](https://github.com/Itseez/opencv/tree/master/samples/cpp/tutorial_code/introduction/display_image/display_image.cpp).
@includelineno cpp/tutorial_code/introduction/display_image/display_image.cpp
Explanation
-----------
In OpenCV 2 we have multiple modules. Each one takes care of a different area or approach towards
image processing. You could already observe this in the structure of the user guide of these
tutorials itself. Before you use any of them you first need to include the header files where the
content of each individual module is declared.
You'll almost always end up using the:
- *core* section, as here are defined the basic building blocks of the library
- *highgui* module, as this contains the functions for input and output operations
@includelineno cpp/tutorial_code/introduction/display_image/display_image.cpp
lines
1-6
We also include the *iostream* to facilitate console line output and input. To avoid data structure
and function name conflicts with other libraries, OpenCV has its own namespace: *cv*. To avoid the
need appending prior each of these the *cv::* keyword you can import the namespace in the whole file
by using the lines:
@includelineno cpp/tutorial_code/introduction/display_image/display_image.cpp
lines
8-9
This is true for the STL library too (used for console I/O). Now, let's analyze the *main* function.
We start up assuring that we acquire a valid image name argument from the command line. Otherwise
take a picture by default: "HappyFish.jpg".
@includelineno cpp/tutorial_code/introduction/display_image/display_image.cpp
lines
13-17
Then create a *Mat* object that will store the data of the loaded image.
@includelineno cpp/tutorial_code/introduction/display_image/display_image.cpp
lines
19
Now we call the @ref cv::imread function which loads the image name specified by the first argument
(*argv[1]*). The second argument specifies the format in what we want the image. This may be:
- IMREAD_UNCHANGED (\<0) loads the image as is (including the alpha channel if present)
- IMREAD_GRAYSCALE ( 0) loads the image as an intensity one
- IMREAD_COLOR (\>0) loads the image in the RGB format
@includelineno cpp/tutorial_code/introduction/display_image/display_image.cpp
lines
20
@note
OpenCV offers support for the image formats Windows bitmap (bmp), portable image formats (pbm,
pgm, ppm) and Sun raster (sr, ras). With help of plugins (you need to specify to use them if you
build yourself the library, nevertheless in the packages we ship present by default) you may
also load image formats like JPEG (jpeg, jpg, jpe), JPEG 2000 (jp2 - codenamed in the CMake as
Jasper), TIFF files (tiff, tif) and portable network graphics (png). Furthermore, OpenEXR is
also a possibility.
After checking that the image data was loaded correctly, we want to display our image, so we create
an OpenCV window using the @ref cv::namedWindow function. These are automatically managed by OpenCV
once you create them. For this you need to specify its name and how it should handle the change of
the image it contains from a size point of view. It may be:
- *WINDOW_AUTOSIZE* is the only supported one if you do not use the Qt backend. In this case the
window size will take up the size of the image it shows. No resize permitted!
- *WINDOW_NORMAL* on Qt you may use this to allow window resize. The image will resize itself
according to the current window size. By using the | operator you also need to specify if you
would like the image to keep its aspect ratio (*WINDOW_KEEPRATIO*) or not
(*WINDOW_FREERATIO*).
@includelineno cpp/tutorial_code/introduction/display_image/display_image.cpp
lines
28
Finally, to update the content of the OpenCV window with a new image use the @ref cv::imshow
function. Specify the OpenCV window name to update and the image to use during this operation:
@includelineno cpp/tutorial_code/introduction/display_image/display_image.cpp
lines
29
Because we want our window to be displayed until the user presses a key (otherwise the program would
end far too quickly), we use the @ref cv::waitKey function whose only parameter is just how long
should it wait for a user input (measured in milliseconds). Zero means to wait forever.
@includelineno cpp/tutorial_code/introduction/display_image/display_image.cpp
lines
31
Result
------
- Compile your code and then run the executable giving an image path as argument. If you're on
Windows the executable will of course contain an *exe* extension too. Of course assure the image
file is near your program file.
@code{.bash}
./DisplayImage HappyFish.jpg
@endcode
- You should get a nice window as the one shown below:
![image](images/Display_Image_Tutorial_Result.jpg)
\htmlonly
<div align="center">
<iframe title="Introduction - Display an Image" width="560" height="349" src="http://www.youtube.com/embed/1OJEqpuaGc4?rel=0&loop=1" frameborder="0" allowfullscreen align="middle"></iframe>
</div>
\endhtmlonly

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,40 @@
Installation in iOS {#tutorial_ios_install}
===================
Required Packages
-----------------
- CMake 2.8.8 or higher
- Xcode 4.2 or higher
### Getting the Cutting-edge OpenCV from Git Repository
Launch GIT client and clone OpenCV repository from [here](http://github.com/itseez/opencv)
In MacOS it can be done using the following command in Terminal:
@code{.bash}
cd ~/<my_working _directory>
git clone https://github.com/Itseez/opencv.git
@endcode
Building OpenCV from Source, using CMake and Command Line
---------------------------------------------------------
1. Make symbolic link for Xcode to let OpenCV build scripts find the compiler, header files etc.
@code{.bash}
cd /
sudo ln -s /Applications/Xcode.app/Contents/Developer Developer
@endcode
2. Build OpenCV framework:
@code{.bash}
cd ~/<my_working_directory>
python opencv/platforms/ios/build_framework.py ios
@endcode
If everything's fine, a few minutes later you will get
\~/\<my_working_directory\>/ios/opencv2.framework. You can add this framework to your Xcode
projects.
Further Reading
---------------
You can find several OpenCV+iOS tutorials here @ref Table-Of-Content-iOS.

View File

@@ -0,0 +1,89 @@
Using OpenCV Java with Eclipse {#tutorial_java_eclipse}
==============================
Since version 2.4.4 [OpenCV supports Java](http://opencv.org/opencv-java-api.html). In this tutorial
I will explain how to setup development environment for using OpenCV Java with Eclipse in
**Windows**, so you can enjoy the benefits of garbage collected, very refactorable (rename variable,
extract method and whatnot) modern language that enables you to write code with less effort and make
less mistakes. Here we go.
Configuring Eclipse
-------------------
First, obtain a fresh release of OpenCV [from download page](http://opencv.org/downloads.html) and
extract it under a simple location like C:\\OpenCV-2.4.6\\. I am using version 2.4.6, but the steps
are more or less the same for other versions.
Now, we will define OpenCV as a user library in Eclipse, so we can reuse the configuration for any
project. Launch Eclipse and select Window --\> Preferences from the menu.
![image](images/1-window-preferences.png)
Navigate under Java --\> Build Path --\> User Libraries and click New....
![image](images/2-user-library-new.png)
Enter a name, e.g. OpenCV-2.4.6, for your new library.
![image](images/3-library-name.png)
Now select your new user library and click Add External JARs....
![image](images/4-add-external-jars.png)
Browse through C:\\OpenCV-2.4.6\\build\\java\\ and select opencv-246.jar. After adding the jar,
extend the opencv-246.jar and select Native library location and press Edit....
![image](images/5-native-library.png)
Select External Folder... and browse to select the folder C:\\OpenCV-2.4.6\\build\\java\\x64. If you
have a 32-bit system you need to select the x86 folder instead of x64.
![image](images/6-external-folder.png)
Your user library configuration should look like this:
![image](images/7-user-library-final.png)
Testing the configuration on a new Java project
-----------------------------------------------
Now start creating a new Java project.
![image](images/7_5-new-java-project.png)
On the Java Settings step, under Libraries tab, select Add Library... and select OpenCV-2.4.6, then
click Finish.
![image](images/8-add-library.png)
![image](images/9-select-user-lib.png)
Libraries should look like this:
![image](images/10-new-project-created.png)
Now you have created and configured a new Java project it is time to test it. Create a new java
file. Here is a starter code for your convenience:
@code{.java}
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
public class Hello
{
public static void main( String[] args )
{
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
Mat mat = Mat.eye( 3, 3, CvType.CV_8UC1 );
System.out.println( "mat = " + mat.dump() );
}
}
@endcode
When you run the code you should see 3x3 identity matrix as output.
![image](images/11-the-code.png)
That is it, whenever you start a new project just add the OpenCV user library that you have defined
to your project and you are good to go. Enjoy your powerful, less painful development environment :)

View File

@@ -0,0 +1,200 @@
Using OpenCV with Eclipse (plugin CDT) {#tutorial_linux_eclipse}
======================================
@note Two ways, one by forming a project directly, and another by CMake Prerequisites
===============
1. Having installed [Eclipse](http://www.eclipse.org/) in your workstation (only the CDT plugin for
C/C++ is needed). You can follow the following steps:
- Go to the Eclipse site
- Download [Eclipse IDE for C/C++
Developers](http://www.eclipse.org/downloads/packages/eclipse-ide-cc-developers/heliossr2) .
Choose the link according to your workstation.
2. Having installed OpenCV. If not yet, go @ref here \<Linux-Installation\>.
Making a project
----------------
1. Start Eclipse. Just run the executable that comes in the folder.
2. Go to **File -\> New -\> C/C++ Project**
![image](images/a0.png)
3. Choose a name for your project (i.e. DisplayImage). An **Empty Project** should be okay for this
example.
![image](images/a1.png)
4. Leave everything else by default. Press **Finish**.
5. Your project (in this case DisplayImage) should appear in the **Project Navigator** (usually at
the left side of your window).
![image](images/a3.png)
6. Now, let's add a source file using OpenCV:
- Right click on **DisplayImage** (in the Navigator). **New -\> Folder** .
![image](images/a4.png)
- Name your folder **src** and then hit **Finish**
- Right click on your newly created **src** folder. Choose **New source file**:
- Call it **DisplayImage.cpp**. Hit **Finish**
![image](images/a7.png)
7. So, now you have a project with a empty .cpp file. Let's fill it with some sample code (in other
words, copy and paste the snippet below):
@code{.cpp}
#include <opencv2/opencv.hpp>
using namespace cv;
int main( int argc, char** argv )
{
Mat image;
image = imread( argv[1], 1 );
if( argc != 2 || !image.data )
{
printf( "No image data \n" );
return -1;
}
namedWindow( "Display Image", WINDOW_AUTOSIZE );
imshow( "Display Image", image );
waitKey(0);
return 0;
}
@endcode
8. We are only missing one final step: To tell OpenCV where the OpenCV headers and libraries are.
For this, do the following:
- Go to **Project--\>Properties**
- In **C/C++ Build**, click on **Settings**. At the right, choose the **Tool Settings** Tab.
Here we will enter the headers and libraries info:
a. In **GCC C++ Compiler**, go to **Includes**. In **Include paths(-l)** you should
include the path of the folder where opencv was installed. In our example, this is
/usr/local/include/opencv.
![image](images/a9.png)
@note If you do not know where your opencv files are, open the **Terminal** and type:
@code{.bash}
pkg-config --cflags opencv
@endcode
For instance, that command gave me this output:
@code{.bash}
-I/usr/local/include/opencv -I/usr/local/include
@endcode
b. Now go to **GCC C++ Linker**,there you have to fill two spaces:
First in **Library search path (-L)** you have to write the path to where the opencv libraries
reside, in my case the path is: :
/usr/local/lib
Then in **Libraries(-l)** add the OpenCV libraries that you may need. Usually just the 3 first
on the list below are enough (for simple applications) . In my case, I am putting all of them
since I plan to use the whole bunch:
opencv_core opencv_imgproc opencv_highgui opencv_ml opencv_video opencv_features2d
opencv_calib3d opencv_objdetect opencv_contrib opencv_legacy opencv_flann
![image](images/a10.png)
If you don't know where your libraries are (or you are just psychotic and want to make sure
the path is fine), type in **Terminal**:
@code{.bash}
pkg-config --libs opencv
@endcode
My output (in case you want to check) was: .. code-block:: bash
-L/usr/local/lib -lopencv_core -lopencv_imgproc -lopencv_highgui -lopencv_ml -lopencv_video -lopencv_features2d -lopencv_calib3d -lopencv_objdetect -lopencv_contrib -lopencv_legacy -lopencv_flann
Now you are done. Click **OK**
- Your project should be ready to be built. For this, go to **Project-\>Build all**
In the Console you should get something like
![image](images/a12.png)
If you check in your folder, there should be an executable there.
Running the executable
----------------------
So, now we have an executable ready to run. If we were to use the Terminal, we would probably do
something like:
@code{.bash}
cd <DisplayImage_directory>
cd src
./DisplayImage ../images/HappyLittleFish.png
@endcode
Assuming that the image to use as the argument would be located in
\<DisplayImage_directory\>/images/HappyLittleFish.png. We can still do this, but let's do it from
Eclipse:
1. Go to **Run-\>Run Configurations**
2. Under C/C++ Application you will see the name of your executable + Debug (if not, click over
C/C++ Application a couple of times). Select the name (in this case **DisplayImage Debug**).
3. Now, in the right side of the window, choose the **Arguments** Tab. Write the path of the image
file we want to open (path relative to the workspace/DisplayImage folder). Let's use
**HappyLittleFish.png**:
![image](images/a14.png)
4. Click on the **Apply** button and then in Run. An OpenCV window should pop up with the fish
image (or whatever you used).
![image](images/a15.jpg)
5. Congratulations! You are ready to have fun with OpenCV using Eclipse.
### V2: Using CMake+OpenCV with Eclipse (plugin CDT)
Say you have or create a new file, *helloworld.cpp* in a directory called *foo*:
@code{.cpp}
#include <opencv2/opencv.hpp>
using namespace cv;
int main ( int argc, char **argv )
{
Mat img(480, 640, CV_8U);
putText(img, "Hello World!", Point( 200, 400 ), FONT_HERSHEY_SIMPLEX | FONT_ITALIC, 1.0, Scalar( 255, 255, 0 ));
imshow("My Window", img);
waitKey();
return 0;
}
@endcode
1. Create a build directory, say, under *foo*: mkdir /build. Then cd build.
2. Put a *CmakeLists.txt* file in build:
@code{.bash}
PROJECT( helloworld_proj )
FIND_PACKAGE( OpenCV REQUIRED )
ADD_EXECUTABLE( helloworld helloworld.cxx )
TARGET_LINK_LIBRARIES( helloworld \f${OpenCV_LIBS} )
@endcode
1. Run: cmake-gui .. and make sure you fill in where opencv was built.
2. Then click configure and then generate. If it's OK, **quit cmake-gui**
3. Run make -j4 *(the -j4 is optional, it just tells the compiler to build in 4 threads)*. Make
sure it builds.
4. Start eclipse . Put the workspace in some directory but **not** in foo or foo\\\\build
5. Right click in the Project Explorer section. Select Import And then open the C/C++ filter.
Choose *Existing Code* as a Makefile Project\`\`
6. Name your project, say *helloworld*. Browse to the Existing Code location foo\\\\build (where
you ran your cmake-gui from). Select *Linux GCC* in the *"Toolchain for Indexer Settings"* and
press *Finish*.
7. Right click in the Project Explorer section. Select Properties. Under C/C++ Build, set the
*build directory:* from something like \\f${workspace_loc:/helloworld} to
\\f${workspace_loc:/helloworld}/build since that's where you are building to.
a. You can also optionally modify the Build command: from make to something like
make VERBOSE=1 -j4 which tells the compiler to produce detailed symbol files for debugging and
also to compile in 4 parallel threads.
1. Done!

View File

@@ -0,0 +1,79 @@
Using OpenCV with gcc and CMake {#tutorial_linux_gcc_cmake}
===============================
@note We assume that you have successfully installed OpenCV in your workstation. .. container::
enumeratevisibleitemswithsquare
- The easiest way of using OpenCV in your code is to use [CMake](http://www.cmake.org/). A few
advantages (taken from the Wiki):
1. No need to change anything when porting between Linux and Windows
2. Can easily be combined with other tools by CMake( i.e. Qt, ITK and VTK )
- If you are not familiar with CMake, checkout the
[tutorial](http://www.cmake.org/cmake/help/cmake_tutorial.html) on its website.
Steps
-----
### Create a program using OpenCV
Let's use a simple program such as DisplayImage.cpp shown below.
@code{.cpp}
#include <stdio.h>
#include <opencv2/opencv.hpp>
using namespace cv;
int main(int argc, char** argv )
{
if ( argc != 2 )
{
printf("usage: DisplayImage.out <Image_Path>\n");
return -1;
}
Mat image;
image = imread( argv[1], 1 );
if ( !image.data )
{
printf("No image data \n");
return -1;
}
namedWindow("Display Image", WINDOW_AUTOSIZE );
imshow("Display Image", image);
waitKey(0);
return 0;
}
@endcode
### Create a CMake file
Now you have to create your CMakeLists.txt file. It should look like this:
@code{.cmake}
cmake_minimum_required(VERSION 2.8)
project( DisplayImage )
find_package( OpenCV REQUIRED )
include_directories( \f${OpenCV_INCLUDE_DIRS} )
add_executable( DisplayImage DisplayImage.cpp )
target_link_libraries( DisplayImage \f${OpenCV_LIBS} )
@endcode
### Generate the executable
This part is easy, just proceed as with any other project using CMake:
@code{.bash}
cd <DisplayImage_directory>
cmake .
make
@endcode
### Result
By now you should have an executable (called DisplayImage in this case). You just have to run it
giving an image location as an argument, i.e.:
@code{.bash}
./DisplayImage lena.jpg
@endcode
You should get a nice window as the one shown below:
![image](images/GCC_CMake_Example_Tutorial.jpg)

View File

@@ -0,0 +1,136 @@
Installation in Linux {#tutorial_linux_install}
=====================
These steps have been tested for Ubuntu 10.04 but should work with other distros as well.
Required Packages
-----------------
- GCC 4.4.x or later
- CMake 2.8.7 or higher
- Git
- GTK+2.x or higher, including headers (libgtk2.0-dev)
- pkg-config
- Python 2.6 or later and Numpy 1.5 or later with developer packages (python-dev, python-numpy)
- ffmpeg or libav development packages: libavcodec-dev, libavformat-dev, libswscale-dev
- [optional] libtbb2 libtbb-dev
- [optional] libdc1394 2.x
- [optional] libjpeg-dev, libpng-dev, libtiff-dev, libjasper-dev, libdc1394-22-dev
The packages can be installed using a terminal and the following commands or by using Synaptic
Manager:
@code{.bash}
[compiler] sudo apt-get install build-essential
[required] sudo apt-get install cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev
[optional] sudo apt-get install python-dev python-numpy libtbb2 libtbb-dev libjpeg-dev libpng-dev libtiff-dev libjasper-dev libdc1394-22-dev
@endcode
Getting OpenCV Source Code
--------------------------
You can use the latest stable OpenCV version or you can grab the latest snapshot from our [Git
repository](https://github.com/Itseez/opencv.git).
### Getting the Latest Stable OpenCV Version
- Go to our [downloads page](http://opencv.org/downloads.html).
- Download the source archive and unpack it.
### Getting the Cutting-edge OpenCV from the Git Repository
Launch Git client and clone [OpenCV repository](http://github.com/itseez/opencv). If you need
modules from [OpenCV contrib repository](http://github.com/itseez/opencv_contrib) then clone it too.
For example
@code{.bash}
cd ~/<my_working_directory>
git clone https://github.com/Itseez/opencv.git
git clone https://github.com/Itseez/opencv_contrib.git
@endcode
Building OpenCV from Source Using CMake
---------------------------------------
1. Create a temporary directory, which we denote as \<cmake_build_dir\>, where you want to put
the generated Makefiles, project files as well the object files and output binaries and enter
there.
For example
@code{.bash}
cd ~/opencv
mkdir build
cd build
@endcode
2. Configuring. Run cmake [\<some optional parameters\>] \<path to the OpenCV source directory\>
For example
@code{.bash}
cmake -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=/usr/local ..
@endcode
or cmake-gui
- set full path to OpenCV source code, e.g. /home/user/opencv
- set full path to \<cmake_build_dir\>, e.g. /home/user/opencv/build
- set optional parameters
- run: “Configure”
- run: “Generate”
3. Description of some parameters
- build type: CMAKE_BUILD_TYPE=Release\\Debug
- to build with modules from opencv_contrib set OPENCV_EXTRA_MODULES_PATH to \<path to
opencv_contrib/modules/\>
- set BUILD_DOCS for building documents
- set BUILD_EXAMPLES to build all examples
4. [optional] Building python. Set the following python parameters:
- PYTHON2(3)_EXECUTABLE = \<path to python\>
- PYTHON_INCLUDE_DIR = /usr/include/python\<version\>
- PYTHON_INCLUDE_DIR2 = /usr/include/x86_64-linux-gnu/python\<version\>
- PYTHON_LIBRARY = /usr/lib/x86_64-linux-gnu/libpython\<version\>.so
- PYTHON2(3)_NUMPY_INCLUDE_DIRS =
/usr/lib/python\<version\>/dist-packages/numpy/core/include/
5. [optional] Building java.
- Unset parameter: BUILD_SHARED_LIBS
- It is useful also to unset BUILD_EXAMPLES, BUILD_TESTS, BUILD_PERF_TESTS - as they all
will be statically linked with OpenCV and can take a lot of memory.
6. Build. From build directory execute make, recomend to do it in several threads
For example
@code{.bash}
make -j7 # runs 7 jobs in parallel
@endcode
7. [optional] Building documents. Enter \<cmake_build_dir/doc/\> and run make with target
"html_docs"
For example
@code{.bash}
cd ~/opencv/build/doc/
make -j7 html_docs
@endcode
8. To install libraries, from build directory execute
@code{.bash}
sudo make install
@endcode
9. [optional] Running tests
- Get the required test data from [OpenCV extra
repository](https://github.com/Itseez/opencv_extra).
For example
@code{.bash}
git clone https://github.com/Itseez/opencv_extra.git
@endcode
- set OPENCV_TEST_DATA_PATH environment variable to \<path to opencv_extra/testdata\>.
- execute tests from build directory.
For example
@code{.bash}
<cmake_build_dir>/bin/opencv_test_core
@endcode
@note
If the size of the created library is a critical issue (like in case of an Android build) you
can use the install/strip command to get the smallest size as possible. The *stripped* version
appears to be twice as small. However, we do not recommend using this unless those extra
megabytes do really matter.

View File

@@ -0,0 +1,106 @@
Load, Modify, and Save an Image {#tutorial_load_save_image}
===============================
@note
We assume that by now you know how to load an image using @ref cv::imread and to display it in a
window (using @ref cv::imshow ). Read the @ref Display_Image tutorial otherwise.
Goals
-----
In this tutorial you will learn how to:
- Load an image using @ref cv::imread
- Transform an image from BGR to Grayscale format by using @ref cv::cvtColor
- Save your transformed image in a file on disk (using @ref cv::imwrite )
Code
----
Here it is:
@code{.cpp}
#include <opencv2/opencv.hpp>
using namespace cv;
int main( int argc, char** argv )
{
char* imageName = argv[1];
Mat image;
image = imread( imageName, 1 );
if( argc != 2 || !image.data )
{
printf( " No image data \n " );
return -1;
}
Mat gray_image;
cvtColor( image, gray_image, COLOR_BGR2GRAY );
imwrite( "../../images/Gray_Image.jpg", gray_image );
namedWindow( imageName, WINDOW_AUTOSIZE );
namedWindow( "Gray image", WINDOW_AUTOSIZE );
imshow( imageName, image );
imshow( "Gray image", gray_image );
waitKey(0);
return 0;
}
@endcode
Explanation
-----------
1. We begin by loading an image using @ref cv::imread , located in the path given by *imageName*.
For this example, assume you are loading a RGB image.
2. Now we are going to convert our image from BGR to Grayscale format. OpenCV has a really nice
function to do this kind of transformations:
@code{.cpp}
cvtColor( image, gray_image, COLOR_BGR2GRAY );
@endcode
As you can see, @ref cv::cvtColor takes as arguments:
- a source image (*image*)
- a destination image (*gray_image*), in which we will save the converted image.
- an additional parameter that indicates what kind of transformation will be performed. In
this case we use **COLOR_BGR2GRAY** (because of @ref cv::imread has BGR default channel
order in case of color images).
3. So now we have our new *gray_image* and want to save it on disk (otherwise it will get lost
after the program ends). To save it, we will use a function analagous to @ref cv::imread : @ref
cv::imwrite
@code{.cpp}
imwrite( "../../images/Gray_Image.jpg", gray_image );
@endcode
Which will save our *gray_image* as *Gray_Image.jpg* in the folder *images* located two levels
up of my current location.
4. Finally, let's check out the images. We create two windows and use them to show the original
image as well as the new one:
@code{.cpp}
namedWindow( imageName, WINDOW_AUTOSIZE );
namedWindow( "Gray image", WINDOW_AUTOSIZE );
imshow( imageName, image );
imshow( "Gray image", gray_image );
@endcode
5. Add the *waitKey(0)* function call for the program to wait forever for an user key press.
Result
------
When you run your program you should get something like this:
![image](images/Load_Save_Image_Result_1.jpg)
And if you check in your folder (in my case *images*), you should have a newly .jpg file named
*Gray_Image.jpg*:
![image](images/Load_Save_Image_Result_2.jpg)
Congratulations, you are done with this tutorial!

View File

@@ -0,0 +1,145 @@
Introduction to OpenCV {#tutorial_table_of_content_introduction}
======================
Here you can read tutorials about how to set up your computer to work with the OpenCV library.
Additionally you can find very basic sample source code to introduce you to the world of the OpenCV.
- @subpage tutorial_linux_install
*Compatibility:* \> OpenCV 2.0
*Author:* Ana Huamán
We will learn how to setup OpenCV in your computer!
- @subpage tutorial_linux_gcc_cmake
*Compatibility:* \> OpenCV 2.0
*Author:* Ana Huamán
We will learn how to compile your first project using gcc and CMake
- @subpage tutorial_linux_eclipse
*Compatibility:* \> OpenCV 2.0
*Author:* Ana Huamán
We will learn how to compile your first project using the Eclipse environment
- @subpage tutorial_windows_install
*Compatibility:* \> OpenCV 2.0
*Author:* Bernát Gábor
You will learn how to setup OpenCV in your Windows Operating System!
- @subpage tutorial_windows_visual_studio_Opencv
*Compatibility:* \> OpenCV 2.0
*Author:* Bernát Gábor
You will learn what steps you need to perform in order to use the OpenCV library inside a new
Microsoft Visual Studio project.
- @subpage tutorial_windows_visual_studio_image_watch
*Compatibility:* \>= OpenCV 2.4
*Author:* Wolf Kienzle
You will learn how to visualize OpenCV matrices and images within Visual Studio 2012.
- @subpage tutorial_java_dev_intro
*Compatibility:* \> OpenCV 2.4.4
*Authors:* Eric Christiansen and Andrey Pavlenko
Explains how to build and run a simple desktop Java application using Eclipse, Ant or the
Simple Build Tool (SBT).
- @subpage tutorial_java_eclipse
*Compatibility:* \> OpenCV 2.4.4
*Author:* Barış Evrim Demiröz
A tutorial on how to use OpenCV Java with Eclipse.
- @subpage tutorial_clojure_dev_intro
*Compatibility:* \> OpenCV 2.4.4
*Author:* Mimmo Cosenza
A tutorial on how to interactively use OpenCV from the Clojure REPL.
- @subpage tutorial_android_dev_intro
*Compatibility:* \> OpenCV 2.4.2
*Author:* Vsevolod Glumov
Not a tutorial, but a guide introducing Android development basics and environment setup
- @subpage tutorial_O4A_SDK
*Compatibility:* \> OpenCV 2.4.2
*Author:* Vsevolod Glumov
OpenCV4Android SDK: general info, installation, running samples
- @subpage tutorial_dev_with_OCV_on_Android
*Compatibility:* \> OpenCV 2.4.3
*Author:* Vsevolod Glumov
Development with OpenCV4Android SDK
- @subpage tutorial_ios_install
*Compatibility:* \> OpenCV 2.4.2
*Author:* Artem Myagkov, Eduard Feicho
We will learn how to setup OpenCV for using it in iOS!
- @subpage tutorial_arm_crosscompile_with_cmake
*Compatibility:* \> OpenCV 2.4.4
*Author:* Alexander Smorkalov
We will learn how to setup OpenCV cross compilation environment for ARM Linux.
- @subpage tutorial_display_image
*Compatibility:* \> OpenCV 2.0
*Author:* Ana Huamán
We will learn how to display an image using OpenCV
- @subpage tutorial_load_save_image
*Compatibility:* \> OpenCV 2.0
*Author:* Ana Huamán
We will learn how to save an Image in OpenCV...plus a small conversion to grayscale
- @subpage tutorial_how_to_write_a_tutorial
*Compatibility:* \> OpenCV 1.0
*Author:* Bernát Gábor
If you already have a good grasp on using OpenCV and have made some projects that would be
perfect presenting an OpenCV feature not yet part of these tutorials, here it is what you
need to know.

View File

@@ -0,0 +1,363 @@
Installation in Windows {#tutorial_windows_install}
=======================
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](http://answers.opencv.org). We'll do our
best to help you out.
@note To use the OpenCV library you have two options: @ref Windows_Install_Prebuild or @ref
CppTutWindowsMakeOwn. 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. .. _Windows_Install_Prebuild:
Installation by Using the Pre-built Libraries
---------------------------------------------
1. Launch a web browser of choice and go to our [page on
Sourceforge](http://sourceforge.net/projects/opencvlibrary/files/opencv-win/).
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.
![image](images/OpenCV_Install_Directory.png)
5. To finalize the installation go to the @ref WindowsSetPathAndEnviromentVariable 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](https://www.youtube.com/watch?v=NnovZ1cTlMs) and [Part
2](https://www.youtube.com/watch?v=qGNWMcfWwPU), hosted on YouTube.
\htmlonly
<div align="center">
<iframe title="Install OpenCV by using its source files - Part 1" width="560" height="349" src="http://www.youtube.com/embed/NnovZ1cTlMs?rel=0&loop=1" frameborder="0" allowfullscreen align="middle"></iframe>
<iframe title="Install OpenCV by using its source files - Part 2" width="560" height="349" src="http://www.youtube.com/embed/qGNWMcfWwPU?rel=0&loop=1" frameborder="0" allowfullscreen align="middle"></iframe>
</div>
\endhtmlonly
**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](https://github.com/Itseez/opencv.git).
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](https://www.microsoft.com/visualstudio/en-us).
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](http://sourceforge.net/projects/opencvlibrary/files/opencv-win/)
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*.
- Numpy_ is a scientific computing package for Python. Required for the *Python interface*.
- Intel |copy| 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.
- Intel |copy| 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.
- Intel |copy| IPP Asynchronous C/C++_ is currently focused delivering Intel |copy| Graphics
support for advanced image processing and computer vision functions.
- 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.
- Eigen_ is a C++ template library for linear algebra.
- 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.
- Miktex_ is the best [TEX](https://secure.wikimedia.org/wikipedia/en/wiki/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 @ref How to Install Sphinx \<HereInstallSphinx\> 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](http://code.google.com/p/msysgit/downloads/list). 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.
a) 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`).
b) 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.
a) 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](http://pypi.python.org/pypi/setuptools#downloads). Download and install
again.
b) 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 *sphinx* argument.
![image](images/cmsdstartwindows.jpg)
![image](images/Sphinx_Install.png)
@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](http://jinja.pocoo.org/docs/) and
[Pygments](http://pygments.org/).
1) The easiest way to install Numpy_ is to just download its binaries from the [sourceforga
page](http://sourceforge.net/projects/numpy/files/NumPy/). Make sure your download and install
exactly the binary for your python version (so for version `2.7`).
2) 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 *Yes* option, as you can
see on the image below. Again this will take quite some time so be patient.
![image](images/MiktexInstall.png)
3) For the Intel |copy| Threading Building Blocks (*TBB*)_ download the source files and extract
it inside a directory on your system. For example let there be `D:/OpenCV/dep`. For installing
the Intel |copy| Integrated Performance Primitives (*IPP*)_ the story is the same. For
exctracting the archives I recommend using the [7-Zip](http://www.7-zip.org/) application.
![image](images/IntelTBB.png)
4) For the Intel |copy| IPP Asynchronous C/C++_ download the source files and set environment
variable **IPP_ASYNC_ROOT**. It should point to
`<your Program Files(x86) directory>/Intel/IPP Preview */ipp directory`. Here \* denotes the
particular preview name.
5) In case of the Eigen_ library it is again a case of download and extract to the
`D:/OpenCV/dep` directory.
6) Same as above with OpenEXR_.
7) For the OpenNI Framework_ you need to install both the [development
build](http://www.openni.org/downloadfiles/opennimodules/openni-binaries/21-stable) and the
[PrimeSensor
Module](http://www.openni.org/downloadfiles/opennimodules/openni-compliant-hardware-binaries/32-stable).
8) 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.
9) 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 the [Qt
Downloads](http://qt.nokia.com/downloads) page. Download the source files (not the
installers!!!):
![image](images/qtDownloadThisPackage.png)
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)).
![image](images/visualstudiocommandprompt.jpg)
Now navigate to the extracted folder and enter inside it by using this console window. You
should have a folder containing files like *Install*, *Make* and so on. Use the *dir* command
to list files inside your current directory. Once arrived at this directory enter the
following command:
@code{.bash}
configure.exe -release -no-webkit -no-phonon -no-phonon-backend -no-script -no-scripttools
-no-qt3support -no-multimedia -no-ltcg
@endcode
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):
@code{.bash}
nmake
@endcode
After this set the Qt enviroment variables using the following command on Windows 7:
@code{.bash}
setx -m QTDIR D:/OpenCV/dep/qt/qt-everywhere-opensource-src-4.7.3
@endcode
Also, add the built binary files path to the system path by using the |PathEditor|_. 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.
1. 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).
![image](images/CMakeSelectBin.jpg)
Press 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.
![image](images/CMake_Configure_Windows.jpg)
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:
![image](images/CMakeBuildWithWindowsGUI.jpg)
Select 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:
![image](images/CMakePackageNotFoundWindows.jpg)
![image](images/CMakeOutputPackageNotFound.jpg)
For 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.
![image](images/CMakeBuildOptionsOpenCV.jpg)
Furthermore, 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 use OpenCV from the
Python language.
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.
![image](images/ChangeBuildVisualStudio.jpg)
In the end you can observe the built binary files inside the bin directory:
![image](images/OpenCVBuildResultWindows.jpg)
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.
![image](images/WindowsBuildDoc.png)
To 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.
![image](images/WindowsBuildInstall.png)
This 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 *Debug* versions.
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 @ref cv::Q&A
forum . If everything is okay the *contours.exe* output should resemble the following image (if
built with Qt support):
![image](images/WindowsQtContoursOutput.png)
@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 because 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 the operating system 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 |PathEditor|_ and add the
following new entry (right click in the application to bring up the menu):
%OPENCV_DIR%\bin
![image](images/PathEditorOpenCVInsertNew.png)
![image](images/PathEditorOpenCVSetPath.png)
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.
Now you can continue reading the tutorials with the @ref Windows_Visual_Studio_How_To section.
There you will find out how to use the OpenCV library in your own projects with the help of the
Microsoft Visual Studio IDE.

View File

@@ -0,0 +1,237 @@
How to build applications with OpenCV inside the *Microsoft Visual Studio* {#tutorial_windows_visual_studio_Opencv}
==========================================================================
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 @ref Windows_Installation 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 @ref described here
\<WindowsSetPathAndEnviromentVariable\>.
![image](images/OpenCV_Install_Directory.jpg)
The OpenCV libraries, distributed by us, on the Microsoft Windows operating system are in a
**D**ynamic **L**inked **L**ibraries (*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 @ref Windows_Installation 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.
![image](images/NewProjectVisualStudio.jpg)
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 with
View --\> Property Pages. Expand it and you can see the existing rule packages (called *Proporty
Sheets*).
![image](images/PropertyPageExample.jpg)
The 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:
![image](images/AddNewPropertySheet.jpg)
Use 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.
@code{.bash}
\f$(OPENCV_DIR)\..\..\include
@endcode
![image](images/PropertySheetOpenCVInclude.jpg)
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 @ref previous tutorial \<WindowsSetPathAndEnviromentVariable\>.
Next go to the Linker --\> General and under the *"Additional Library Directories"* add the libs
directory:
@code{.bash}
\f$(OPENCV_DIR)\lib
@endcode
![image](images/PropertySheetOpenCVLib.jpg)
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:
![image](images/PropertySheetOpenCVLibrariesDebugSmple.jpg)
![image](images/PropertySheetOpenCVLibrariesDebug.jpg)
The names of the libraries are as follow:
@code{.bash}
opencv_(The Name of the module)(The version Number of the library you use)d.lib
@endcode
A full list, for the latest version would contain:
@code{.bash}
opencv_calib3d300d.lib
opencv_core300d.lib
opencv_features2d300d.lib
opencv_flann300d.lib
opencv_highgui300d.lib
opencv_imgcodecs300d.lib
opencv_imgproc300d.lib
opencv_ml300d.lib
opencv_objdetect300d.lib
opencv_photo300d.lib
opencv_shape300d.lib
opencv_stitching300d.lib
opencv_superres300d.lib
opencv_ts300d.lib
opencv_video300d.lib
opencv_videoio300d.lib
opencv_videostab300d.lib
@endcode
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.
![image](images/PropertySheetOpenCVLibrariesRelease.jpg)
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*.
![image](images/PropertySheetInsideFolder.jpg)
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.
![image](images/PropertyPageAddExisting.jpg)
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.
![image](images/VCDirectories2008.jpg)
In Visual Studio 2010 this has been moved to a global property sheet which is automatically added to
every project you create:
![image](images/VCDirectories2010.jpg)
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
](samples/cpp/tutorial_code/introduction/windows_visual_studio_Opencv/introduction_windows_vs.cpp)
or get it from the sample code folder of the OpenCV sources. Add this to your project and build it.
Here's its content:
@includelineno
cpp/tutorial_code/introduction/windows_visual_studio_Opencv/introduction_windows_vs.cpp
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](samples/data/opencv-logo.png). 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 á:
![image](images/SuccessVisualStudioWindows.jpg)
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:
@code{.bash}
D:
CD OpenCV\MySolutionName\Release
MySolutionName.exe exampleImage.jpg
@endcode
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:
![image](images/VisualStudioCommandLineArguments.jpg)
Specify here the name of the inputs and while you start your application from the Visual Studio
enviroment you have automatic argument passing. In the next introductionary tutorial you'll see an
in-depth explanation of the upper source code: @ref Display_Image.

View File

@@ -0,0 +1,181 @@
Image Watch: viewing in-memory images in the Visual Studio debugger {#tutorial_windows_visual_studio_image_watch}
===================================================================
Image Watch is a plug-in for Microsoft Visual Studio that lets you to visualize in-memory images
(*cv::Mat* or *IplImage_* objects, for example) while debugging an application. This can be helpful
for tracking down bugs, or for simply understanding what a given piece of code is doing.
Prerequisites
-------------
This tutorial assumes that you have the following available:
1. Visual Studio 2012 Professional (or better) with Update 1 installed. Update 1 can be downloaded
[here](http://www.microsoft.com/en-us/download/details.aspx?id=35774).
2. An OpenCV installation on your Windows machine (Tutorial: @ref Windows_Installation).
3. Ability to create and build OpenCV projects in Visual Studio (Tutorial: @ref
Windows_Visual_Studio_How_To).
Installation
------------
[Download](http://go.microsoft.com/fwlink/?LinkId=285460) the Image Watch installer. The installer
comes in a single file with extension .vsix (*Visual Studio Extension*). To launch it, simply
double-click on the .vsix file in Windows Explorer. When the installer has finished, make sure to
restart Visual Studio to complete the installation.
Example
-------
Image Watch works with any existing project that uses OpenCV image objects (for example, *cv::Mat*).
In this example, we use a minimal test program that loads an image from a file and runs an edge
detector. To build the program, create a console application project in Visual Studio, name it
"image-watch-demo", and insert the source code below.
@code{.cpp}
// Test application for the Visual Studio Image Watch Debugger extension
#include <iostream> // std::cout
#include <opencv2/core/core.hpp> // cv::Mat
#include <opencv2/imgcodecs/imgcodecs.hpp> // cv::imread()
#include <opencv2/imgproc/imgproc.hpp> // cv::Canny()
using namespace std;
using namespace cv;
void help()
{
cout
<< "----------------------------------------------------" << endl
<< "This is a test program for the Image Watch Debugger " << endl
<< "plug-in for Visual Studio. The program loads an " << endl
<< "image from a file and runs the Canny edge detector. " << endl
<< "No output is displayed or written to disk."
<< endl
<< "Usage:" << endl
<< "image-watch-demo inputimage" << endl
<< "----------------------------------------------------" << endl
<< endl;
}
int main(int argc, char *argv[])
{
help();
if (argc != 2)
{
cout << "Wrong number of parameters" << endl;
return -1;
}
cout << "Loading input image: " << argv[1] << endl;
Mat input;
input = imread(argv[1], IMREAD_COLOR);
cout << "Detecting edges in input image" << endl;
Mat edges;
Canny(input, edges, 10, 100);
return 0;
}
@endcode
Make sure your active solution configuration (Build --\> Configuration Manager) is set to a debug
build (usually called "Debug"). This should disable compiler optimizations so that viewing variables
in the debugger can work reliably.
Build your solution (Build --\> Build Solution, or press *F7*).
Before continuing, do not forget to add the command line argument of your input image to your
project (Right click on project --\> Properties --\> Configuration Properties --\> Debugging and
then set the field Command Arguments with the location of the image).
Now set a breakpoint on the source line that says
@code{.cpp}
Mat edges;
@endcode
To set the breakpoint, right-click on the source line and select Breakpoints --\> Insert Breakpoint
from the context menu.
Launch the program in the debugger (Debug --\> Start Debugging, or hit *F5*). When the breakpoint is
hit, the program is paused and Visual Studio displays a yellow instruction pointer at the
breakpoint:
![image](images/breakpoint.png)
Now you can inspect the state of you program. For example, you can bring up the *Locals* window
(Debug --\> Windows --\> Locals), which will show the names and values of the variables in the
current scope:
![image](images/vs_locals.png)
Note that the built-in *Locals* window will display text only. This is where the Image Watch plug-in
comes in. Image Watch is like another *Locals* window, but with an image viewer built into it. To
bring up Image Watch, select View --\> Other Windows --\> Image Watch. Like Visual Studio's *Locals*
window, Image Watch can dock to the Visual Studio IDE. Also, Visual Studio will remember whether you
had Image Watch open, and where it was located between debugging sessions. This means you only have
to do this once--the next time you start debugging, Image Watch will be back where you left it.
Here's what the docked Image Watch window looks like at our breakpoint:
![image](images/toolwindow.jpg)
The radio button at the top left (*Locals/Watch*) selects what is shown in the *Image List* below:
*Locals* lists all OpenCV image objects in the current scope (this list is automatically populated).
*Watch* shows image expressions that have been pinned for continuous inspection (not described here,
see [Image Watch documentation](http://go.microsoft.com/fwlink/?LinkId=285461) for details). The
image list shows basic information such as width, height, number of channels, and, if available, a
thumbnail. In our example, the image list contains our two local image variables, *input* and
*edges*.
If an image has a thumbnail, left-clicking on that image will select it for detailed viewing in the
*Image Viewer* on the right. The viewer lets you pan (drag mouse) and zoom (mouse wheel). It also
displays the pixel coordinate and value at the current mouse position.
![image](images/viewer.jpg)
Note that the second image in the list, *edges*, is shown as "invalid". This indicates that some
data members of this image object have corrupt or invalid values (for example, a negative image
width). This is expected at this point in the program, since the C++ constructor for *edges* has not
run yet, and so its members have undefined values (in debug mode they are usually filled with "0xCD"
bytes).
From here you can single-step through your code (Debug-\>Step Over, or press *F10*) and watch the
pixels change: if you step once, over the *Mat edges;* statement, the *edges* image will change from
"invalid" to "empty", which means that it is now in a valid state (default constructed), even though
it has not been initialized yet (using *cv::Mat::create()*, for example). If you make one more step
over the *cv::Canny()* call, you will see a thumbnail of the edge image appear in the image list.
Now assume you want to do a visual sanity check of the *cv::Canny()* implementation. Bring the
*edges* image into the viewer by selecting it in the *Image List* and zoom into a region with a
clearly defined edge:
![image](images/edges_zoom.png)
Right-click on the *Image Viewer* to bring up the view context menu and enable Link Views (a check
box next to the menu item indicates whether the option is enabled).
![image](images/viewer_context_menu.png)
The Link Views feature keeps the view region fixed when flipping between images of the same size. To
see how this works, select the input image from the image list--you should now see the corresponding
zoomed-in region in the input image:
![image](images/input_zoom.png)
You may also switch back and forth between viewing input and edges with your up/down cursor keys.
That way you can easily verify that the detected edges line up nicely with the data in the input
image.
More ...
--------
Image watch has a number of more advanced features, such as
1. pinning images to a *Watch* list for inspection across scopes or between debugging sessions
2. clamping, thresholding, or diff'ing images directly inside the Watch window
3. comparing an in-memory image against a reference image from a file
Please refer to the online [Image Watch
Documentation](http://go.microsoft.com/fwlink/?LinkId=285461) for details--you also can get to the
documentation page by clicking on the *Help* link in the Image Watch window:
![image](images/help_button.jpg)