init - 初始化项目

This commit is contained in:
Lee Nony
2022-05-06 01:58:53 +08:00
commit 90a5cc7cb6
6772 changed files with 2837787 additions and 0 deletions

View File

@@ -0,0 +1,255 @@
OpenCV4Android SDK {#tutorial_O4A_SDK}
==================
@prev_tutorial{tutorial_android_dev_intro}
@next_tutorial{tutorial_dev_with_OCV_on_Android}
| | |
| -: | :- |
| Original author | Vsevolod Glumov |
| Compatibility | OpenCV >= 3.0 |
@warning
This tutorial is deprecated.
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 tutorial_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](https://forum.opencv.org). We'll do our best to help you out.
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 `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/master>. 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;
Manual OpenCV4Android SDK setup
-------------------------------
### Get the OpenCV4Android SDK
-# Go to the [OpenCV download page on
SourceForge](http://sourceforge.net/projects/opencvlibrary/files/) and download
the latest available version. This tutorial is based on this package: [OpenCV-2.4.9-android-sdk.zip](http://sourceforge.net/projects/opencvlibrary/files/opencv-android/2.4.9/OpenCV-2.4.9-android-sdk.zip/download).
-# 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):
![](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
-# 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:
![](images/eclipse_1_choose_workspace.png)
-# 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:
- Right click on the Package Explorer window and choose Import... option from the context
menu:
![](images/eclipse_5_import_command.png)
- In the main panel select General --\> Existing Projects into Workspace and press Next
button:
![](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:
![](images/eclipse_7_select_projects.png)
- Click Finish button to complete the import operation.
@note OpenCV samples are indeed **dependent** on OpenCV library project so don't forget to import it to your workspace as well.
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.
![](images/eclipse_cdt_cfg4.png)
Once Eclipse completes build you will have the clean workspace without any build errors:
![](images/eclipse_10_crystal_clean.png)
@anchor tutorial_O4A_SDK_samples
### 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 tutorial_android_dev_intro.
**warning**
Please consider that some samples use Android Java Camera API, which is accessible with an AVD.
@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:
![](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:
![](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 `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+.
@note
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 available devices.
Click Edit in the context menu of the selected device. In the window, which then pop-ups, find
the CPU field.
@note
You may also see section `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.
![](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 tutorial_dev_with_OCV_on_Android tutorial.

View File

@@ -0,0 +1,501 @@
Introduction into Android Development {#tutorial_android_dev_intro}
=====================================
@prev_tutorial{tutorial_clojure_dev_intro}
@next_tutorial{tutorial_O4A_SDK}
| | |
| -: | :- |
| Original author | Vsevolod Glumov |
| Compatibility | OpenCV >= 3.0 |
@warning
This tutorial is deprecated.
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](https://forum.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:
-# [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.
-# [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.
-# [Android
Activity](http://developer.android.com/training/basics/activity-lifecycle/starting.html) and its
lifecycle, that is an essential Android API class.
-# OpenCV development will certainly require some knowledge of the [Android
Camera](http://developer.android.com/guide/topics/media/camera.html) specifics.
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:
-# **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
-# **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
-# **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.
![](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.
-# **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/).
-# **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:
-# Start Eclipse, then select Help --\> Install New Software...
-# Click Add (in the top-right corner).
-# 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/>
-# 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).
-# In the Available Software dialog, select the checkbox next to Developer Tools and click Next.
-# 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.
![](images/eclipse_inst_adt.png)
-# 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.
-# 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++:
-# **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.
@anchor tutorial_android_dev_intro_ndk
Building application native part from command line
--------------------------------------------------
Here is the standard way to compile C++ part of an Android application:
**warning**
We strongly recommend 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.
-# Open console and go to the root folder of an Android application
@code{.bash}
cd <root folder of the project>/
@endcode
-# 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.
![](images/ndk_build.png)
-# 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
@anchor tutorial_android_dev_intro_eclipse
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.
-# 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.
-# Open Eclipse and load the Android app project to configure.
-# Add C/C++ Nature to the project via Eclipse menu
New -\> Other -\> C/C++ -\> Convert to a C/C++ Project.
![](images/eclipse_cdt_cfg1.png)
And:
![](images/eclipse_cdt_cfg2.png)
-# Select the project(s) to convert. Specify "Project type" = Makefile project, "Toolchains" =
Other Toolchain.
![](images/eclipse_cdt_cfg3.png)
-# Open Project Properties -\> C/C++ Build, uncheck Use default build command, replace "Build
command" text from "make" to
"${NDKROOT}/ndk-build.cmd" on Windows,
"${NDKROOT}/ndk-build" on Linux and MacOS.
![](images/eclipse_cdt_cfg4.png)
-# Go to Behaviour tab and change "Workbench build type" section like shown below:
![](images/eclipse_cdt_cfg5.png)
-# Press OK and make sure the ndk-build is successfully invoked when building the project.
![](images/eclipse_cdt_cfg6.png)
-# 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.
![](images/eclipse_cdt_cfg7.png)
-# Open Project Properties -\> C/C++ General -\> Paths and Symbols and add the following
**Include** paths for **C++**:
@code
# for NDK r8 and prior:
${NDKROOT}/platforms/android-9/arch-arm/usr/include
${NDKROOT}/sources/cxx-stl/gnu-libstdc++/include
${NDKROOT}/sources/cxx-stl/gnu-libstdc++/libs/armeabi-v7a/include
${ProjDirPath}/../../sdk/native/jni/include
# for NDK r8b and later:
${NDKROOT}/platforms/android-9/arch-arm/usr/include
${NDKROOT}/sources/cxx-stl/gnu-libstdc++/4.6/include
${NDKROOT}/sources/cxx-stl/gnu-libstdc++/4.6/libs/armeabi-v7a/include
${ProjDirPath}/../../sdk/native/jni/include
@endcode
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.
![](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.
-# Assuming you already have *Android SDK* and *Eclipse IDE* installed, in Eclipse go
Window -\> AVD Manager.
-# Press the New button in AVD Manager window.
-# 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.
![](images/AVD_create.png)
-# When you click the Create AVD button, your new AVD will be available in AVD Manager.
-# 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.
-# 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
-# Enable USB debugging on the Android device (via Settings menu).
-# Attach the Android device to your PC with a USB cable.
-# Go to Start Menu and **right-click** on Computer. Select Manage in the context menu. You may be
asked for Administrative permissions.
-# 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.
![](images/usb_device_connect_01.png)
-# 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.
![](images/usb_device_connect_05.png)
-# Select Browse computer for driver software.
![](images/usb_device_connect_06.png)
-# Specify the path to `<Android SDK folder>/extras/google/usb_driver/` folder.
![](images/usb_device_connect_07.png)
-# If you get the prompt to install unverified drivers and report about success - you've finished
with USB driver installation.
![](images/usb_device_connect_08.png)
![](images/usb_device_connect_09.png)
-# Otherwise (getting the failure like shown below) follow the next steps.
![](images/usb_device_connect_12.png)
-# Again **right-click** on the unknown device, select Properties --\> Details --\> Hardware Ids
and copy the line like `USB\VID_XXXX&PID_XXXX&MI_XX`.
![](images/usb_device_connect_02.png)
-# 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.
![](images/usb_device_connect_03.png)
-# There should be a record like existing ones for your device and you need to add one manually.
![](images/usb_device_connect_04.png)
-# Save the `android_winusb.inf` file and try to install the USB driver again.
![](images/usb_device_connect_05.png)
![](images/usb_device_connect_06.png)
![](images/usb_device_connect_07.png)
-# This time installation should go successfully.
![](images/usb_device_connect_08.png)
![](images/usb_device_connect_09.png)
-# And an unknown device is now recognized as an Android phone.
![](images/usb_device_connect_10.png)
-# Successful device USB connection can be verified in console via adb devices command.
![](images/usb_device_connect_11.png)
-# 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:
![](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 tutorial_O4A_SDK tutorial.

View File

@@ -0,0 +1,406 @@
Use OpenCL in Android camera preview based CV application {#tutorial_android_ocl_intro}
=====================================
@prev_tutorial{tutorial_dev_with_OCV_on_Android}
@next_tutorial{tutorial_macos_install}
| | |
| -: | :- |
| Original author | Andrey Pavlenko |
| Compatibility | OpenCV >= 3.0 |
@warning
This tutorial is deprecated.
This guide was designed to help you in use of [OpenCL &trade;](https://www.khronos.org/opencl/) in Android camera preview based CV application.
It was written for [Eclipse-based ADT tools](http://developer.android.com/tools/help/adt.html)
(deprecated by Google now), but it easily can be reproduced with [Android Studio](http://developer.android.com/tools/studio/index.html).
This tutorial assumes you have the following installed and configured:
- JDK
- Android SDK and NDK
- Eclipse IDE with ADT and CDT plugins
It also assumes that you are familiar with Android Java and JNI programming basics.
If you need help with anything of the above, you may refer to our @ref tutorial_android_dev_intro guide.
This tutorial also assumes you have an Android operated device with OpenCL enabled.
The related source code is located within OpenCV samples at
[opencv/samples/android/tutorial-4-opencl](https://github.com/opencv/opencv/tree/master/samples/android/tutorial-4-opencl/) directory.
Preface
-------
Using [GPGPU](https://en.wikipedia.org/wiki/General-purpose_computing_on_graphics_processing_units)
via OpenCL for applications performance enhancements is quite a modern trend now.
Some CV algo-s (e.g. image filtering) run much faster on a GPU than on a CPU.
Recently it has become possible on Android OS.
The most popular CV application scenario for an Android operated device is starting camera in preview mode, applying some CV algo to every frame
and displaying the preview frames modified by that CV algo.
Let's consider how we can use OpenCL in this scenario. In particular let's try two ways: direct calls to OpenCL API and recently introduced OpenCV T-API
(aka [Transparent API](https://docs.google.com/presentation/d/1qoa29N_B-s297-fp0-b3rBirvpzJQp8dCtllLQ4DVCY/present)) - implicit OpenCL accelerations of some OpenCV algo-s.
Application structure
---------------------
Starting Android API level 11 (Android 3.0) [Camera API](http://developer.android.com/reference/android/hardware/Camera.html)
allows use of OpenGL texture as a target for preview frames.
Android API level 21 brings a new [Camera2 API](http://developer.android.com/reference/android/hardware/camera2/package-summary.html)
that provides much more control over the camera settings and usage modes,
it allows several targets for preview frames and OpenGL texture in particular.
Having a preview frame in an OpenGL texture is a good deal for using OpenCL because there is an
[OpenGL-OpenCL Interoperability API (cl_khr_gl_sharing)](https://www.khronos.org/registry/cl/sdk/1.2/docs/man/xhtml/cl_khr_gl_sharing.html),
allowing sharing OpenGL texture data with OpenCL functions without copying (with some restrictions of course).
Let's create a base for our application that just configures Android camera to send preview frames to OpenGL texture and displays these frames
on display without any processing.
A minimal `Activity` class for that purposes looks like following:
@code{.java}
public class Tutorial4Activity extends Activity {
private MyGLSurfaceView mView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
mView = new MyGLSurfaceView(this);
setContentView(mView);
}
@Override
protected void onPause() {
mView.onPause();
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
mView.onResume();
}
}
@endcode
And a minimal `View` class respectively:
@code{.java}
public class MyGLSurfaceView extends GLSurfaceView {
MyGLRendererBase mRenderer;
public MyGLSurfaceView(Context context) {
super(context);
if(android.os.Build.VERSION.SDK_INT >= 21)
mRenderer = new Camera2Renderer(this);
else
mRenderer = new CameraRenderer(this);
setEGLContextClientVersion(2);
setRenderer(mRenderer);
setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
super.surfaceCreated(holder);
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
super.surfaceDestroyed(holder);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
super.surfaceChanged(holder, format, w, h);
}
@Override
public void onResume() {
super.onResume();
mRenderer.onResume();
}
@Override
public void onPause() {
mRenderer.onPause();
super.onPause();
}
}
@endcode
__Note__: we use two renderer classes: one for legacy [Camera](http://developer.android.com/reference/android/hardware/Camera.html) API
and another for modern [Camera2](http://developer.android.com/reference/android/hardware/camera2/package-summary.html).
A minimal `Renderer` class can be implemented in Java (OpenGL ES 2.0 [available](http://developer.android.com/reference/android/opengl/GLES20.html) in Java),
but since we are going to modify the preview texture with OpenCL let's move OpenGL stuff to JNI.
Here is a simple Java wrapper for our JNI stuff:
@code{.java}
public class NativeGLRenderer {
static
{
System.loadLibrary("opencv_java4"); // comment this when using OpenCV Manager
System.loadLibrary("JNIrender");
}
public static native int initGL();
public static native void closeGL();
public static native void drawFrame();
public static native void changeSize(int width, int height);
}
@endcode
Since `Camera` and `Camera2` APIs differ significantly in camera setup and control, let's create a base class for the two corresponding renderers:
@code{.java}
public abstract class MyGLRendererBase implements GLSurfaceView.Renderer, SurfaceTexture.OnFrameAvailableListener {
protected final String LOGTAG = "MyGLRendererBase";
protected SurfaceTexture mSTex;
protected MyGLSurfaceView mView;
protected boolean mGLInit = false;
protected boolean mTexUpdate = false;
MyGLRendererBase(MyGLSurfaceView view) {
mView = view;
}
protected abstract void openCamera();
protected abstract void closeCamera();
protected abstract void setCameraPreviewSize(int width, int height);
public void onResume() {
Log.i(LOGTAG, "onResume");
}
public void onPause() {
Log.i(LOGTAG, "onPause");
mGLInit = false;
mTexUpdate = false;
closeCamera();
if(mSTex != null) {
mSTex.release();
mSTex = null;
NativeGLRenderer.closeGL();
}
}
@Override
public synchronized void onFrameAvailable(SurfaceTexture surfaceTexture) {
//Log.i(LOGTAG, "onFrameAvailable");
mTexUpdate = true;
mView.requestRender();
}
@Override
public void onDrawFrame(GL10 gl) {
//Log.i(LOGTAG, "onDrawFrame");
if (!mGLInit)
return;
synchronized (this) {
if (mTexUpdate) {
mSTex.updateTexImage();
mTexUpdate = false;
}
}
NativeGLRenderer.drawFrame();
}
@Override
public void onSurfaceChanged(GL10 gl, int surfaceWidth, int surfaceHeight) {
Log.i(LOGTAG, "onSurfaceChanged("+surfaceWidth+"x"+surfaceHeight+")");
NativeGLRenderer.changeSize(surfaceWidth, surfaceHeight);
setCameraPreviewSize(surfaceWidth, surfaceHeight);
}
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
Log.i(LOGTAG, "onSurfaceCreated");
String strGLVersion = GLES20.glGetString(GLES20.GL_VERSION);
if (strGLVersion != null)
Log.i(LOGTAG, "OpenGL ES version: " + strGLVersion);
int hTex = NativeGLRenderer.initGL();
mSTex = new SurfaceTexture(hTex);
mSTex.setOnFrameAvailableListener(this);
openCamera();
mGLInit = true;
}
}
@endcode
As you can see, inheritors for `Camera` and `Camera2` APIs should implement the following abstract methods:
@code{.java}
protected abstract void openCamera();
protected abstract void closeCamera();
protected abstract void setCameraPreviewSize(int width, int height);
@endcode
Let's leave the details of their implementation beyond of this tutorial, please refer the
[source code](https://github.com/opencv/opencv/tree/master/samples/android/tutorial-4-opencl/) to see them.
Preview Frames modification
---------------------------
The details OpenGL ES 2.0 initialization are also quite straightforward and noisy to be quoted here,
but the important point here is that the OpeGL texture to be the target for camera preview should be of type `GL_TEXTURE_EXTERNAL_OES`
(not `GL_TEXTURE_2D`), internally it keeps picture data in _YUV_ format.
That makes unable sharing it via CL-GL interop (`cl_khr_gl_sharing`) and accessing its pixel data via C/C++ code.
To overcome this restriction we have to perform an OpenGL rendering from this texture to another regular `GL_TEXTURE_2D` one
using _FrameBuffer Object_ (aka FBO).
### C/C++ code
After that we can read (_copy_) pixel data from C/C++ via `glReadPixels()` and write them back to texture after modification via `glTexSubImage2D()`.
### Direct OpenCL calls
Also that `GL_TEXTURE_2D` texture can be shared with OpenCL without copying, but we have to create OpenCL context with special way for that:
@code{.cpp}
void initCL()
{
EGLDisplay mEglDisplay = eglGetCurrentDisplay();
if (mEglDisplay == EGL_NO_DISPLAY)
LOGE("initCL: eglGetCurrentDisplay() returned 'EGL_NO_DISPLAY', error = %x", eglGetError());
EGLContext mEglContext = eglGetCurrentContext();
if (mEglContext == EGL_NO_CONTEXT)
LOGE("initCL: eglGetCurrentContext() returned 'EGL_NO_CONTEXT', error = %x", eglGetError());
cl_context_properties props[] =
{ CL_GL_CONTEXT_KHR, (cl_context_properties) mEglContext,
CL_EGL_DISPLAY_KHR, (cl_context_properties) mEglDisplay,
CL_CONTEXT_PLATFORM, 0,
0 };
try
{
cl::Platform p = cl::Platform::getDefault();
std::string ext = p.getInfo<CL_PLATFORM_EXTENSIONS>();
if(ext.find("cl_khr_gl_sharing") == std::string::npos)
LOGE("Warning: CL-GL sharing isn't supported by PLATFORM");
props[5] = (cl_context_properties) p();
theContext = cl::Context(CL_DEVICE_TYPE_GPU, props);
std::vector<cl::Device> devs = theContext.getInfo<CL_CONTEXT_DEVICES>();
LOGD("Context returned %d devices, taking the 1st one", devs.size());
ext = devs[0].getInfo<CL_DEVICE_EXTENSIONS>();
if(ext.find("cl_khr_gl_sharing") == std::string::npos)
LOGE("Warning: CL-GL sharing isn't supported by DEVICE");
theQueue = cl::CommandQueue(theContext, devs[0]);
// ...
}
catch(cl::Error& e)
{
LOGE("cl::Error: %s (%d)", e.what(), e.err());
}
catch(std::exception& e)
{
LOGE("std::exception: %s", e.what());
}
catch(...)
{
LOGE( "OpenCL info: unknown error while initializing OpenCL stuff" );
}
LOGD("initCL completed");
}
@endcode
@note To build this JNI code you need __OpenCL 1.2__ headers from [Khronos web site](https://www.khronos.org/registry/cl/api/1.2/) and
the __libOpenCL.so__ downloaded from the device you'll run the application.
Then the texture can be wrapped by a `cl::ImageGL` object and processed via OpenCL calls:
@code{.cpp}
cl::ImageGL imgIn (theContext, CL_MEM_READ_ONLY, GL_TEXTURE_2D, 0, texIn);
cl::ImageGL imgOut(theContext, CL_MEM_WRITE_ONLY, GL_TEXTURE_2D, 0, texOut);
std::vector < cl::Memory > images;
images.push_back(imgIn);
images.push_back(imgOut);
theQueue.enqueueAcquireGLObjects(&images);
theQueue.finish();
cl::Kernel Laplacian = ...
Laplacian.setArg(0, imgIn);
Laplacian.setArg(1, imgOut);
theQueue.finish();
theQueue.enqueueNDRangeKernel(Laplacian, cl::NullRange, cl::NDRange(w, h), cl::NullRange);
theQueue.finish();
theQueue.enqueueReleaseGLObjects(&images);
theQueue.finish();
@endcode
### OpenCV T-API
But instead of writing OpenCL code by yourselves you may want to use __OpenCV T-API__ that calls OpenCL implicitly.
All that you need is to pass the created OpenCL context to OpenCV (via `cv::ocl::attachContext()`) and somehow wrap OpenGL texture with `cv::UMat`.
Unfortunately `UMat` keeps OpenCL _buffer_ internally, that can't be wrapped over either OpenGL _texture_ or OpenCL _image_ - so we have to copy image data here:
@code{.cpp}
cl::ImageGL imgIn (theContext, CL_MEM_READ_ONLY, GL_TEXTURE_2D, 0, tex);
std::vector < cl::Memory > images(1, imgIn);
theQueue.enqueueAcquireGLObjects(&images);
theQueue.finish();
cv::UMat uIn, uOut, uTmp;
cv::ocl::convertFromImage(imgIn(), uIn);
theQueue.enqueueReleaseGLObjects(&images);
cv::Laplacian(uIn, uTmp, CV_8U);
cv:multiply(uTmp, 10, uOut);
cv::ocl::finish();
cl::ImageGL imgOut(theContext, CL_MEM_WRITE_ONLY, GL_TEXTURE_2D, 0, tex);
images.clear();
images.push_back(imgOut);
theQueue.enqueueAcquireGLObjects(&images);
cl_mem clBuffer = (cl_mem)uOut.handle(cv::ACCESS_READ);
cl_command_queue q = (cl_command_queue)cv::ocl::Queue::getDefault().ptr();
size_t offset = 0;
size_t origin[3] = { 0, 0, 0 };
size_t region[3] = { w, h, 1 };
CV_Assert(clEnqueueCopyBufferToImage (q, clBuffer, imgOut(), offset, origin, region, 0, NULL, NULL) == CL_SUCCESS);
theQueue.enqueueReleaseGLObjects(&images);
cv::ocl::finish();
@endcode
- @note We have to make one more image data copy when placing back the modified image to the original OpenGL texture via OpenCL image wrapper.
- @note By default the OpenCL support (T-API) is disabled in OpenCV builds for Android OS (so it's absent in official packages as of version 3.0),
but it's possible to rebuild locally OpenCV for Android with OpenCL/T-API enabled: use `-DWITH_OPENCL=YES` option for CMake.
@code{.cmd}
cd opencv-build-android
path/to/cmake.exe -GNinja -DCMAKE_MAKE_PROGRAM="path/to/ninja.exe" -DCMAKE_TOOLCHAIN_FILE=path/to/opencv/platforms/android/android.toolchain.cmake -DANDROID_ABI="armeabi-v7a with NEON" -DCMAKE_BUILD_WITH_INSTALL_RPATH=ON path/to/opencv
path/to/ninja.exe install/strip
@endcode
To use your own modified `libopencv_java4.so` you have to keep inside your APK, not to use OpenCV Manager and load it manually via `System.loadLibrary("opencv_java4")`.
Performance notes
-----------------
To compare the performance we measured FPS of the same preview frames modification (_Laplacian_) done by C/C++ code (call to `cv::Laplacian` with `cv::Mat`),
by direct OpenCL calls (using OpenCL _images_ for input and output), and by OpenCV _T-API_ (call to `cv::Laplacian` with `cv::UMat`) on _Sony Xperia Z3_ with 720p camera resolution:
* __C/C++ version__ shows __3-4 fps__
* __direct OpenCL calls__ shows __25-27 fps__
* __OpenCV T-API__ shows __11-13 fps__ (due to extra copying from `cl_image` to `cl_buffer` and back)

View File

@@ -0,0 +1,384 @@
Android Development with OpenCV {#tutorial_dev_with_OCV_on_Android}
===============================
@prev_tutorial{tutorial_O4A_SDK}
@next_tutorial{tutorial_android_ocl_intro}
| | |
| -: | :- |
| Original author | Vsevolod Glumov |
| Compatibility | OpenCV >= 3.0 |
@warning
This tutorial is deprecated.
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 tutorial_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 tutorial_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](https://forum.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: `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.
-# 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`).
![](images/eclipse_opencv_dependency0.png)
-# In application project add a reference to the OpenCV Java SDK in
Project -\> Properties -\> Android -\> Library -\> Add select OpenCV Library - 2.4.9.
![](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 `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.
-# 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`).
![](images/eclipse_opencv_dependency0.png)
-# In the application project add a reference to the OpenCV4Android SDK in
Project -\> Properties -\> Android -\> Library -\> Add select OpenCV Library - 2.4.9;
![](images/eclipse_opencv_dependency1.png)
-# 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 $(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 $(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).
-# 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:
-# 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.
-# 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`.
-# 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 $(CLEAR_VARS)
@endcode
-# 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.
-# 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
-# Either use @ref tutorial_android_dev_intro_ndk "manual" ndk-build invocation or
@ref tutorial_android_dev_intro_eclipse "setup Eclipse 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.
-# Open Eclipse IDE, create a new clean workspace, create a new Android project
File --\> New --\> Android Project
-# 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.
-# Allow Eclipse to create default activity. Lets name the activity HelloOpenCvActivity.
-# Choose Blank Activity with full screen layout. Lets name the layout HelloOpenCvLayout.
-# Import OpenCV library project to your workspace.
-# Reference OpenCV library within your project properties.
![](images/dev_OCV_reference.png)
-# 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
-# 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
-# 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
-# Add OpenCV library initialization to your activity. Fix errors by adding required 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
-# 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 to the code snippet below. Fix errors by adding required 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
-# 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.
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.

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

View File

@@ -0,0 +1,667 @@
Building OpenCV for Tegra with CUDA {#tutorial_building_tegra_cuda}
===================================
@prev_tutorial{tutorial_arm_crosscompile_with_cmake}
@next_tutorial{tutorial_display_image}
| | |
| -: | :- |
| Original author | Randy J. Ray |
| Compatibility | OpenCV >= 3.1.0 |
@warning
This tutorial is deprecated.
@tableofcontents
OpenCV with CUDA for Tegra
==========================
This document is a basic guide to building the OpenCV libraries with CUDA support for use in the Tegra environment. It covers the basic elements of building the version 3.1.0 libraries from source code for three (3) different types of platforms:
* NVIDIA DRIVE&trade; PX 2 (V4L)
* NVIDIA<sup>&reg;</sup> Tegra<sup>&reg;</sup> Linux Driver Package (L4T)
* Desktop Linux (Ubuntu 14.04 LTS and 16.04 LTS)
This document is not an exhaustive guide to all of the options available when building OpenCV. Specifically, it covers the basic options used when building each platform but does not cover any options that are not needed (or are unchanged from their default values). Additionally, the installation of the CUDA toolkit is not covered here.
This document is focused on building the 3.1.0 version of OpenCV, but the guidelines here may also work for building from the master branch of the git repository. There are differences in some of the CMake options for builds of the 2.4.13 version of OpenCV, which are summarized below in the @ref tutorial_building_tegra_cuda_opencv_24X section.
Most of the configuration commands are based on the system having CUDA 8.0 installed. In the case of the Jetson TK1, an older CUDA is used because 8.0 is not supported for that platform. These instructions may also work with older versions of CUDA, but are only tested with 8.0.
### A Note on Native Compilation vs. Cross-Compilation
The OpenCV build system supports native compilation for all the supported platforms, as well as cross-compilation for platforms such as ARM and others. The native compilation process is simpler, whereas the cross-compilation is generally faster.
At the present time, this document focuses only on native compilation.
Getting the Source Code {#tutorial_building_tegra_cuda_getting_the_code}
=======================
There are two (2) ways to get the OpenCV source code:
* Direct download from the [OpenCV downloads](http://opencv.org/releases.html) page
* Cloning the git repositories hosted on [GitHub](https://github.com/opencv)
For this guide, the focus is on using the git repositories. This is because the 3.1.0 version of OpenCV will not build with CUDA 8.0 without applying a few small upstream changes from the git repository.
OpenCV
------
Start with the `opencv` repository:
# Clone the opencv repository locally:
$ git clone https://github.com/opencv/opencv.git
To build the 3.1.0 version (as opposed to building the most-recent source), you must check out a branch based on the `3.1.0` tag:
$ cd opencv
$ git checkout -b v3.1.0 3.1.0
__Note:__ This operation creates a new local branch in your clone's repository.
There are some upstream changes that must be applied via the `git cherry-pick` command. The first of these is to apply a fix for building specifically with the 8.0 version of CUDA that was not part of the 3.1.0 release:
# While still in the opencv directory:
$ git cherry-pick 10896
You will see the following output from the command:
[v3.1.0 d6d69a7] GraphCut deprecated in CUDA 7.5 and removed in 8.0
Author: Vladislav Vinogradov <vlad.vinogradov@itseez.com>
1 file changed, 2 insertions(+), 1 deletion(-)
Secondly, there is a fix for a CMake macro call that is problematic on some systems:
$ git cherry pick cdb9c
You should see output similar to:
[v3.1.0-28613 e5ac2e4] gpu samples: fix REMOVE_ITEM error
Author: Alexander Alekhin <alexander.alekhin@itseez.com>
1 file changed, 1 insertion(+), 1 deletion(-)
The last upstream fix that is needed deals with the `pkg-config` configuration file that is bundled with the developer package (`libopencv-dev`):
$ git cherry-pick 24dbb
You should see output similar to:
[v3.1.0 3a6d7ab] pkg-config: modules list contains only OpenCV modules (fixes #5852)
Author: Alexander Alekhin <alexander.alekhin@itseez.com>
1 file changed, 7 insertions(+), 4 deletions(-)
At this point, the `opencv` repository is ready for building.
OpenCV Extra
------------
The `opencv_extra` repository contains extra data for the OpenCV library, including the data files used by the tests and demos. It must be cloned separately:
# In the same base directory from which you cloned OpenCV:
$ git clone https://github.com/opencv/opencv_extra.git
As with the OpenCV source, you must use the same method as above to set the source tree to the 3.1.0 version. When you are building from a specific tag, both repositories must be checked out at that tag.
$ cd opencv_extra
$ git checkout -b v3.1.0 3.1.0
You may opt to not fetch this repository if you do not plan on running the tests or installing the test-data along with the samples and example programs. If it is not referenced in the invocation of CMake, it will not be used.
__Note:__ If you plan to run the tests, some tests expect the data to be present and will fail without it.
Preparation and Prerequisites {#tutorial_building_tegra_cuda_preparation}
=============================
To build OpenCV, you need a directory to create the configuration and build the libraries. You also need a number of 3rd-party libraries upon which OpenCV depends.
Prerequisites for Ubuntu Linux
------------------------------
These are the basic requirements for building OpenCV for Tegra on Linux:
* CMake 2.8.10 or newer
* CUDA toolkit 8.0 (7.0 or 7.5 may also be used)
* Build tools (make, gcc, g++)
* Python 2.6 or greater
These are the same regardless of the platform (DRIVE PX 2, Desktop, etc.).
A number of development packages are required for building on Linux:
* libglew-dev
* libtiff5-dev
* zlib1g-dev
* libjpeg-dev
* libpng12-dev
* libjasper-dev
* libavcodec-dev
* libavformat-dev
* libavutil-dev
* libpostproc-dev
* libswscale-dev
* libeigen3-dev
* libtbb-dev
* libgtk2.0-dev
* pkg-config
Some of the packages above are in the `universe` repository for Ubuntu Linux systems. If you have not already enabled that repository, you need to do the following before trying to install all of the packages listed above:
$ sudo apt-add-repository universe
$ sudo apt-get update
The following command can be pasted into a shell in order to install the required packages:
$ sudo apt-get install \
libglew-dev \
libtiff5-dev \
zlib1g-dev \
libjpeg-dev \
libpng12-dev \
libjasper-dev \
libavcodec-dev \
libavformat-dev \
libavutil-dev \
libpostproc-dev \
libswscale-dev \
libeigen3-dev \
libtbb-dev \
libgtk2.0-dev \
pkg-config
(Line-breaks and continuation characters are added for readability.)
If you want the Python bindings to be built, you will also need the appropriate packages for either or both of Python 2 and Python 3:
* python-dev / python3-dev
* python-numpy / python3-numpy
* python-py / python3-py
* python-pytest / python3-pytest
The commands that will do this:
$ sudo apt-get install python-dev python-numpy python-py python-pytest
# And, optionally:
$ sudo apt-get install python3-dev python3-numpy python3-py python3-pytest
Once all the necessary packages are installed, you can configure the build.
Preparing the Build Area
------------------------
Software projects that use the CMake system for configuring their builds expect the actual builds to be done outside of the source tree itself. For configuring and building OpenCV, create a directory called "build" in the same base directory into which you cloned the git repositories:
$ mkdir build
$ cd build
You are now ready to configure and build OpenCV.
Configuring OpenCV for Building {#tutorial_building_tegra_cuda_configuring}
===============================
The CMake configuration options given below for the different platforms are targeted towards the functionality needed for Tegra. They are based on the original configuration options used for building OpenCV 2.4.13.
The build of OpenCV is configured with CMake. If run with no parameters, it detects what it needs to know about your system. However, it may have difficulty finding the CUDA files if they are not in a standard location, and it may try to build some options that you might otherwise not want included, so the following invocations of CMake are recommended.
In each `cmake` command listed in the following sub-sections, line-breaks and indentation are added for readability. Continuation characters are also added in examples for Linux-based platforms, allowing you to copy and paste the examples directly into a shell. When entering these commands by hand, enter the command and options as a single line. For a detailed explanation of the parameters passed to `cmake`, see the "CMake Parameter Reference" section.
For the Linux-based platforms, the shown value for the `CMAKE_INSTALL_PREFIX` parameter is `/usr`. You can set this to whatever you want, based on the layout of your system.
In each of the `cmake` invocations below, the last parameter, `OPENCV_TEST_DATA_PATH`, tells the build system where to find the test-data that is provided by the `opencv_extra` repository. When this is included, a `make install` installs this test-data alongside the libraries and example code, and a `make test` automatically provides this path to the tests that have to load data from it. If you did not clone the `opencv_extra` repository, do not include this parameter.
Vibrante V4L Configuration
--------------------------
Supported platform: Drive PX 2
$ cmake \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_INSTALL_PREFIX=/usr \
-DBUILD_PNG=OFF \
-DBUILD_TIFF=OFF \
-DBUILD_TBB=OFF \
-DBUILD_JPEG=OFF \
-DBUILD_JASPER=OFF \
-DBUILD_ZLIB=OFF \
-DBUILD_EXAMPLES=ON \
-DBUILD_JAVA=OFF \
-DBUILD_opencv_python2=ON \
-DBUILD_opencv_python3=OFF \
-DENABLE_NEON=ON \
-DWITH_OPENCL=OFF \
-DWITH_OPENMP=OFF \
-DWITH_FFMPEG=ON \
-DWITH_GSTREAMER=OFF \
-DWITH_GSTREAMER_0_10=OFF \
-DWITH_CUDA=ON \
-DWITH_GTK=ON \
-DWITH_VTK=OFF \
-DWITH_TBB=ON \
-DWITH_1394=OFF \
-DWITH_OPENEXR=OFF \
-DCUDA_TOOLKIT_ROOT_DIR=/usr/local/cuda-8.0 \
-DCUDA_ARCH_BIN=6.2 \
-DCUDA_ARCH_PTX="" \
-DINSTALL_C_EXAMPLES=ON \
-DINSTALL_TESTS=OFF \
-DOPENCV_TEST_DATA_PATH=../opencv_extra/testdata \
../opencv
The configuration provided above builds the Python bindings for Python 2 (but not Python 3) as part of the build process. If you want the Python 3 bindings (or do not want the Python 2 bindings), change the values of `BUILD_opencv_python2` and/or `BUILD_opencv_python3` as needed. To enable bindings, set the value to `ON`, to disable them set it to `OFF`:
-DBUILD_opencv_python2=OFF
Jetson L4T Configuration
------------------------
Supported platforms:
* Jetson TK1
* Jetson TX1
Configuration is slightly different for the Jetson TK1 and the Jetson TX1 systems.
### Jetson TK1
$ cmake \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_INSTALL_PREFIX=/usr \
-DCMAKE_CXX_FLAGS=-Wa,-mimplicit-it=thumb \
-DBUILD_PNG=OFF \
-DBUILD_TIFF=OFF \
-DBUILD_TBB=OFF \
-DBUILD_JPEG=OFF \
-DBUILD_JASPER=OFF \
-DBUILD_ZLIB=OFF \
-DBUILD_EXAMPLES=ON \
-DBUILD_JAVA=OFF \
-DBUILD_opencv_python2=ON \
-DBUILD_opencv_python3=OFF \
-DENABLE_NEON=ON \
-DWITH_OPENCL=OFF \
-DWITH_OPENMP=OFF \
-DWITH_FFMPEG=ON \
-DWITH_GSTREAMER=OFF \
-DWITH_GSTREAMER_0_10=OFF \
-DWITH_CUDA=ON \
-DWITH_GTK=ON \
-DWITH_VTK=OFF \
-DWITH_TBB=ON \
-DWITH_1394=OFF \
-DWITH_OPENEXR=OFF \
-DCUDA_TOOLKIT_ROOT_DIR=/usr/local/cuda-6.5 \
-DCUDA_ARCH_BIN=3.2 \
-DCUDA_ARCH_PTX="" \
-DINSTALL_C_EXAMPLES=ON \
-DINSTALL_TESTS=OFF \
-DOPENCV_TEST_DATA_PATH=../opencv_extra/testdata \
../opencv
__Note:__ This uses CUDA 6.5, not 8.0.
### Jetson TX1
$ cmake \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_INSTALL_PREFIX=/usr \
-DBUILD_PNG=OFF \
-DBUILD_TIFF=OFF \
-DBUILD_TBB=OFF \
-DBUILD_JPEG=OFF \
-DBUILD_JASPER=OFF \
-DBUILD_ZLIB=OFF \
-DBUILD_EXAMPLES=ON \
-DBUILD_JAVA=OFF \
-DBUILD_opencv_python2=ON \
-DBUILD_opencv_python3=OFF \
-DENABLE_PRECOMPILED_HEADERS=OFF \
-DWITH_OPENCL=OFF \
-DWITH_OPENMP=OFF \
-DWITH_FFMPEG=ON \
-DWITH_GSTREAMER=OFF \
-DWITH_GSTREAMER_0_10=OFF \
-DWITH_CUDA=ON \
-DWITH_GTK=ON \
-DWITH_VTK=OFF \
-DWITH_TBB=ON \
-DWITH_1394=OFF \
-DWITH_OPENEXR=OFF \
-DCUDA_TOOLKIT_ROOT_DIR=/usr/local/cuda-8.0 \
-DCUDA_ARCH_BIN=5.3 \
-DCUDA_ARCH_PTX="" \
-DINSTALL_C_EXAMPLES=ON \
-DINSTALL_TESTS=OFF \
-DOPENCV_TEST_DATA_PATH=../opencv_extra/testdata \
../opencv
__Note:__ This configuration does not set the `ENABLE_NEON` parameter.
Ubuntu Desktop Linux Configuration
----------------------------------
Supported platforms:
* Ubuntu Desktop Linux 14.04 LTS
* Ubuntu Desktop Linux 16.04 LTS
The configuration options given to `cmake` below are targeted towards the functionality needed for Tegra. For a desktop system, you may wish to adjust some options to enable (or disable) certain features. The features enabled below are based on the building of OpenCV 2.4.13.
$ cmake \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_INSTALL_PREFIX=/usr \
-DBUILD_PNG=OFF \
-DBUILD_TIFF=OFF \
-DBUILD_TBB=OFF \
-DBUILD_JPEG=OFF \
-DBUILD_JASPER=OFF \
-DBUILD_ZLIB=OFF \
-DBUILD_EXAMPLES=ON \
-DBUILD_JAVA=OFF \
-DBUILD_opencv_python2=ON \
-DBUILD_opencv_python3=OFF \
-DWITH_OPENCL=OFF \
-DWITH_OPENMP=OFF \
-DWITH_FFMPEG=ON \
-DWITH_GSTREAMER=OFF \
-DWITH_GSTREAMER_0_10=OFF \
-DWITH_CUDA=ON \
-DWITH_GTK=ON \
-DWITH_VTK=OFF \
-DWITH_TBB=ON \
-DWITH_1394=OFF \
-DWITH_OPENEXR=OFF \
-DCUDA_TOOLKIT_ROOT_DIR=/usr/local/cuda-8.0 \
-DCUDA_ARCH_BIN='3.0 3.5 5.0 6.0 6.2' \
-DCUDA_ARCH_PTX="" \
-DINSTALL_C_EXAMPLES=ON \
-DINSTALL_TESTS=OFF \
-DOPENCV_TEST_DATA_PATH=../opencv_extra/testdata \
../opencv
This configuration is nearly identical to that for V4L and L4T, except that the `CUDA_ARCH_BIN` parameter specifies multiple architectures so as to support a variety of GPU boards. For a desktop, you have the option of omitting this parameter, and CMake will instead run a small test program that probes for the supported architectures. However, the libraries produced might not work on Ubuntu systems with different cards.
As with previous examples, the configuration given above builds the Python bindings for Python 2 (but not Python 3) as part of the build process.
Building OpenCV {#tutorial_building_tegra_cuda_building}
===============
Once `cmake` finishes configuring OpenCV, building is done using the standard `make` utility.
Building with `make`
--------------------
The only parameter that is needed for the invocation of `make` is the `-j` parameter for specifying how many parallel threads to use. This varies depending on the system and how much memory is available, other running processes, etc. The following table offers suggested values for this parameter:
|Platform|Suggested value|Notes|
|--------|---------------|-----|
|DRIVE PX 2|6| |
|Jetson TK1|3|If the build fails due to a compiler-related error, try again with a smaller number of threads. Also consider rebooting the system if it has been running for a long time since the last reboot.|
|Jetson TX1|4| |
|Ubuntu Desktop|7|The actual value will vary with the number of cores you have and the amount of physical memory. Because of the resource requirements of compiling the CUDA code, it is not recommended to go above 7.|
Based on the value you select, build (assuming you selected 6):
$ make -j6
By default, CMake hides the details of the build steps. If you need to see more detail about each compilation unit, etc., you can enable verbose output:
$ make -j6 VERBOSE=1
Testing OpenCV {#tutorial_building_tegra_cuda_testing}
==============
Once the build completes successfully, you have the option of running the extensive set of tests that OpenCV provides. If you did not clone the `opencv_extra` repository and specify the path to `testdata` in the `cmake` invocation, then testing is not recommended.
Testing under Linux
-------------------
To run the basic tests under Linux, execute:
$ make test
This executes `ctest` to carry out the tests, as specified in CTest syntax within the OpenCV repository. The `ctest` harness takes many different parameters (too many to list here, see the manual page for CTest to see the full set), and if you wish to pass any of them, you can do so by specifying them in a `make` command-line parameter called `ARGS`:
$ make test ARGS="--verbose --parallel 3"
In this example, there are two (2) arguments passed to `ctest`: `--verbose` and `--parallel 3`. The first argument causes the output from `ctest` to be more detailed, and the second causes `ctest` to run as many as three (3) tests in parallel. As with choosing a thread count for building, base any choice for testing on the available number of processor cores, physical memory, etc. Some of the tests do attempt to allocate significant amounts of memory.
### Known Issues with Tests
At present, not all of the tests in the OpenCV test suite pass. There are tests that fail whether or not CUDA is compiled, and there are tests that are only specific to CUDA that also do not currently pass.
__Note:__ There are no tests that pass without CUDA but fail only when CUDA is included.
As the full lists of failing tests vary based on platform, it is impractical to list them here.
Installing OpenCV {#tutorial_building_tegra_cuda_installing}
=================
Installing OpenCV is very straightforward. For the Linux-based platforms, the command is:
$ make install
Depending on the chosen installation location, you may need root privilege to install.
Building OpenCV 2.4.X {#tutorial_building_tegra_cuda_opencv_24X}
=====================
If you wish to build your own version of the 2.4 version of OpenCV, there are only a few adjustments that must be made. At the time of this writing, the latest version on the 2.4 tree is 2.4.13. These instructions may work for later versions of 2.4, though they have not been tested for any earlier versions.
__Note:__ The 2.4.X OpenCV source does not have the extra modules and code for Tegra that was upstreamed into the 3.X versions of OpenCV. This part of the guide is only for cases where you want to build a vanilla version of OpenCV 2.4.
Selecting the 2.4 Source
------------------------
First you must select the correct source branch or tag. If you want a specific version such as 2.4.13, you want to make a local branch based on the tag, as was done with the 3.1.0 tag above:
# Within the opencv directory:
$ git checkout -b v2.4.13 2.4.13
# Within the opencv_extra directory:
$ git checkout -b v2.4.13 2.4.13
If you simply want the newest code from the 2.4 line of OpenCV, there is a `2.4` branch already in the repository. You can check that out instead of a specific tag:
$ git checkout 2.4
There is no need for the `git cherry-pick` commands used with 3.1.0 when building the 2.4.13 source.
Configuring
-----------
Configuring is done with CMake as before. The primary difference is that OpenCV 2.4 only provides Python bindings for Python 2, and thus does not distinguish between Python 2 and Python 3 in the CMake parameters. There is only one parameter, `BUILD_opencv_python`. In addition, there is a build-related parameter that controls features in 2.4 that are not in 3.1.0. This parameter is `BUILD_opencv_nonfree`.
Configuration still takes place in a separate directory that must be a sibling to the `opencv` and `opencv_extra` directories.
### Configuring Vibrante V4L
For DRIVE PX 2:
$ cmake \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_INSTALL_PREFIX=/usr \
-DBUILD_PNG=OFF \
-DBUILD_TIFF=OFF \
-DBUILD_TBB=OFF \
-DBUILD_JPEG=OFF \
-DBUILD_JASPER=OFF \
-DBUILD_ZLIB=OFF \
-DBUILD_EXAMPLES=ON \
-DBUILD_JAVA=OFF \
-DBUILD_opencv_nonfree=OFF \
-DBUILD_opencv_python=ON \
-DENABLE_NEON=ON \
-DWITH_OPENCL=OFF \
-DWITH_OPENMP=OFF \
-DWITH_FFMPEG=ON \
-DWITH_GSTREAMER=OFF \
-DWITH_GSTREAMER_0_10=OFF \
-DWITH_CUDA=ON \
-DWITH_GTK=ON \
-DWITH_VTK=OFF \
-DWITH_TBB=ON \
-DWITH_1394=OFF \
-DWITH_OPENEXR=OFF \
-DCUDA_TOOLKIT_ROOT_DIR=/usr/local/cuda-8.0 \
-DCUDA_ARCH_BIN=6.2 \
-DCUDA_ARCH_PTX="" \
-DINSTALL_C_EXAMPLES=ON \
-DINSTALL_TESTS=ON \
-DOPENCV_TEST_DATA_PATH=../opencv_extra/testdata \
../opencv
### Configuring Jetson L4T
For Jetson TK1:
$ cmake \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_INSTALL_PREFIX=/usr \
-DBUILD_PNG=OFF \
-DBUILD_TIFF=OFF \
-DBUILD_TBB=OFF \
-DBUILD_JPEG=OFF \
-DBUILD_JASPER=OFF \
-DBUILD_ZLIB=OFF \
-DBUILD_EXAMPLES=ON \
-DBUILD_JAVA=OFF \
-DBUILD_opencv_nonfree=OFF \
-DBUILD_opencv_python=ON \
-DENABLE_NEON=ON \
-DWITH_OPENCL=OFF \
-DWITH_OPENMP=OFF \
-DWITH_FFMPEG=ON \
-DWITH_GSTREAMER=OFF \
-DWITH_GSTREAMER_0_10=OFF \
-DWITH_CUDA=ON \
-DWITH_GTK=ON \
-DWITH_VTK=OFF \
-DWITH_TBB=ON \
-DWITH_1394=OFF \
-DWITH_OPENEXR=OFF \
-DCUDA_TOOLKIT_ROOT_DIR=/usr/local/cuda-6.5 \
-DCUDA_ARCH_BIN=3.2 \
-DCUDA_ARCH_PTX="" \
-DINSTALL_C_EXAMPLES=ON \
-DINSTALL_TESTS=ON \
-DOPENCV_TEST_DATA_PATH=../opencv_extra/testdata \
../opencv
For Jetson TX1:
$ cmake \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_INSTALL_PREFIX=/usr \
-DBUILD_PNG=OFF \
-DBUILD_TIFF=OFF \
-DBUILD_TBB=OFF \
-DBUILD_JPEG=OFF \
-DBUILD_JASPER=OFF \
-DBUILD_ZLIB=OFF \
-DBUILD_EXAMPLES=ON \
-DBUILD_JAVA=OFF \
-DBUILD_opencv_nonfree=OFF \
-DBUILD_opencv_python=ON \
-DENABLE_PRECOMPILED_HEADERS=OFF \
-DWITH_OPENCL=OFF \
-DWITH_OPENMP=OFF \
-DWITH_FFMPEG=ON \
-DWITH_GSTREAMER=OFF \
-DWITH_GSTREAMER_0_10=OFF \
-DWITH_CUDA=ON \
-DWITH_GTK=ON \
-DWITH_VTK=OFF \
-DWITH_TBB=ON \
-DWITH_1394=OFF \
-DWITH_OPENEXR=OFF \
-DCUDA_TOOLKIT_ROOT_DIR=/usr/local/cuda-8.0 \
-DCUDA_ARCH_BIN=5.3 \
-DCUDA_ARCH_PTX="" \
-DINSTALL_C_EXAMPLES=ON \
-DINSTALL_TESTS=ON \
-DOPENCV_TEST_DATA_PATH=../opencv_extra/testdata \
../opencv
### Configuring Desktop Ubuntu Linux
For both 14.04 LTS and 16.04 LTS:
$ cmake \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_INSTALL_PREFIX=/usr \
-DBUILD_PNG=OFF \
-DBUILD_TIFF=OFF \
-DBUILD_TBB=OFF \
-DBUILD_JPEG=OFF \
-DBUILD_JASPER=OFF \
-DBUILD_ZLIB=OFF \
-DBUILD_EXAMPLES=ON \
-DBUILD_JAVA=OFF \
-DBUILD_opencv_nonfree=OFF \
-DBUILD_opencv_python=ON \
-DWITH_OPENCL=OFF \
-DWITH_OPENMP=OFF \
-DWITH_FFMPEG=ON \
-DWITH_GSTREAMER=OFF \
-DWITH_GSTREAMER_0_10=OFF \
-DWITH_CUDA=ON \
-DWITH_GTK=ON \
-DWITH_VTK=OFF \
-DWITH_TBB=ON \
-DWITH_1394=OFF \
-DWITH_OPENEXR=OFF \
-DCUDA_TOOLKIT_ROOT_DIR=/usr/local/cuda-8.0 \
-DCUDA_ARCH_BIN='3.0 3.5 5.0 6.0 6.2' \
-DCUDA_ARCH_PTX="" \
-DINSTALL_C_EXAMPLES=ON \
-DINSTALL_TESTS=ON \
-DOPENCV_TEST_DATA_PATH=../opencv_extra/testdata \
../opencv
Building, Testing and Installing
--------------------------------
Once configured, the steps of building, testing, and installing are the same as above for the 3.1.0 source.
CMake Parameter Reference {#tutorial_building_tegra_cuda_parameter_reference}
=========================
The following is a table of all the parameters passed to CMake in the recommended invocations above. Some of these are parameters from CMake itself, while most are specific to OpenCV.
|Parameter|Our Default Value|What It Does|Notes|
|---------|-----------------|------------|-----|
|BUILD_EXAMPLES|ON|Governs whether the C/C++ examples are built| |
|BUILD_JASPER|OFF|Governs whether the Jasper library (`libjasper`) is built from source in the `3rdparty` directory| |
|BUILD_JPEG|OFF|As above, for `libjpeg`| |
|BUILD_PNG|OFF|As above, for `libpng`| |
|BUILD_TBB|OFF|As above, for `tbb`| |
|BUILD_TIFF|OFF|As above, for `libtiff`| |
|BUILD_ZLIB|OFF|As above, for `zlib`| |
|BUILD_JAVA|OFF|Controls the building of the Java bindings for OpenCV|Building the Java bindings requires OpenCV libraries be built for static linking only|
|BUILD_opencv_nonfree|OFF|Controls the building of non-free (non-open-source) elements|Used only for building 2.4.X|
|BUILD_opencv_python|ON|Controls the building of the Python 2 bindings in OpenCV 2.4.X|Used only for building 2.4.X|
|BUILD_opencv_python2|ON|Controls the building of the Python 2 bindings in OpenCV 3.1.0|Not used in 2.4.X|
|BUILD_opencv_python3|OFF|Controls the building of the Python 3 bindings in OpenCV 3.1.0|Not used in 2.4.X|
|CMAKE_BUILD_TYPE|Release|Selects the type of build (release vs. development)|Is generally either `Release` or `Debug`|
|CMAKE_INSTALL_PREFIX|/usr|Sets the root for installation of the libraries and header files| |
|CUDA_ARCH_BIN|varies|Sets the CUDA architecture(s) for which code is compiled|Usually only passed for platforms with known specific cards. OpenCV includes a small program that determines the architectures of the system's installed card if you do not pass this parameter. Here, for Ubuntu desktop, the value is a list to maximize card support.|
|CUDA_ARCH_PTX|""|Builds PTX intermediate code for the specified virtual PTX architectures| |
|CUDA_TOOLKIT_ROOT_DIR|/usr/local/cuda-8.0 (for Linux)|Specifies the location of the CUDA include files and libraries| |
|ENABLE_NEON|ON|Enables the use of NEON SIMD extensions for ARM chips|Only passed for builds on ARM platforms|
|ENABLE_PRECOMPILED_HEADERS|OFF|Enables/disables support for pre-compiled headers|Only specified on some of the ARM platforms|
|INSTALL_C_EXAMPLES|ON|Enables the installation of the C example files as part of `make install`| |
|INSTALL_TESTS|ON|Enables the installation of the tests as part of `make install`| |
|OPENCV_TEST_DATA_PATH|../opencv_extra/testdata|Path to the `testdata` directory in the `opencv_extra` repository| |
|WITH_1394|OFF|Specifies whether to include IEEE-1394 support| |
|WITH_CUDA|ON|Specifies whether to include CUDA support| |
|WITH_FFMPEG|ON|Specifies whether to include FFMPEG support| |
|WITH_GSTREAMER|OFF|Specifies whether to include GStreamer 1.0 support| |
|WITH_GSTREAMER_0_10|OFF|Specifies whether to include GStreamer 0.10 support| |
|WITH_GTK|ON|Specifies whether to include GTK 2.0 support|Only given on Linux platforms, not Microsoft Windows|
|WITH_OPENCL|OFF|Specifies whether to include OpenCL runtime support| |
|WITH_OPENEXR|OFF|Specifies whether to include ILM support via OpenEXR| |
|WITH_OPENMP|OFF|Specifies whether to include OpenMP runtime support| |
|WITH_TBB|ON|Specifies whether to include Intel TBB support| |
|WITH_VTK|OFF|Specifies whether to include VTK support| |
Copyright &copy; 2016, NVIDIA CORPORATION. All rights reserved.

View File

@@ -0,0 +1,597 @@
Introduction to OpenCV Development with Clojure {#tutorial_clojure_dev_intro}
===============================================
@prev_tutorial{tutorial_java_eclipse}
@next_tutorial{tutorial_android_dev_intro}
| | |
| -: | :- |
| Original author | Mimmo Cosenza |
| Compatibility | OpenCV >= 3.0 |
@warning
This tutorial can contain obsolete information.
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 @ref tutorial_java_dev_intro "corresponding
tutorial".
If you are in hurry, here is a minimum quick start guide to install OpenCV on Mac OS X:
@note
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/opencv/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:
-# [Download the script](https://raw.github.com/technomancy/leiningen/stable/bin/lein)
-# Place it on your $PATH (cf. \~/bin is a good choice if it is on your path.)
-# 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
[Here](https://docs.opencv.org/master/javadoc/index.html) 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 documentation:
@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 @ref tutorial_java_dev_intro "OpenCV Java tutorial sample".
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 initialized 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 accepted 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.
![](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.
![](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.

Binary file not shown.

After

Width:  |  Height:  |  Size: 351 KiB

View File

@@ -0,0 +1,592 @@
OpenCV configuration options reference {#tutorial_config_reference}
======================================
@prev_tutorial{tutorial_general_install}
@next_tutorial{tutorial_linux_install}
@tableofcontents
# Introduction {#tutorial_config_reference_intro}
@note
We assume you have read @ref tutorial_general_install tutorial or have experience with CMake.
Configuration options can be set in several different ways:
* Command line: `cmake -Doption=value ...`
* Initial cache files: `cmake -C my_options.txt ...`
* Interactive via GUI
In this reference we will use regular command line.
Most of the options can be found in the root cmake script of OpenCV: `opencv/CMakeLists.txt`. Some options can be defined in specific modules.
It is possible to use CMake tool to print all available options:
```.sh
# initial configuration
cmake ../opencv
# print all options
cmake -L
# print all options with help message
cmake -LH
# print all options including advanced
cmake -LA
```
Most popular and useful are options starting with `WITH_`, `ENABLE_`, `BUILD_`, `OPENCV_`.
Default values vary depending on platform and other options values.
# General options {#tutorial_config_reference_general}
## Build with extra modules {#tutorial_config_reference_general_contrib}
`OPENCV_EXTRA_MODULES_PATH` option contains a semicolon-separated list of directories containing extra modules which will be added to the build. Module directory must have compatible layout and CMakeLists.txt, brief description can be found in the [Coding Style Guide](https://github.com/opencv/opencv/wiki/Coding_Style_Guide).
Examples:
```.sh
# build with all modules in opencv_contrib
cmake -DOPENCV_EXTRA_MODULES_PATH=../opencv_contrib/modules ../opencv
# build with one of opencv_contrib modules
cmake -DOPENCV_EXTRA_MODULES_PATH=../opencv_contrib/modules/bgsegm ../opencv
# build with two custom modules (semicolon must be escaped in bash)
cmake -DOPENCV_EXTRA_MODULES_PATH=../my_mod1\;../my_mod2 ../opencv
```
@note
Only 0- and 1-level deep module locations are supported, following command will raise an error:
```.sh
cmake -DOPENCV_EXTRA_MODULES_PATH=../opencv_contrib ../opencv
```
## Debug build {#tutorial_config_reference_general_debug}
`CMAKE_BUILD_TYPE` option can be used to enable debug build; resulting binaries will contain debug symbols and most of compiler optimizations will be turned off. To enable debug symbols in Release build turn the `BUILD_WITH_DEBUG_INFO` option on.
On some platforms (e.g. Linux) build type must be set at configuration stage:
```.sh
cmake -DCMAKE_BUILD_TYPE=Debug ../opencv
cmake --build .
```
On other platforms different types of build can be produced in the same build directory (e.g. Visual Studio, XCode):
```.sh
cmake <options> ../opencv
cmake --build . --config Debug
```
If you use GNU libstdc++ (default for GCC) you can turn on the `ENABLE_GNU_STL_DEBUG` option, then C++ library will be used in Debug mode, e.g. indexes will be bound-checked during vector element access.
Many kinds of optimizations can be disabled with `CV_DISABLE_OPTIMIZATION` option:
* Some third-party libraries (e.g. IPP, Lapack, Eigen)
* Explicit vectorized implementation (universal intrinsics, raw intrinsics, etc.)
* Dispatched optimizations
* Explicit loop unrolling
@see https://cmake.org/cmake/help/latest/variable/CMAKE_BUILD_TYPE.html
@see https://gcc.gnu.org/onlinedocs/libstdc++/manual/using_macros.html
@see https://github.com/opencv/opencv/wiki/CPU-optimizations-build-options
## Static build {#tutorial_config_reference_general_static}
`BUILD_SHARED_LIBS` option control whether to produce dynamic (.dll, .so, .dylib) or static (.a, .lib) libraries. Default value depends on target platform, in most cases it is `ON`.
Example:
```.sh
cmake -DBUILD_SHARED_LIBS=OFF ../opencv
```
@see https://en.wikipedia.org/wiki/Static_library
`ENABLE_PIC` sets the [CMAKE_POSITION_INDEPENDENT_CODE](https://cmake.org/cmake/help/latest/variable/CMAKE_POSITION_INDEPENDENT_CODE.html) option. It enables or disable generation of "position-independent code". This option must be enabled when building dynamic libraries or static libraries intended to be linked into dynamic libraries. Default value is `ON`.
@see https://en.wikipedia.org/wiki/Position-independent_code
## Generate pkg-config info
`OPENCV_GENERATE_PKGCONFIG` option enables `.pc` file generation along with standard CMake package. This file can be useful for projects which do not use CMake for build.
Example:
```.sh
cmake -DOPENCV_GENERATE_PKGCONFIG=ON ../opencv
```
@note
Due to complexity of configuration process resulting `.pc` file can contain incomplete list of third-party dependencies and may not work in some configurations, especially for static builds. This feature is not officially supported since 4.x version and is disabled by default.
## Build tests, samples and applications {#tutorial_config_reference_general_tests}
There are two kinds of tests: accuracy (`opencv_test_*`) and performance (`opencv_perf_*`). Tests and applications are enabled by default. Examples are not being built by default and should be enabled explicitly.
Corresponding _cmake_ options:
```.sh
cmake \
-DBUILD_TESTS=ON \
-DBUILD_PERF_TESTS=ON \
-DBUILD_EXAMPLES=ON \
-DBUILD_opencv_apps=ON \
../opencv
```
## Build limited set of modules {#tutorial_config_reference_general_modules}
Each module is a subdirectory of the `modules` directory. It is possible to disable one module:
```.sh
cmake -DBUILD_opencv_calib3d=OFF ../opencv
```
The opposite option is to build only specified modules and all modules they depend on:
```.sh
cmake -DBUILD_LIST=calib3d,videoio,ts ../opencv
```
In this example we requested 3 modules and configuration script has determined all dependencies automatically:
```
-- OpenCV modules:
-- To be built: calib3d core features2d flann highgui imgcodecs imgproc ts videoio
```
## Downloaded dependencies {#tutorial_config_reference_general_download}
Configuration script can try to download additional libraries and files from the internet, if it fails to do it corresponding features will be turned off. In some cases configuration error can occur. By default all files are first downloaded to the `<source>/.cache` directory and then unpacked or copied to the build directory. It is possible to change download cache location by setting environment variable or configuration option:
```.sh
export OPENCV_DOWNLOAD_PATH=/tmp/opencv-cache
cmake ../opencv
# or
cmake -DOPENCV_DOWNLOAD_PATH=/tmp/opencv-cache ../opencv
```
In case of access via proxy, corresponding environment variables should be set before running cmake:
```.sh
export http_proxy=<proxy-host>:<port>
export https_proxy=<proxy-host>:<port>
```
Full log of download process can be found in build directory - `CMakeDownloadLog.txt`. In addition, for each failed download a command will be added to helper scripts in the build directory, e.g. `download_with_wget.sh`. Users can run these scripts as is or modify according to their needs.
## CPU optimization level {#tutorial_config_reference_general_cpu}
On x86_64 machines the library will be compiled for SSE3 instruction set level by default. This level can be changed by configuration option:
```.sh
cmake -DCPU_BASELINE=AVX2 ../opencv
```
@note
Other platforms have their own instruction set levels: `VFPV3` and `NEON` on ARM, `VSX` on PowerPC.
Some functions support dispatch mechanism allowing to compile them for several instruction sets and to choose one during runtime. List of enabled instruction sets can be changed during configuration:
```.sh
cmake -DCPU_DISPATCH=AVX,AVX2 ../opencv
```
To disable dispatch mechanism this option should be set to an empty value:
```.sh
cmake -DCPU_DISPATCH= ../opencv
```
It is possible to disable optimized parts of code for troubleshooting and debugging:
```.sh
# disable universal intrinsics
cmake -DCV_ENABLE_INTRINSICS=OFF ../opencv
# disable all possible built-in optimizations
cmake -DCV_DISABLE_OPTIMIZATION=ON ../opencv
```
@note
More details on CPU optimization options can be found in wiki: https://github.com/opencv/opencv/wiki/CPU-optimizations-build-options
## Profiling, coverage, sanitize, hardening, size optimization
Following options can be used to produce special builds with instrumentation or improved security. All options are disabled by default.
| Option | Compiler | Description |
| `ENABLE_PROFILING` | GCC or Clang | Enable profiling compiler and linker options. |
| `ENABLE_COVERAGE` | GCC or Clang | Enable code coverage support. |
| `OPENCV_ENABLE_MEMORY_SANITIZER` | N/A | Enable several quirks in code to assist memory sanitizer. |
| `ENABLE_BUILD_HARDENING` | GCC, Clang, MSVC | Enable compiler options which reduce possibility of code exploitation. |
| `ENABLE_LTO` | GCC, Clang, MSVC | Enable Link Time Optimization (LTO). |
| `ENABLE_THIN_LTO` | Clang | Enable thin LTO which incorporates intermediate bitcode to binaries allowing consumers optimize their applications later. |
@see [GCC instrumentation](https://gcc.gnu.org/onlinedocs/gcc/Instrumentation-Options.html)
@see [Build hardening](https://en.wikipedia.org/wiki/Hardening_(computing))
@see [Interprocedural optimization](https://en.wikipedia.org/wiki/Interprocedural_optimization)
@see [Link time optimization](https://gcc.gnu.org/wiki/LinkTimeOptimization)
@see [ThinLTO](https://clang.llvm.org/docs/ThinLTO.html)
# Functional features and dependencies {#tutorial_config_reference_func}
There are many optional dependencies and features that can be turned on or off. _cmake_ has special option allowing to print all available configuration parameters:
```.sh
cmake -LH ../opencv
```
## Options naming conventions
There are three kinds of options used to control dependencies of the library, they have different prefixes:
- Options starting with `WITH_` enable or disable a dependency
- Options starting with `BUILD_` enable or disable building and using 3rdparty library bundled with OpenCV
- Options starting with `HAVE_` indicate that dependency have been enabled, can be used to manually enable a dependency if automatic detection can not be used.
When `WITH_` option is enabled:
- If `BUILD_` option is enabled, 3rdparty library will be built and enabled => `HAVE_` set to `ON`
- If `BUILD_` option is disabled, 3rdparty library will be detected and enabled if found => `HAVE_` set to `ON` if dependency is found
## Heterogeneous computation {#tutorial_config_reference_func_hetero}
### CUDA support
`WITH_CUDA` (default: _OFF_)
Many algorithms have been implemented using CUDA acceleration, these functions are located in separate modules. CUDA toolkit must be installed from the official NVIDIA site as a prerequisite. For cmake versions older than 3.9 OpenCV uses own `cmake/FindCUDA.cmake` script, for newer versions - the one packaged with CMake. Additional options can be used to control build process, e.g. `CUDA_GENERATION` or `CUDA_ARCH_BIN`. These parameters are not documented yet, please consult with the `cmake/OpenCVDetectCUDA.cmake` script for details.
@note Since OpenCV version 4.0 all CUDA-accelerated algorithm implementations have been moved to the _opencv_contrib_ repository. To build _opencv_ and _opencv_contrib_ together check @ref tutorial_config_reference_general_contrib.
@cond CUDA_MODULES
@note Some tutorials can be found in the corresponding section: @ref tutorial_table_of_content_gpu
@see @ref cuda
@endcond
@see https://en.wikipedia.org/wiki/CUDA
TODO: other options: `WITH_CUFFT`, `WITH_CUBLAS`, `WITH_NVCUVID`?
### OpenCL support
`WITH_OPENCL` (default: _ON_)
Multiple OpenCL-accelerated algorithms are available via so-called "Transparent API (T-API)". This integration uses same functions at the user level as regular CPU implementations. Switch to the OpenCL execution branch happens if input and output image arguments are passed as opaque cv::UMat objects. More information can be found in [the brief introduction](https://opencv.org/opencl/) and @ref core_opencl
At the build time this feature does not have any prerequisites. During runtime a working OpenCL runtime is required, to check it run `clinfo` and/or `opencv_version --opencl` command. Some parameters of OpenCL integration can be modified using environment variables, e.g. `OPENCV_OPENCL_DEVICE`. However there is no thorough documentation for this feature yet, so please check the source code in `modules/core/src/ocl.cpp` file for details.
@see https://en.wikipedia.org/wiki/OpenCL
TODO: other options: `WITH_OPENCL_SVM`, `WITH_OPENCLAMDFFT`, `WITH_OPENCLAMDBLAS`, `WITH_OPENCL_D3D11_NV`, `WITH_VA_INTEL`
## Image reading and writing (imgcodecs module) {#tutorial_config_reference_func_imgcodecs}
### Built-in formats
Following formats can be read by OpenCV without help of any third-party library:
- [BMP](https://en.wikipedia.org/wiki/BMP_file_format)
- [HDR](https://en.wikipedia.org/wiki/RGBE_image_format) (`WITH_IMGCODEC_HDR`)
- [Sun Raster](https://en.wikipedia.org/wiki/Sun_Raster) (`WITH_IMGCODEC_SUNRASTER`)
- [PPM, PGM, PBM, PFM](https://en.wikipedia.org/wiki/Netpbm#File_formats) (`WITH_IMGCODEC_PXM`, `WITH_IMGCODEC_PFM`)
### PNG, JPEG, TIFF, WEBP support
| Formats | Option | Default | Force build own |
| --------| ------ | ------- | --------------- |
| [PNG](https://en.wikipedia.org/wiki/Portable_Network_Graphics) | `WITH_PNG` | _ON_ | `BUILD_PNG` |
| [JPEG](https://en.wikipedia.org/wiki/JPEG) | `WITH_JPEG` | _ON_ | `BUILD_JPEG` |
| [TIFF](https://en.wikipedia.org/wiki/TIFF) | `WITH_TIFF` | _ON_ | `BUILD_TIFF` |
| [WEBP](https://en.wikipedia.org/wiki/WebP) | `WITH_WEBP` | _ON_ | `BUILD_WEBP` |
| [JPEG2000 with OpenJPEG](https://en.wikipedia.org/wiki/OpenJPEG) | `WITH_OPENJPEG` | _ON_ | `BUILD_OPENJPEG` |
| [JPEG2000 with JasPer](https://en.wikipedia.org/wiki/JasPer) | `WITH_JASPER` | _ON_ (see note) | `BUILD_JASPER` |
| [EXR](https://en.wikipedia.org/wiki/OpenEXR) | `WITH_OPENEXR` | _ON_ | `BUILD_OPENEXR` |
All libraries required to read images in these formats are included into OpenCV and will be built automatically if not found at the configuration stage. Corresponding `BUILD_*` options will force building and using own libraries, they are enabled by default on some platforms, e.g. Windows.
@note OpenJPEG have higher priority than JasPer which is deprecated. In order to use JasPer, OpenJPEG must be disabled.
### GDAL integration
`WITH_GDAL` (default: _OFF_)
[GDAL](https://en.wikipedia.org/wiki/GDAL) is a higher level library which supports reading multiple file formats including PNG, JPEG and TIFF. It will have higher priority when opening files and can override other backends. This library will be searched using cmake package mechanism, make sure it is installed correctly or manually set `GDAL_DIR` environment or cmake variable.
### GDCM integration
`WITH_GDCM` (default: _OFF_)
Enables [DICOM](https://en.wikipedia.org/wiki/DICOM) medical image format support through [GDCM library](https://en.wikipedia.org/wiki/GDCM). This library will be searched using cmake package mechanism, make sure it is installed correctly or manually set `GDCM_DIR` environment or cmake variable.
## Video reading and writing (videoio module) {#tutorial_config_reference_func_videoio}
TODO: how videoio works, registry, priorities
### Video4Linux
`WITH_V4L` (Linux; default: _ON_ )
Capture images from camera using [Video4Linux](https://en.wikipedia.org/wiki/Video4Linux) API. Linux kernel headers must be installed.
### FFmpeg
`WITH_FFMPEG` (default: _ON_)
Integration with [FFmpeg](https://en.wikipedia.org/wiki/FFmpeg) library for decoding and encoding video files and network streams. This library can read and write many popular video formats. It consists of several components which must be installed as prerequisites for the build:
- _avcodec_
- _avformat_
- _avutil_
- _swscale_
- _avresample_ (optional)
Exception is Windows platform where a prebuilt [plugin library containing FFmpeg](https://github.com/opencv/opencv_3rdparty/tree/ffmpeg/master) will be downloaded during a configuration stage and copied to the `bin` folder with all produced libraries.
@note [Libav](https://en.wikipedia.org/wiki/Libav) library can be used instead of FFmpeg, but this combination is not actively supported.
### GStreamer
`WITH_GSTREAMER` (default: _ON_)
Enable integration with [GStreamer](https://en.wikipedia.org/wiki/GStreamer) library for decoding and encoding video files, capturing frames from cameras and network streams. Numerous plugins can be installed to extend supported formats list. OpenCV allows running arbitrary GStreamer pipelines passed as strings to @ref cv::VideoCapture and @ref cv::VideoWriter objects.
Various GStreamer plugins offer HW-accelerated video processing on different platforms.
### Microsoft Media Foundation
`WITH_MSMF` (Windows; default: _ON_)
Enables MSMF backend which uses Windows' built-in [Media Foundation framework](https://en.wikipedia.org/wiki/Media_Foundation). Can be used to capture frames from camera, decode and encode video files. This backend have HW-accelerated processing support (`WITH_MSMF_DXVA` option, default is _ON_).
@note Older versions of Windows (prior to 10) can have incompatible versions of Media Foundation and are known to have problems when used from OpenCV.
### DirectShow
`WITH_DSHOW` (Windows; default: _ON_)
This backend uses older [DirectShow](https://en.wikipedia.org/wiki/DirectShow) framework. It can be used only to capture frames from camera. It is now deprecated in favor of MSMF backend, although both can be enabled in the same build.
### AVFoundation
`WITH_AVFOUNDATION` (Apple; default: _ON_)
[AVFoundation](https://en.wikipedia.org/wiki/AVFoundation) framework is part of Apple platforms and can be used to capture frames from camera, encode and decode video files.
### Other backends
There are multiple less popular frameworks which can be used to read and write videos. Each requires corresponding library or SDK installed.
| Option | Default | Description |
| ------ | ------- | ----------- |
| `WITH_1394` | _ON_ | [IIDC IEEE1394](https://en.wikipedia.org/wiki/IEEE_1394#IIDC) support using DC1394 library |
| `WITH_OPENNI` | _OFF_ | [OpenNI](https://en.wikipedia.org/wiki/OpenNI) can be used to capture data from depth-sensing cameras. Deprecated. |
| `WITH_OPENNI2` | _OFF_ | [OpenNI2](https://structure.io/openni) can be used to capture data from depth-sensing cameras. |
| `WITH_PVAPI` | _OFF_ | [PVAPI](https://www.alliedvision.com/en/support/software-downloads.html) is legacy SDK for Prosilica GigE cameras. Deprecated. |
| `WITH_ARAVIS` | _OFF_ | [Aravis](https://github.com/AravisProject/aravis) library is used for video acquisition using Genicam cameras. |
| `WITH_XIMEA` | _OFF_ | [XIMEA](https://www.ximea.com/) cameras support. |
| `WITH_XINE` | _OFF_ | [XINE](https://en.wikipedia.org/wiki/Xine) library support. |
| `WITH_LIBREALSENSE` | _OFF_ | [RealSense](https://en.wikipedia.org/wiki/Intel_RealSense) cameras support. |
| `WITH_MFX` | _OFF_ | [MediaSDK](http://mediasdk.intel.com/) library can be used for HW-accelerated decoding and encoding of raw video streams. |
| `WITH_GPHOTO2` | _OFF_ | [GPhoto](https://en.wikipedia.org/wiki/GPhoto) library can be used to capure frames from cameras. |
| `WITH_ANDROID_MEDIANDK` | _ON_ | [MediaNDK](https://developer.android.com/ndk/guides/stable_apis#libmediandk) library is available on Android since API level 21. |
### videoio plugins
Some _videoio_ backends can be built as plugins thus breaking strict dependency on third-party libraries and making them optional at runtime. Following options can be used to control this mechanism:
| Option | Default | Description |
| --------| ------ | ------- |
| `VIDEOIO_ENABLE_PLUGINS` | _ON_ | Enable or disable plugins completely. |
| `VIDEOIO_PLUGIN_LIST` | _empty_ | Comma- or semicolon-separated list of backend names to be compiled as plugins. Supported names are _ffmpeg_, _gstreamer_, _msmf_, _mfx_ and _all_. |
| `VIDEOIO_ENABLE_STRICT_PLUGIN_CHECK` | _ON_ | Enable strict runtime version check to only allow plugins built with the same version of OpenCV. |
## Parallel processing {#tutorial_config_reference_func_core}
Some of OpenCV algorithms can use multithreading to accelerate processing. OpenCV can be built with one of threading backends.
| Backend | Option | Default | Platform | Description |
|-------- | ------ | ------- | -------- | ----------- |
| pthreads | `WITH_PTHREADS_PF` | _ON_ | Unix-like | Default backend based on [pthreads](https://en.wikipedia.org/wiki/POSIX_Threads) library is available on Linux, Android and other Unix-like platforms. Thread pool is implemented in OpenCV and can be controlled with environment variables `OPENCV_THREAD_POOL_*`. Please check sources in _modules/core/src/parallel_impl.cpp_ file for details. |
| Concurrency | N/A | _ON_ | Windows | [Concurrency runtime](https://docs.microsoft.com/en-us/cpp/parallel/concrt/concurrency-runtime) is available on Windows and will be turned _ON_ on supported platforms unless other backend is enabled. |
| GCD | N/A | _ON_ | Apple | [Grand Central Dispatch](https://en.wikipedia.org/wiki/Grand_Central_Dispatch) is available on Apple platforms and will be turned _ON_ automatically unless other backend is enabled. Uses global system thread pool. |
| TBB | `WITH_TBB` | _OFF_ | Multiple | [Threading Building Blocks](https://en.wikipedia.org/wiki/Threading_Building_Blocks) is a cross-platform library for parallel programming. |
| OpenMP | `WITH_OPENMP` | _OFF_ | Multiple | [OpenMP](https://en.wikipedia.org/wiki/OpenMP) API relies on compiler support. |
| HPX | `WITH_HPX` | _OFF_ | Multiple | [High Performance ParallelX](https://en.wikipedia.org/wiki/HPX) is an experimental backend which is more suitable for multiprocessor environments. |
@note OpenCV can download and build TBB library from GitHub, this functionality can be enabled with the `BUILD_TBB` option.
## GUI backends (highgui module) {#tutorial_config_reference_highgui}
OpenCV relies on various GUI libraries for window drawing.
| Option | Default | Platform | Description |
| ------ | ------- | -------- | ----------- |
| `WITH_GTK` | _ON_ | Linux | [GTK](https://en.wikipedia.org/wiki/GTK) is a common toolkit in Linux and Unix-like OS-es. By default version 3 will be used if found, version 2 can be forced with the `WITH_GTK_2_X` option. |
| `WITH_WIN32UI` | _ON_ | Windows | [WinAPI](https://en.wikipedia.org/wiki/Windows_API) is a standard GUI API in Windows. |
| N/A | _ON_ | macOS | [Cocoa](https://en.wikipedia.org/wiki/Cocoa_(API)) is a framework used in macOS. |
| `WITH_QT` | _OFF_ | Cross-platform | [Qt](https://en.wikipedia.org/wiki/Qt_(software)) is a cross-platform GUI framework. |
@note OpenCV compiled with Qt support enables advanced _highgui_ interface, see @ref highgui_qt for details.
### OpenGL
`WITH_OPENGL` (default: _OFF_)
OpenGL integration can be used to draw HW-accelerated windows with following backends: GTK, WIN32 and Qt. And enables basic interoperability with OpenGL, see @ref core_opengl and @ref highgui_opengl for details.
## Deep learning neural networks inference backends and options (dnn module) {#tutorial_config_reference_dnn}
OpenCV have own DNN inference module which have own build-in engine, but can also use other libraries for optimized processing. Multiple backends can be enabled in single build. Selection happens at runtime automatically or manually.
| Option | Default | Description |
| ------ | ------- | ----------- |
| `WITH_PROTOBUF` | _ON_ | Enables [protobuf](https://en.wikipedia.org/wiki/Protocol_Buffers) library search. OpenCV can either build own copy of the library or use external one. This dependency is required by the _dnn_ module, if it can't be found module will be disabled. |
| `BUILD_PROTOBUF` | _ON_ | Build own copy of _protobuf_. Must be disabled if you want to use external library. |
| `PROTOBUF_UPDATE_FILES` | _OFF_ | Re-generate all .proto files. _protoc_ compiler compatible with used version of _protobuf_ must be installed. |
| `OPENCV_DNN_OPENCL` | _ON_ | Enable built-in OpenCL inference backend. |
| `WITH_INF_ENGINE` | _OFF_ | Enables [Intel Inference Engine (IE)](https://github.com/openvinotoolkit/openvino) backend. Allows to execute networks in IE format (.xml + .bin). Inference Engine must be installed either as part of [OpenVINO toolkit](https://en.wikipedia.org/wiki/OpenVINO), either as a standalone library built from sources. |
| `INF_ENGINE_RELEASE` | _2020040000_ | Defines version of Inference Engine library which is tied to OpenVINO toolkit version. Must be a 10-digit string, e.g. _2020040000_ for OpenVINO 2020.4. |
| `WITH_NGRAPH` | _OFF_ | Enables Intel NGraph library support. This library is part of Inference Engine backend which allows executing arbitrary networks read from files in multiple formats supported by OpenCV: Caffe, TensorFlow, PyTorch, Darknet, etc.. NGraph library must be installed, it is included into Inference Engine. |
| `OPENCV_DNN_CUDA` | _OFF_ | Enable CUDA backend. [CUDA](https://en.wikipedia.org/wiki/CUDA), CUBLAS and [CUDNN](https://developer.nvidia.com/cudnn) must be installed. |
| `WITH_HALIDE` | _OFF_ | Use experimental [Halide](https://en.wikipedia.org/wiki/Halide_(programming_language)) backend which can generate optimized code for dnn-layers at runtime. Halide must be installed. |
| `WITH_VULKAN` | _OFF_ | Enable experimental [Vulkan](https://en.wikipedia.org/wiki/Vulkan_(API)) backend. Does not require additional dependencies, but can use external Vulkan headers (`VULKAN_INCLUDE_DIRS`). |
| `WITH_TENGINE` | _OFF_ | Enable experimental [Tengine](https://github.com/OAID/Tengine) backend for ARM CPUs. Tengine library must be installed. |
# Installation layout {#tutorial_config_reference_install}
## Installation root {#tutorial_config_reference_install_root}
To install produced binaries root location should be configured. Default value depends on distribution, in Ubuntu it is usually set to `/usr/local`. It can be changed during configuration:
```.sh
cmake -DCMAKE_INSTALL_PREFIX=/opt/opencv ../opencv
```
This path can be relative to current working directory, in the following example it will be set to `<absolute-path-to-build>/install`:
```.sh
cmake -DCMAKE_INSTALL_PREFIX=install ../opencv
```
After building the library, all files can be copied to the configured install location using the following command:
```.sh
cmake --build . --target install
```
To install binaries to the system location (e.g. `/usr/local`) as a regular user it is necessary to run the previous command with elevated privileges:
```.sh
sudo cmake --build . --target install
```
@note
On some platforms (Linux) it is possible to remove symbol information during install. Binaries will become 10-15% smaller but debugging will be limited:
```.sh
cmake --build . --target install/strip
```
## Components and locations {#tutorial_config_reference_install_comp}
Options cane be used to control whether or not a part of the library will be installed:
| Option | Default | Description |
| ------ | ------- | ----------- |
| `INSTALL_C_EXAMPLES` | _OFF_ | Install C++ sample sources from the _samples/cpp_ directory. |
| `INSTALL_PYTHON_EXAMPLES` | _OFF_ | Install Python sample sources from the _samples/python_ directory. |
| `INSTALL_ANDROID_EXAMPLES` | _OFF_ | Install Android sample sources from the _samples/android_ directory. |
| `INSTALL_BIN_EXAMPLES` | _OFF_ | Install prebuilt sample applications (`BUILD_EXAMPLES` must be enabled). |
| `INSTALL_TESTS` | _OFF_ | Install tests (`BUILD_TESTS` must be enabled). |
| `OPENCV_INSTALL_APPS_LIST` | _all_ | Comma- or semicolon-separated list of prebuilt applications to install (from _apps_ directory) |
Following options allow to modify components' installation locations relatively to install prefix. Default values of these options depend on platform and other options, please check the _cmake/OpenCVInstallLayout.cmake_ file for details.
| Option | Components |
| ------ | ----------- |
| `OPENCV_BIN_INSTALL_PATH` | applications, dynamic libraries (_win_) |
| `OPENCV_TEST_INSTALL_PATH` | test applications |
| `OPENCV_SAMPLES_BIN_INSTALL_PATH` | sample applications |
| `OPENCV_LIB_INSTALL_PATH` | dynamic libraries, import libraries (_win_) |
| `OPENCV_LIB_ARCHIVE_INSTALL_PATH` | static libraries |
| `OPENCV_3P_LIB_INSTALL_PATH` | 3rdparty libraries |
| `OPENCV_CONFIG_INSTALL_PATH` | cmake config package |
| `OPENCV_INCLUDE_INSTALL_PATH` | header files |
| `OPENCV_OTHER_INSTALL_PATH` | extra data files |
| `OPENCV_SAMPLES_SRC_INSTALL_PATH` | sample sources |
| `OPENCV_LICENSES_INSTALL_PATH` | licenses for included 3rdparty components |
| `OPENCV_TEST_DATA_INSTALL_PATH` | test data |
| `OPENCV_DOC_INSTALL_PATH` | documentation |
| `OPENCV_JAR_INSTALL_PATH` | JAR file with Java bindings |
| `OPENCV_JNI_INSTALL_PATH` | JNI part of Java bindings |
| `OPENCV_JNI_BIN_INSTALL_PATH` | Dynamic libraries from the JNI part of Java bindings |
Following options can be used to change installation layout for common scenarios:
| Option | Default | Description |
| ------ | ------- | ----------- |
| `INSTALL_CREATE_DISTRIB` | _OFF_ | Tune multiple things to produce Windows and Android distributions. |
| `INSTALL_TO_MANGLED_PATHS` | _OFF_ | Adds one level to several installation locations to allow side-by-side installations. For example, headers will be installed to _/usr/include/opencv-4.4.0_ instead of _/usr/include/opencv4_ with this option enabled. |
# Miscellaneous features {#tutorial_config_reference_misc}
| Option | Default | Description |
| ------ | ------- | ----------- |
| `OPENCV_ENABLE_NONFREE` | _OFF_ | Some algorithms included in the library are known to be protected by patents and are disabled by default. |
| `OPENCV_FORCE_3RDPARTY_BUILD`| _OFF_ | Enable all `BUILD_` options at once. |
| `ENABLE_CCACHE` | _ON_ (on Unix-like platforms) | Enable [ccache](https://en.wikipedia.org/wiki/Ccache) auto-detection. This tool wraps compiler calls and caches results, can significantly improve re-compilation time. |
| `ENABLE_PRECOMPILED_HEADERS` | _ON_ (for MSVC) | Enable precompiled headers support. Improves build time. |
| `BUILD_DOCS` | _OFF_ | Enable documentation build (_doxygen_, _doxygen_cpp_, _doxygen_python_, _doxygen_javadoc_ targets). [Doxygen](http://www.doxygen.org/index.html) must be installed for C++ documentation build. Python and [BeautifulSoup4](https://en.wikipedia.org/wiki/Beautiful_Soup_(HTML_parser)) must be installed for Python documentation build. Javadoc and Ant must be installed for Java documentation build (part of Java SDK). |
| `ENABLE_PYLINT` | _ON_ (when docs or examples are enabled) | Enable python scripts check with [Pylint](https://en.wikipedia.org/wiki/Pylint) (_check_pylint_ target). Pylint must be installed. |
| `ENABLE_FLAKE8` | _ON_ (when docs or examples are enabled) | Enable python scripts check with [Flake8](https://flake8.pycqa.org/) (_check_flake8_ target). Flake8 must be installed. |
| `BUILD_JAVA` | _ON_ | Enable Java wrappers build. Java SDK and Ant must be installed. |
| `BUILD_FAT_JAVA_LIB` | _ON_ (for static Android builds) | Build single _opencv_java_ dynamic library containing all library functionality bundled with Java bindings. |
| `BUILD_opencv_python2` | _ON_ | Build python2 bindings (deprecated). Python with development files and numpy must be installed. |
| `BUILD_opencv_python3` | _ON_ | Build python3 bindings. Python with development files and numpy must be installed. |
TODO: need separate tutorials covering bindings builds
## Automated builds
Some features have been added specifically for automated build environments, like continuous integration and packaging systems.
| Option | Default | Description |
| ------ | ------- | ----------- |
| `ENABLE_NOISY_WARNINGS` | _OFF_ | Enables several compiler warnings considered _noisy_, i.e. having less importance than others. These warnings are usually ignored but in some cases can be worth being checked for. |
| `OPENCV_WARNINGS_ARE_ERRORS` | _OFF_ | Treat compiler warnings as errors. Build will be halted. |
| `ENABLE_CONFIG_VERIFICATION` | _OFF_ | For each enabled dependency (`WITH_` option) verify that it has been found and enabled (`HAVE_` variable). By default feature will be silently turned off if dependency was not found, but with this option enabled cmake configuration will fail. Convenient for packaging systems which require stable library configuration not depending on environment fluctuations. |
| `OPENCV_CMAKE_HOOKS_DIR` | _empty_ | OpenCV allows to customize configuration process by adding custom hook scripts at each stage and substage. cmake scripts with predefined names located in the directory set by this variable will be included before and after various configuration stages. Examples of file names: _CMAKE_INIT.cmake_, _PRE_CMAKE_BOOTSTRAP.cmake_, _POST_CMAKE_BOOTSTRAP.cmake_, etc.. Other names are not documented and can be found in the project cmake files by searching for the _ocv_cmake_hook_ macro calls. |
| `OPENCV_DUMP_HOOKS_FLOW` | _OFF_ | Enables a debug message print on each cmake hook script call. |
# Other non-documented options
`BUILD_ANDROID_PROJECTS`
`BUILD_ANDROID_EXAMPLES`
`ANDROID_HOME`
`ANDROID_SDK`
`ANDROID_NDK`
`ANDROID_SDK_ROOT`
`CMAKE_TOOLCHAIN_FILE`
`WITH_CAROTENE`
`WITH_CPUFEATURES`
`WITH_EIGEN`
`WITH_OPENVX`
`WITH_CLP`
`WITH_DIRECTX`
`WITH_VA`
`WITH_LAPACK`
`WITH_QUIRC`
`BUILD_ZLIB`
`BUILD_ITT`
`WITH_IPP`
`BUILD_IPP_IW`

View File

@@ -0,0 +1,71 @@
Cross referencing OpenCV from other Doxygen projects {#tutorial_cross_referencing}
====================================================
@prev_tutorial{tutorial_transition_guide}
| | |
| -: | :- |
| Original author | Sebastian Höffner |
| Compatibility | OpenCV >= 3.3.0 |
@warning
This tutorial can contain obsolete information.
Cross referencing OpenCV
------------------------
[Doxygen](http://www.doxygen.nl) is a tool to generate
documentations like the OpenCV documentation you are reading right now.
It is used by a variety of software projects and if you happen to use it
to generate your own documentation, and you are using OpenCV inside your
project, this short tutorial is for you.
Imagine this warning inside your documentation code:
@code
/**
* @warning This functions returns a cv::Mat.
*/
@endcode
Inside your generated documentation this warning will look roughly like this:
@warning This functions returns a %cv::Mat.
While inside the OpenCV documentation the `%cv::Mat` is rendered as a link:
@warning This functions returns a cv::Mat.
To generate links to the OpenCV documentation inside your project, you only
have to perform two small steps. First download the file
[opencv.tag](opencv.tag) (right-click and choose "save as...") and place it
somewhere in your project directory, for example as
`docs/doxygen-tags/opencv.tag`.
Open your Doxyfile using your favorite text editor and search for the key
`TAGFILES`. Change it as follows:
@code
TAGFILES = ./docs/doxygen-tags/opencv.tag=http://docs.opencv.org/4.5.2
@endcode
If you had other definitions already, you can append the line using a `\`:
@code
TAGFILES = ./docs/doxygen-tags/libstdc++.tag=https://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen \
./docs/doxygen-tags/opencv.tag=http://docs.opencv.org/4.5.2
@endcode
Doxygen can now use the information from the tag file to link to the OpenCV
documentation. Rebuild your documentation right now!
@note To allow others to also use a *.tag file to link to your documentation,
set `GENERATE_TAGFILE = html/your_project.tag`. Your documentation will now
contain a `your_project.tag` file in its root directory.
References
----------
- [Doxygen: Linking to external documentation](http://www.doxygen.nl/manual/external.html)
- [opencv.tag](opencv.tag)

View File

@@ -0,0 +1,103 @@
Cross compilation for ARM based Linux systems {#tutorial_arm_crosscompile_with_cmake}
=============================================
@prev_tutorial{tutorial_macos_install}
@next_tutorial{tutorial_building_tegra_cuda}
| | |
| -: | :- |
| Original author | Alexander Smorkalov |
| Compatibility | OpenCV >= 3.0 |
@warning
This tutorial can contain obsolete information.
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/opencv/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/opencv/opencv)
In Linux it can be achieved with the following command in Terminal:
@code{.bash}
cd ~/<my_working _directory>
git clone https://github.com/opencv/opencv.git
@endcode
Building OpenCV
---------------
-# 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
-# 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.

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 500 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 248 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 195 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 258 KiB

View File

@@ -0,0 +1,338 @@
Introduction to Java Development {#tutorial_java_dev_intro}
================================
@prev_tutorial{tutorial_windows_visual_studio_image_watch}
@next_tutorial{tutorial_java_eclipse}
| | |
| -: | :- |
| Original author | Eric Christiansen and Andrey Pavlenko |
| Compatibility | OpenCV >= 3.0 |
@warning
This tutorial can contain obsolete information.
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 tutorial_java_eclipse. For further reading after this guide, look at
the @ref tutorial_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/opencv/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/opencv/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.
![](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:
@include samples/java/ant/build.xml
@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
("${ocvJarDir}" in line 5 and "${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:
![](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:
![](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:
![](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:
![](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:
![](images/sbt_run_face.png)
It should also write the following image to `faceDetection.png`:
![](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,134 @@
Getting Started with Images {#tutorial_display_image}
===========================
@prev_tutorial{tutorial_building_tegra_cuda}
@next_tutorial{tutorial_documentation}
| | |
| -: | :- |
| Original author | Ana Huamán |
| Compatibility | OpenCV >= 3.4.4 |
@warning
This tutorial can contain obsolete information.
Goal
----
In this tutorial you will learn how to:
- Read an image from file (using @ref cv::imread)
- Display an image in an OpenCV window (using @ref cv::imshow)
- Write an image to a file (using @ref cv::imwrite)
Source Code
-----------
@add_toggle_cpp
- **Downloadable code**: Click
[here](https://github.com/opencv/opencv/tree/master/samples/cpp/tutorial_code/introduction/display_image/display_image.cpp)
- **Code at glance:**
@include samples/cpp/tutorial_code/introduction/display_image/display_image.cpp
@end_toggle
@add_toggle_python
- **Downloadable code**: Click
[here](https://github.com/opencv/opencv/tree/master/samples/python/tutorial_code/introduction/display_image/display_image.py)
- **Code at glance:**
@include samples/python/tutorial_code/introduction/display_image/display_image.py
@end_toggle
Explanation
-----------
@add_toggle_cpp
In OpenCV 3 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:
- @ref core "core" section, as here are defined the basic building blocks of the library
- @ref imgcodecs "imgcodecs" module, which provides functions for reading and writing
- @ref highgui "highgui" module, as this contains the functions to show an image in a window
We also include the *iostream* to facilitate console line output and input.
By declaring `using namespace cv;`, in the following, the library functions can be accessed without explicitly stating the namespace.
@snippet cpp/tutorial_code/introduction/display_image/display_image.cpp includes
@end_toggle
@add_toggle_python
As a first step, the OpenCV python library is imported.
The proper way to do this is to additionally assign it the name *cv*, which is used in the following to reference the library.
@snippet samples/python/tutorial_code/introduction/display_image/display_image.py imports
@end_toggle
Now, let's analyze the main code.
As a first step, we read the image "starry_night.jpg" from the OpenCV samples.
In order to do so, a call to the @ref cv::imread function loads the image using the file path specified by the first argument.
The second argument is optional and specifies the format in which we want the image. This may be:
- IMREAD_COLOR loads the image in the BGR 8-bit format. This is the **default** that is used here.
- IMREAD_UNCHANGED loads the image as is (including the alpha channel if present)
- IMREAD_GRAYSCALE loads the image as an intensity one
After reading in the image data will be stored in a @ref cv::Mat object.
@add_toggle_cpp
@snippet cpp/tutorial_code/introduction/display_image/display_image.cpp imread
@end_toggle
@add_toggle_python
@snippet samples/python/tutorial_code/introduction/display_image/display_image.py imread
@end_toggle
@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.
Afterwards, a check is executed, if the image was loaded correctly.
@add_toggle_cpp
@snippet cpp/tutorial_code/introduction/display_image/display_image.cpp empty
@end_toggle
@add_toggle_python
@snippet samples/python/tutorial_code/introduction/display_image/display_image.py empty
@end_toggle
Then, the image is shown using a call to the @ref cv::imshow function.
The first argument is the title of the window and the second argument is the @ref cv::Mat object that will be shown.
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.
The return value is the key that was pressed.
@add_toggle_cpp
@snippet cpp/tutorial_code/introduction/display_image/display_image.cpp imshow
@end_toggle
@add_toggle_python
@snippet samples/python/tutorial_code/introduction/display_image/display_image.py imshow
@end_toggle
In the end, the image is written to a file if the pressed key was the "s"-key.
For this the cv::imwrite function is called that has the file path and the cv::Mat object as an argument.
@add_toggle_cpp
@snippet cpp/tutorial_code/introduction/display_image/display_image.cpp imsave
@end_toggle
@add_toggle_python
@snippet samples/python/tutorial_code/introduction/display_image/display_image.py imsave
@end_toggle

View File

@@ -0,0 +1,695 @@
Writing documentation for OpenCV {#tutorial_documentation}
================================
@prev_tutorial{tutorial_display_image}
@next_tutorial{tutorial_transition_guide}
| | |
| -: | :- |
| Original author | Maksim Shabunin |
| Compatibility | OpenCV >= 3.0 |
@tableofcontents
Doxygen overview {#tutorial_documentation_overview}
================
Intro {#tutorial_documentation_intro}
-----
[Doxygen] is documentation generation system with a lot of great features, such as:
- parse program sources to produce actual and accurate documentation
- check documentation for errors
- insert images and formulas
- use markdown syntax and plain HTML for precise text formatting
- generate documentation in many different formats
OpenCV library existing documentation has been converted to doxygen format.
Installation {#tutorial_documentation_install}
------------
Please, check official [download][Doxygen download] and [installation][Doxygen installation] pages.
Some linux distributions can also provide doxygen packages.
Generate documentation {#tutorial_documentation_generate}
----------------------
- Get the OpenCV sources (version 3.0 and later)
- _Optional:_ get the OpenCV_contrib sources
- Create build directory near the sources folder(s) and go into it
- Run cmake (assuming you put sources to _opencv_ folder):
@code{.sh}
cmake -DBUILD_DOCS=ON ../opencv
@endcode
Or if you get contrib sources too:
@code{.sh}
cmake -DBUILD_DOCS=ON -DOPENCV_EXTRA_MODULES_PATH=../opencv_contrib/modules ../opencv
@endcode
- Run make:
@code{.sh}
make doxygen
@endcode
- Open <i>doc/doxygen/html/index.html</i> file in your favorite browser
- Test your Python code:
@code{.sh}
make check_pylint
@endcode
@note [Pylint](https://www.pylint.org/#install) must be installed before running cmake to be
able to test Python code. You can install using your system's package manager, or with pip:
@code{.sh} pip install pylint @endcode
Quick start {#tutorial_documentation_quick_start}
===========
@note These instructions are specific to OpenCV library documentation, other projects can use
different layout scheme and documenting agreements.
Documentation locations {#tutorial_documentation_quick_start_1}
-----------------------
Whole documentation is gathered from many different places:
- __source code__ entities, like classes, functions or enumerations, should be documented in
corresponding header files, right prior entity definition. See examples in next sections.
- __pages__ are good place to put big pieces of text with images and code examples not directly
connected with any source code entity. Pages should be located in separate files and
contained in several predefined places. This tutorial is example of such page.
- __images__ can be used to illustrate described things. Usually located at the same places as pages,
images can be inserted to any place of the documentation.
- __code examples__ show how to use the library in real applications. Each sample is
self-contained file which represents one simple application. Parts of these files can be
included into documentation and tutorials to demonstrate function calls and objects collaboration.
- __BibTeX references__ are used to create one common bibliography. All science books, articles and
proceedings served as basis for library functionality should be put in this reference list.
Following scheme represents common documentation places for _opencv_ repository:
~~~
<opencv>
├── doc - doxygen config files, root page (root.markdown.in), BibTeX file (opencv.bib)
│   ├── tutorials - tutorials hierarchy (pages and images)
│   └── py_tutorials - python tutorials hierarchy (pages and images)
├── modules
│   └── <modulename>
│      ├── doc - documentation pages and images for module
│      └── include - code documentation in header files
└── samples - place for all code examples
├── cpp
│ └── tutorial_code - place for tutorial code examples
└── ...
~~~
@note Automatic code parser looks for all header files (<i>".h, .hpp"</i> except for <i>".inl.hpp;
.impl.hpp; _detail.hpp"</i>) in _include_ folder and its subfolders. Some module-specific
instructions (group definitions) and documentation should be put into
<i>"include/opencv2/<module-name>.hpp"</i> file.
@note You can put C++ template implementation and specialization to separate files
(<i>".impl.hpp"</i>) ignored by doxygen.
@note Files in _src_ subfolder are not parsed, because documentation is intended mostly for the
library users, not developers. But it still is possible to generate full documentation by
customizing processed files list in cmake script (<i>doc/CMakeLists.txt</i>) and doxygen options in
its configuration file (<i>doc/Doxyfile.in</i>).
Since version 3.0 all new modules are placed into _opencv_contrib_ repository, it has slightly
different layout:
~~~
<opencv_contrib>
└── modules
└── <modulename>
├── doc - documentation pages and images, BibTeX file (<modulename>.bib)
├── include - code documentation in header files
├── samples - place for code examples for documentation and tutorials
└── tutorials - tutorial pages and images
~~~
Example {#tutorial_documentation_quick_start_2}
-------
To add documentation for functions, classes and other entities, just insert special comment prior
its definition. Like this:
@verbatim
/** @brief Calculates the exponent of every array element.
The function exp calculates the exponent of every element of the input array:
\f[ \texttt{dst} [I] = e^{ src(I) } \f]
The maximum relative error is about 7e-6 for single-precision input and less than 1e-10 for
double-precision input. Currently, the function converts denormalized values to zeros on output.
Special values (NaN, Inf) are not handled.
@param src input array.
@param dst output array of the same size and type as src.
@sa log , cartToPolar , polarToCart , phase , pow , sqrt , magnitude
*/
CV_EXPORTS_W void exp(InputArray src, OutputArray dst);
@endverbatim
Here you can see:
- special C-comment syntax denotes it is doxygen comment
@verbatim /** ... */ @endverbatim
- command `brief` denotes following paragraph is a brief description
@verbatim @brief @endverbatim
- empty line denotes paragraph end
- TeX formula between `f[` and `f]` commands
@verbatim \f[ ... \f] @endverbatim
- command `param` denotes following word is name of the parameter and following text is
description of the parameter; all parameters are placed in a list
@verbatim @param @endverbatim
- command `sa` starts "See also" paragraph containing references to some classes, methods, pages or URLs.
@verbatim @sa @endverbatim
Produced reference item looks like this:
![Reference link](doxygen-2.png)
The "More..." link brings you to the function documentation:
![Function documentation](doxygen-1.png)
Another example {#tutorial_documentation_quick_start_3}
---------------
Different comment syntax can be used for one-line short comments:
@verbatim
//! type of line
enum LineTypes {
FILLED = -1,
LINE_4 = 4, //!< 4-connected line
LINE_8 = 8, //!< 8-connected line
LINE_AA = 16 //!< antialiased line
};
@endverbatim
Here:
- special C++-comment syntax denotes it is doxygen comment
@verbatim //! @endverbatim
- additional symbol `<` denotes this comment is located _after_ documented entity
@verbatim //!< @endverbatim
Produced documentation block looks like this:
![Enumeration documentation](doxygen-3.png)
More details {#tutorial_documentation_quick_start_4}
------------
### Command prefix
Doxygen commands starts with `@` or `\` sign:
@verbatim
@brief ...
or
\brief ...
@endverbatim
### Comment syntax
Doxygen comment can have different forms:
@verbatim
C-style:
/** ... */
or
/*! ... */
C++-style
//! ...
or
/// ...
Lines can start with '*':
/**
* ...
* ...
*/
Can be placed after documented entity:
//!< ...
/**< ... */
@endverbatim
### Paragraph end
To end paragraph, insert empty line or any command starting new paragraph:
@verbatim
@brief brief description paragraph
brief continues
new paragraph
@note new note paragraph
note paragraph continues
another paragraph
paragraph continues
@endverbatim
### Naming
Pages, anchors, groups and other named entities should have unique name inside the whole project.
It is a good idea to prefix such identifiers with module name:
@verbatim
@page core_explanation_1 Usage explanation
@defgroup imgproc_transform Image transformations
@anchor mymodule_interesting_note
@endverbatim
Supported Markdown {#tutorial_documentation_quick_start_md}
------------------
Doxygen supports Markdown formatting with some extensions. Short syntax reference is described
below, for details visit [Markdown support].
### lists {#tutorial_documentation_md_list}
@verbatim
Bulleted:
- item1
- item2
Numbered:
1. item1
2. item2
or
-# item1
-# item2
@endverbatim
### emphasis {#tutorial_documentation_md_emph}
@verbatim
_italic_
__bold__
use html in complex cases:
<em>"path/to/file"</em>
@endverbatim
### links {#tutorial_documentation_md_links}
@verbatim
explicit link:
[OpenCV main site](http://opencv.org)
automatic links:
<http://opencv.org>
or even:
http://opencv.org
@endverbatim
### images {#tutorial_documentation_md_image}
@verbatim
![image caption](image path)
@endverbatim
### headers {#tutorial_documentation_md_head}
@verbatim
Level1
======
Level2
------
### Level3
#### Level4
@endverbatim
### header id {#tutorial_documentation_md_headid}
You can assign a unique identifier to any header to reference it from other places.
@verbatim
Header {#some_unique_identifier}
------
...
See @ref some_unique_identifier for details
@endverbatim
### page id {#tutorial_documentation_md_page}
Each page should have additional Level1 header at the beginning with page title and identifier:
@verbatim
Writing documentation for OpenCV {#tutorial_documentation}
================================
@endverbatim
### tables {#tutorial_documentation_md_table}
Example from doxygen documentation:
@verbatim
First Header | Second Header
------------- | -------------
Content Cell | Content Cell
Content Cell | Content Cell
@endverbatim
Commonly used commands {#tutorial_documentation_quick_start_5}
----------------------
Most often used doxygen commands are described here with short examples. For the full list of
available commands and detailed description, please visit [Command reference].
### Basic commands {#tutorial_documentation_commands_basic}
- __brief__ - paragraph with brief entity description
- __param__ - description of function argument.
Multiple adjacent statements are merged into one list. If argument with this name is not found
in actual function signature - doxygen warning will be produced. Function can have either _no_
documented parameters, either _all_ should be documented.
- __sa__ - "See also" paragraph, contains references to classes, functions, pages or URLs
- __note__ - visually highlighted "Note" paragraph. Multiple adjacent statements are merged into
one block.
- __return, returns__ - describes returned value of a function
- __overload__ - adds fixed text to the function description: <em>"This is an overloaded member
function, provided for convenience. It differs from the above function only in what argument(s)
it accepts."</em>
- __anchor__ - places invisible named anchor, which can be referenced by `ref` command. It can be
used in pages only.
- __ref__ - explicit reference to a named section, page or anchor.
If such entity can not be found - doxygen warning will be generated. This command has an
optional argument - link text.
Doxygen also generates some links automatically: if text contains word which can be found in
documented entities - reference will be generated. This functionality can be disabled by prefixing
the word with `%` symbol.
@verbatim
Explicit reference: @ref MyClass
Explicit named reference: @ref example_page "Example page"
Implicit reference: cv::abc::MyClass1 or just MyClass1
Disable implicit reference: %MyClass1
@endverbatim
- __f__ - formula
Inline formulas are bounded with `f$` command:
@verbatim
\f$ ... \f$
@endverbatim
Block formulas - with `f[` and `f]` commands:
@verbatim
\f[ ... \f]
@endverbatim
### Code inclusion commands {#tutorial_documentation_commands_include}
To mark some text as a code in documentation, _code_ and _endcode_ commands are used.
@verbatim
@code
float val = img.at<float>(borderInterpolate(100, img.rows, cv::BORDER_REFLECT_101),
borderInterpolate(-5, img.cols, cv::BORDER_WRAP));
@endcode
@endverbatim
Syntax will be highlighted according to the currently parsed file type (C++ for <em>.hpp</em>, C for <em>.h</em>) or
you can manually specify it in curly braces:
@verbatim
@code{.xml}
@endverbatim
To include whole example file into documentation, _include_ and _includelineno_ commands are used.
The file is searched in common samples locations, so you can specify just its name or short part of
the path. The _includelineno_ version also shows line numbers but prevents copy-pasting since
the line numbers are included.
@verbatim
@include samples/cpp/test.cpp
@endverbatim
If you want to include some parts of existing example file - use _snippet_ command.
First, mark the needed parts of the file with special doxygen comments:
@verbatim
//! [var_init]
int a = 0;
//! [var_init]
@endverbatim
Then include this snippet into documentation:
@verbatim
@snippet samples/cpp/test.cpp var_init
@endverbatim
@note Currently most of such partial inclusions are made with _dontinclude_ command for
compatibility with the old rST documentation. But newly created samples should be included with the
_snippet_ command, since this method is less affected by the changes in processed file.
### Toggle buttons inclusion commands {#tutorial_documentation_toggle_buttons_commands_include}
Toggle buttons are used to display the selected configuration (e.g. programming language, OS, IDE).
To use the buttons in documentation, _add_toggle_ and _end_toggle_ commands are used.
The command _add_toggle_ can be
- general: _add_toggle{Button Name}_
- for C++: _add_toggle_cpp_
- for Java: _add_toggle_java_
- for Python: _add_toggle_python_
Example:
@verbatim
@add_toggle{Button Name}
text / code / doxygen commands
@end_toggle
@endverbatim
For example using toggle buttons with text and [code](@ref tutorial_documentation_commands_include) snippets:
@verbatim
### Buttons Example
@add_toggle_cpp
Text for C++ button
@snippet samples/cpp/tutorial_code/introduction/documentation/documentation.cpp hello_world
@end_toggle
@add_toggle_java
Text for Java button
@snippet samples/java/tutorial_code/introduction/documentation/Documentation.java hello_world
@end_toggle
@add_toggle_python
Text for Python button
@snippet samples/python/tutorial_code/introduction/documentation/documentation.py hello_world
@end_toggle
@endverbatim
Result looks like this:
### Buttons Example
@add_toggle_cpp
Text for C++ button
@snippet samples/cpp/tutorial_code/introduction/documentation/documentation.cpp hello_world
@end_toggle
@add_toggle_java
Text for Java button
@snippet samples/java/tutorial_code/introduction/documentation/Documentation.java hello_world
@end_toggle
@add_toggle_python
Text for Python button
@snippet samples/python/tutorial_code/introduction/documentation/documentation.py hello_world
@end_toggle
As you can see, the buttons are added automatically under the previous heading.
### Grouping commands {#tutorial_documentation_commands_group}
All code entities should be put into named groups representing OpenCV modules and their internal
structure, thus each module should be associated with a group with the same name. Good place to
define groups and subgroups is the main header file for this module:
<em>"<module>/include/opencv2/<module>.hpp"</em>.
@note Doxygen groups are called "modules" and are shown on "Modules" page.
@verbatim
/**
@defgroup mymodule My great module
optional description
@{
@defgroup mymodule_basic Basic operations
optional description
@defgroup mymodule_experimental Experimental operations
optional description
@}
*/
@endverbatim
To put classes and functions into specific group, just add `ingroup` command to its documentation,
or wrap the whole code block with `addtogroup` command:
@verbatim
/** @brief Example function
@ingroup mymodule
*/
or
/**
@addtogroup mymodule_experimental
@{
*/
... several functions, classes or enumerations here
/**
@}
*/
@endverbatim
### Publication reference {#tutorial_documentation_commands_cite}
Use _cite_ command to insert reference to related publications listed in @ref citelist page.
First, add publication BibTeX record into <i>"<opencv>/doc/opencv.bib"</i> or
<i>"<opencv_contrib>/modules/<module>/doc/<module>.bib"</i> file:
@verbatim
@ARTICLE{Bradski98,
author = {Bradski, Gary R},
title = {Computer vision face tracking for use in a perceptual user interface},
year = {1998},
publisher = {Citeseer}
}
@endverbatim
@note Try not to add publication duplicates because it can confuse documentation readers and writers later.
Then make reference with _cite_ command:
@verbatim
@cite Bradski98
@endverbatim
@note To get BibTeX record for the publications one can use [Google Scholar]. Once the publication
have been found - follow its "Cite" link and then choose "BibTeX" option:
![](scholarship_cite_dialog.png)
Step-by-step {#tutorial_documentation_steps}
============
Steps described in this section can be used as checklist during documentation writing. It is not
necessary to do things in the same order, but some steps really depend on previous. And of course
these steps are just basic guidelines, there is always a place for creativity.
Document the function {#tutorial_documentation_steps_fun}
---------------------
1. Add empty doxygen comment preceding function definition.
2. Add _brief_ command with short description of function meaning at the beginning.
3. Add detailed description of the function.
4. _Optional_: insert formulas, images and blocks of example code to illustrate complex cases
5. _Optional_: describe each parameter using the _param_ command.
6. _Optional_: describe return value of the function using the _returns_ command.
7. _Optional_: add "See also" section with links to similar functions or classes
8. _Optional_: add bibliographic reference if any.
9. Test your code. (Python: "make check_pylint")
10. Generate doxygen documentation and verify results.
Write the tutorial {#tutorial_documentation_steps_tutorial}
------------------
1. Formulate the idea to be illustrated in the tutorial.
2. Make the example application, simple enough to be understood by a beginning developer. Be
laconic and write descriptive comments, don't try to avoid every possible runtime error or to make
universal utility. Your goal is to illustrate the idea. And it should fit one source file!
If you want to insert code blocks from this file into your tutorial, mark them with special doxygen comments (see [here](@ref tutorial_documentation_commands_include)).
If you want to write the tutorial in more than one programming language, use the toggle buttons for alternative comments and code (see [here](@ref tutorial_documentation_toggle_buttons_commands_include)).
3. Collect results of the application work. It can be "before/after" images or some numbers
representing performance or even a video.
Save it in appropriate format for later use in the tutorial:
- To save simple graph-like images use lossless ".png" format.
- For photo-like images - lossy ".jpg" format.
- Numbers will be inserted as plain text, possibly formatted as table.
- Video should be uploaded on YouTube.
4. Create new tutorial page (<em>".markdown"</em>-file) in corresponding location (see
[here](@ref tutorial_documentation_quick_start_1)), and place all image files near it (or in "images"
subdirectory). Also put your example application file and make sure it is compiled together with the
OpenCV library when `-DBUILD_EXAMPLES=ON` option is enabled on cmake step.
5. Modify your new page:
- Add page title and identifier, usually prefixed with <em>"tutorial_"</em> (see [here](@ref tutorial_documentation_md_page)).
You can add a link to the previous and next tutorial using the identifier
@verbatim
@prev_tutorial{identifier}
@next_tutorial{identifier}
@endverbatim
@warning Do **not** write the **hashtag (#)**, example: \n Incorrect: @verbatim @prev_tutorial{#tutorial_documentation} @endverbatim Correct: @verbatim @prev_tutorial{tutorial_documentation} @endverbatim
- Add brief description of your idea and tutorial goals.
- Describe your program and/or its interesting pieces.
- Describe your results, insert previously added images or other results.
To add a youtube video, e.g. www.youtube.com/watch?v= **ViPN810E0SU**, use _youtube_{**Video ID**}:
@verbatim
@youtube{ViPN810E0SU}
@endverbatim
- Add bibliographic references if any (see [here](@ref tutorial_documentation_commands_cite)).
6. Add newly created tutorial to the corresponding table of contents. Just find
<em>"table_of_content_*.markdown"</em> file with the needed table and place new record in it
similar to existing ones.
It is simply a list item with special _subpage_ command which marks your page as a
child and places it into the existing pages hierarchy. Also note the list item indent, empty lines between
paragraphs and special _italic_ markers.
7. Generate doxygen documentation and verify results.
References {#tutorial_documentation_refs}
==========
- [Doxygen] - main Doxygen page
- [Documenting basics] - how to include documentation in code
- [Markdown support] - supported syntax and extensions
- [Formulas support] - how to include formulas
- [Supported formula commands] - HTML formulas use MathJax script for rendering
- [Command reference] - supported commands and their parameters
<!-- invisible references list -->
[Doxygen]: http://www.doxygen.nl
[Doxygen download]: http://doxygen.nl/download.html
[Doxygen installation]: http://doxygen.nl/manual/install.html
[Documenting basics]: http://www.doxygen.nl/manual/docblocks.html
[Markdown support]: http://www.doxygen.nl/manual/markdown.html
[Formulas support]: http://www.doxygen.nl/manual/formulas.html
[Supported formula commands]: http://docs.mathjax.org/en/latest/input/tex/macros/index.html
[Command reference]: http://www.doxygen.nl/manual/commands.html
[Google Scholar]: http://scholar.google.ru/

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

View File

@@ -0,0 +1,119 @@
OpenCV installation overview {#tutorial_general_install}
============================
@next_tutorial{tutorial_config_reference}
@tableofcontents
There are two ways of installing OpenCV on your machine: download prebuilt version for your platform or compile from sources.
# Prebuilt version {#tutorial_general_install_prebuilt}
In many cases you can find prebuilt version of OpenCV that will meet your needs.
## Packages by OpenCV core team {#tutorial_general_install_prebuilt_core}
Packages for Android, iOS and Windows built with default parameters and recent compilers are published for each release, they do not contain _opencv_contrib_ modules.
- GitHub releases: https://github.com/opencv/opencv/releases
- SourceForge.net: https://sourceforge.net/projects/opencvlibrary/files/
## Third-party packages {#tutorial_general_install_prebuilt_thirdparty}
Other organizations and people maintain their own binary distributions of OpenCV. For example:
- System packages in popular Linux distributions (https://pkgs.org/search/?q=opencv)
- PyPI (https://pypi.org/search/?q=opencv)
- Conda (https://anaconda.org/search?q=opencv)
- Conan (https://github.com/conan-community/conan-opencv)
- vcpkg (https://github.com/microsoft/vcpkg/tree/master/ports/opencv)
- NuGet (https://www.nuget.org/packages?q=opencv)
- Brew (https://formulae.brew.sh/formula/opencv)
- Maven (https://search.maven.org/search?q=opencv)
# Build from sources {#tutorial_general_install_sources}
It can happen that existing binary packages are not applicable for your use case, then you'll have to build custom version of OpenCV by yourself. This section gives a high-level overview of the build process, check tutorial for specific platform for actual build instructions.
OpenCV uses [CMake](https://cmake.org/) build management system for configuration and build, so this section mostly describes generalized process of building software with CMake.
## Step 0: Prerequisites {#tutorial_general_install_sources_0}
Install C++ compiler and build tools. On \*NIX platforms it is usually GCC/G++ or Clang compiler and Make or Ninja build tool. On Windows it can be Visual Studio IDE or MinGW-w64 compiler. Native toolchains for Android are provided in the Android NDK. XCode IDE is used to build software for OSX and iOS platforms.
Install CMake from the official site or some other source.
Get other third-party dependencies: libraries with extra functionality like decoding videos or showing GUI elements; libraries providing optimized implementations of selected algorithms; tools used for documentation generation and other extras. Check @ref tutorial_config_reference for available options and corresponding dependencies.
## Step 1: Get software sources {#tutorial_general_install_sources_1}
Typical software project consists of one or several code repositories. OpenCV have two repositories with code: _opencv_ - main repository with stable and actively supported algorithms and _opencv_contrib_ which contains experimental and non-free (patented) algorithms; and one repository with test data: _opencv_extra_.
You can download a snapshot of repository in form of an archive or clone repository with full history.
To download snapshot archives:
- Go to https://github.com/opencv/opencv/releases and download "Source code" archive from any release.
- (optionally) Go to https://github.com/opencv/opencv_contrib/releases and download "Source code" archive for the same release as _opencv_
- (optionally) Go to https://github.com/opencv/opencv_extra/releases and download "Source code" archive for the same release as _opencv_
- Unpack all archives to some location
To clone repositories run the following commands in console (_git_ [must be installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)):
```.sh
git clone https://github.com/opencv/opencv
git -C opencv checkout <some-tag>
# optionally
git clone https://github.com/opencv/opencv_contrib
git -C opencv_contrib checkout <same-tag-as-opencv>
# optionally
git clone https://github.com/opencv/opencv_extra
git -C opencv_extra checkout <same-tag-as-opencv>
```
@note
If you want to build software using more than one repository, make sure all components are compatible with each other. For OpenCV it means that _opencv_ and _opencv_contrib_ repositories must be checked out at the same tag or that all snapshot archives are downloaded from the same release.
@note
When choosing which version to download take in account your target platform and development tools versions, latest versions of OpenCV can have build problems with very old compilers and vice versa. We recommend using latest release and fresh OS/compiler combination.
## Step 2: Configure {#tutorial_general_install_sources_2}
At this step CMake will verify that all necessary tools and dependencies are available and compatible with the library and will generate intermediate files for the chosen build system. It could be Makefiles, IDE projects and solutions, etc. Usually this step is performed in newly created build directory:
```
cmake -G<generator> <configuration-options> <source-directory>
```
@note
`cmake-gui` application allows to see and modify available options using graphical user interface. See https://cmake.org/runningcmake/ for details.
## Step 3: Build {#tutorial_general_install_sources_3}
During build process source files are compiled into object files which are linked together or otherwise combined into libraries and applications. This step can be run using universal command:
```
cmake --build <build-directory> <build-options>
```
... or underlying build system can be called directly:
```
make
```
## Step 3: Install {#tutorial_general_install_sources_4}
During installation procedure build results and other files from build directory will be copied to the install location. Default installation location is `/usr/local` on UNIX and `C:/Program Files` on Windows. This location can be changed at the configuration step by setting `CMAKE_INSTALL_PREFIX` option. To perform installation run the following command:
```
cmake --build <build-directory> --target install <other-options>
```
@note
This step is optional, OpenCV can be used directly from the build directory.
@note
If the installation root location is a protected system directory, so the installation process must be run with superuser or administrator privileges (e.g. `sudo cmake ...`).

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

View File

@@ -0,0 +1,112 @@
Using OpenCV Java with Eclipse {#tutorial_java_eclipse}
==============================
@prev_tutorial{tutorial_java_dev_intro}
@next_tutorial{tutorial_clojure_dev_intro}
| | |
| -: | :- |
| Original author | Barış Evrim Demiröz |
| Compatibility | OpenCV >= 3.0 |
@warning
This tutorial can contain obsolete information.
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/releases.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.
![](images/1-window-preferences.png)
Navigate under Java --\> Build Path --\> User Libraries and click New....
![](images/2-user-library-new.png)
Enter a name, e.g. OpenCV-2.4.6, for your new library.
![](images/3-library-name.png)
Now select your new user library and click Add External JARs....
![](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....
![](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.
![](images/6-external-folder.png)
Your user library configuration should look like this:
![](images/7-user-library-final.png)
Testing the configuration on a new Java project
-----------------------------------------------
Now start creating a new Java project.
![](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.
![](images/8-add-library.png)
![](images/9-select-user-lib.png)
Libraries should look like this:
![](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.
![](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 :)
Running Java code with OpenCV and MKL dependency
------------------------------------------------
You may get the following error (e.g. on Ubuntu) if you have built OpenCV with MKL library with some Java code that calls OpenCV functions
that use Intel MKL:
> Intel MKL FATAL ERROR: Cannot load libmkl_avx2.so or libmkl_def.so.
One solution to solve this on Linux consists in preloading the Intel MKL library (either run the command in a terminal or add it to your `.bashrc` file).
Your command line should be something similar to this (add `$LD_PRELOAD:` before if you have already set the `LD_PRELOAD` variable):
> export LD_PRELOAD=/opt/intel/mkl/lib/intel64/libmkl_core.so:/opt/intel/mkl/lib/intel64/libmkl_sequential.so
Then, run the Eclipse IDE from a terminal that have this environment variable set (`echo $LD_PRELOAD`) and the error should disappear.

Some files were not shown because too many files have changed in this diff Show More