fixed doc/tutorials/introduction/android_binary_package/dev_with_OCV_on_Android.rst
[profile/ivi/opencv.git] / doc / tutorials / introduction / android_binary_package / dev_with_OCV_on_Android.rst
1
2 .. _dev_with_OCV_on_Android:
3
4 Android Development with OpenCV
5 *******************************
6
7 This tutorial has been created to help you use OpenCV library within your Android project.
8
9 This guide was written with Windows 7 in mind, though it should work with any other OS supported by
10 OpenCV4Android SDK.
11
12 This tutorial assumes you have the following installed and configured:
13
14 * JDK
15
16 * Android SDK and NDK
17
18 * Eclipse IDE
19
20 * ADT and CDT plugins for Eclipse
21
22      ..
23
24 If you need help with anything of the above, you may refer to our :ref:`android_dev_intro` guide.
25
26 This tutorial also assumes you have OpenCV4Android SDK already installed on your development
27 machine and OpenCV Manager on your testing device correspondingly. If you need help with any of
28 these, you may consult our :ref:`O4A_SDK` tutorial.
29
30 If you encounter any error after thoroughly following these steps, feel free to contact us via
31 `OpenCV4Android <https://groups.google.com/group/android-opencv/>`_ discussion group or OpenCV
32 `Q&A forum <http://answers.opencv.org>`_ . We'll do our best to help you out.
33
34
35 Using OpenCV Library Within Your Android Project
36 ================================================
37
38 In this section we will explain how to make some existing project to use OpenCV.
39 Starting with 2.4.2 release for Android, *OpenCV Manager* is used to provide apps with the best
40 available version of OpenCV.
41 You can get more information here: :ref:`Android_OpenCV_Manager` and in these
42 `slides <https://docs.google.com/a/itseez.com/presentation/d/1EO_1kijgBg_BsjNp2ymk-aarg-0K279_1VZRcPplSuk/present#slide=id.p>`_.
43
44
45 Java
46 ----
47
48 Application Development with Async Initialization
49 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
50
51 Using async initialization is a **recommended** way for application development. It uses the OpenCV
52 Manager to access OpenCV libraries externally installed in the target system.
53
54 #. Add OpenCV library project to your workspace. Use menu
55    :guilabel:`File -> Import -> Existing project in your workspace`.
56
57    Press :guilabel:`Browse`  button and locate OpenCV4Android SDK
58    (:file:`OpenCV-2.4.8-android-sdk/sdk`).
59
60    .. image:: images/eclipse_opencv_dependency0.png
61         :alt: Add dependency from OpenCV library
62         :align: center
63
64 #. In application project add a reference to the OpenCV Java SDK in
65    :guilabel:`Project -> Properties -> Android -> Library -> Add` select ``OpenCV Library - 2.4.8``.
66
67    .. image:: images/eclipse_opencv_dependency1.png
68         :alt: Add dependency from OpenCV library
69         :align: center
70
71 In most cases OpenCV Manager may be installed automatically from Google Play. For the case, when
72 Google Play is not available, i.e. emulator, developer board, etc, you can install it manually
73 using adb tool. See :ref:`manager_selection` for details.
74
75 There is a very base code snippet implementing the async initialization. It shows basic principles.
76 See the "15-puzzle" OpenCV sample for details.
77
78 .. code-block:: java
79     :linenos:
80
81     public class Sample1Java extends Activity implements CvCameraViewListener {
82
83         private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
84             @Override
85             public void onManagerConnected(int status) {
86                 switch (status) {
87                     case LoaderCallbackInterface.SUCCESS:
88                     {
89                         Log.i(TAG, "OpenCV loaded successfully");
90                         mOpenCvCameraView.enableView();
91                     } break;
92                     default:
93                     {
94                         super.onManagerConnected(status);
95                     } break;
96                 }
97             }
98         };
99
100         @Override
101         public void onResume()
102         {
103             super.onResume();
104             OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_6, this, mLoaderCallback);
105         }
106
107         ...
108     }
109
110 It this case application works with OpenCV Manager in asynchronous fashion. ``OnManagerConnected``
111 callback will be called in UI thread, when initialization finishes. Please note, that it is not
112 allowed to use OpenCV calls or load OpenCV-dependent native libs before invoking this callback.
113 Load your own native libraries that depend on OpenCV after the successful OpenCV initialization.
114 Default ``BaseLoaderCallback`` implementation treat application context as Activity and calls
115 ``Activity.finish()`` method to exit in case of initialization failure. To override this behavior
116 you need to override ``finish()`` method of ``BaseLoaderCallback`` class and implement your own
117 finalization method.
118
119
120 Application Development with Static Initialization
121 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
122
123 According to this approach all OpenCV binaries are included into your application package. It is
124 designed mostly for development purposes. This approach is deprecated for the production code,
125 release package is recommended to communicate with OpenCV Manager via the async initialization
126 described above.
127
128 #. Add the OpenCV library project to your workspace the same way as for the async initialization
129    above. Use menu :guilabel:`File -> Import -> Existing project in your workspace`,
130    press :guilabel:`Browse` button and select OpenCV SDK path
131    (:file:`OpenCV-2.4.8-android-sdk/sdk`).
132
133    .. image:: images/eclipse_opencv_dependency0.png
134         :alt: Add dependency from OpenCV library
135         :align: center
136
137 #. In the application project add a reference to the OpenCV4Android SDK in
138    :guilabel:`Project -> Properties -> Android -> Library -> Add` select ``OpenCV Library - 2.4.8``;
139
140    .. image:: images/eclipse_opencv_dependency1.png
141        :alt: Add dependency from OpenCV library
142        :align: center
143
144 #. If your application project **doesn't have a JNI part**, just copy the corresponding OpenCV
145    native libs from :file:`<OpenCV-2.4.8-android-sdk>/sdk/native/libs/<target_arch>` to your
146    project directory to folder :file:`libs/<target_arch>`.
147
148    In case of the application project **with a JNI part**, instead of manual libraries copying you
149    need to modify your ``Android.mk`` file:
150    add the following two code lines after the ``"include $(CLEAR_VARS)"`` and before
151    ``"include path_to_OpenCV-2.4.8-android-sdk/sdk/native/jni/OpenCV.mk"``
152
153    .. code-block:: make
154       :linenos:
155
156       OPENCV_CAMERA_MODULES:=on
157       OPENCV_INSTALL_MODULES:=on
158
159    The result should look like the following:
160
161    .. code-block:: make
162       :linenos:
163
164       include $(CLEAR_VARS)
165
166       # OpenCV
167       OPENCV_CAMERA_MODULES:=on
168       OPENCV_INSTALL_MODULES:=on
169       include ../../sdk/native/jni/OpenCV.mk
170
171    After that the OpenCV libraries will be copied to your application :file:`libs` folder during
172    the JNI build.v
173
174    Eclipse will automatically include all the libraries from the :file:`libs` folder to the
175    application package (APK).
176
177 #. The last step of enabling OpenCV in your application is Java initialization code before calling
178    OpenCV API. It can be done, for example, in the static section of the ``Activity`` class:
179
180    .. code-block:: java
181       :linenos:
182
183       static {
184           if (!OpenCVLoader.initDebug()) {
185               // Handle initialization error
186           }
187       }
188
189    If you application includes other OpenCV-dependent native libraries you should load them
190    **after** OpenCV initialization:
191
192    .. code-block:: java
193       :linenos:
194
195       static {
196           if (!OpenCVLoader.initDebug()) {
197               // Handle initialization error
198           } else {
199               System.loadLibrary("my_jni_lib1");
200               System.loadLibrary("my_jni_lib2");
201           }
202       }
203
204
205 Native/C++
206 ----------
207
208 To build your own Android application, using OpenCV as native part, the following steps should be
209 taken:
210
211 #. You can use an environment variable to specify the location of OpenCV package or just hardcode
212    absolute or relative path in the :file:`jni/Android.mk` of your projects.
213
214 #.  The file :file:`jni/Android.mk` should be written for the current application using the common
215     rules for this file.
216
217     For detailed information see the Android NDK documentation from the Android NDK archive, in the
218     file :file:`<path_where_NDK_is_placed>/docs/ANDROID-MK.html`.
219
220 #. The following line:
221
222    .. code-block:: make
223
224       include C:\Work\OpenCV4Android\OpenCV-2.4.8-android-sdk\sdk\native\jni\OpenCV.mk
225
226    Should be inserted into the :file:`jni/Android.mk` file **after** this line:
227
228    .. code-block:: make
229
230       include $(CLEAR_VARS)
231
232 #. Several variables can be used to customize OpenCV stuff, but you **don't need** to use them when
233    your application uses the `async initialization` via the `OpenCV Manager` API.
234
235    .. note:: These variables should be set **before**  the ``"include .../OpenCV.mk"`` line:
236
237              .. code-block:: make
238
239                 OPENCV_INSTALL_MODULES:=on
240
241    Copies necessary OpenCV dynamic libs to the project ``libs`` folder in order to include them
242    into the APK.
243
244    .. code-block:: make
245
246       OPENCV_CAMERA_MODULES:=off
247
248    Skip native OpenCV camera related libs copying to the project ``libs`` folder.
249
250    .. code-block:: make
251
252       OPENCV_LIB_TYPE:=STATIC
253
254    Perform static linking with OpenCV. By default dynamic link is used and the project JNI lib
255    depends on ``libopencv_java.so``.
256
257 #. The file :file:`Application.mk` should exist and should contain lines:
258
259    .. code-block:: make
260
261       APP_STL := gnustl_static
262       APP_CPPFLAGS := -frtti -fexceptions
263
264    Also, the line like this one:
265
266    .. code-block:: make
267
268       APP_ABI := armeabi-v7a
269
270    Should specify the application target platforms.
271
272    In some cases a linkage error (like ``"In function 'cv::toUtf16(std::basic_string<...>...
273    undefined reference to 'mbstowcs'"``) happens when building an application JNI library,
274    depending on OpenCV. The following line in the :file:`Application.mk` usually fixes it:
275
276    .. code-block:: make
277
278       APP_PLATFORM := android-9
279
280
281 #. Either use :ref:`manual <NDK_build_cli>` ``ndk-build`` invocation or
282    :ref:`setup Eclipse CDT Builder <CDT_Builder>` to build native JNI lib before (re)building the Java
283    part and creating an APK.
284
285
286 Hello OpenCV Sample
287 ===================
288
289 Here are basic steps to guide you trough the process of creating a simple OpenCV-centric
290 application. It will be capable of accessing camera output, processing it and displaying the
291 result.
292
293 #. Open Eclipse IDE, create a new clean workspace, create a new Android project
294    :menuselection:`File --> New --> Android Project`
295
296 #. Set name, target, package and ``minSDKVersion`` accordingly. The minimal SDK version for build
297    with OpenCV4Android SDK is 11. Minimal device API Level (for application manifest) is 8.
298
299 #. Allow Eclipse to create default activity. Lets name the activity ``HelloOpenCvActivity``.
300
301 #. Choose Blank Activity with full screen layout. Lets name the layout ``HelloOpenCvLayout``.
302
303 #. Import OpenCV library project to your workspace.
304
305 #. Reference OpenCV library within your project properties.
306
307    .. image:: images/dev_OCV_reference.png
308         :alt: Reference OpenCV library.
309         :align: center
310
311 #. Edit your layout file as xml file and pass the following layout there:
312
313     .. code-block:: xml
314         :linenos:
315
316         <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
317             xmlns:tools="http://schemas.android.com/tools"
318             xmlns:opencv="http://schemas.android.com/apk/res-auto"
319             android:layout_width="match_parent"
320             android:layout_height="match_parent" >
321
322             <org.opencv.android.JavaCameraView
323                 android:layout_width="fill_parent"
324                 android:layout_height="fill_parent"
325                 android:visibility="gone"
326                 android:id="@+id/HelloOpenCvView"
327                 opencv:show_fps="true"
328                 opencv:camera_id="any" />
329
330         </LinearLayout>
331
332 #. Add the following permissions to the :file:`AndroidManifest.xml` file:
333
334    .. code-block:: xml
335       :linenos:
336
337       </application>
338
339       <uses-permission android:name="android.permission.CAMERA"/>
340
341       <uses-feature android:name="android.hardware.camera" android:required="false"/>
342       <uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/>
343       <uses-feature android:name="android.hardware.camera.front" android:required="false"/>
344       <uses-feature android:name="android.hardware.camera.front.autofocus" android:required="false"/>
345
346 #. Set application theme in AndroidManifest.xml to hide title and system buttons.
347
348    .. code-block:: xml
349       :linenos:
350
351       <application
352           android:icon="@drawable/icon"
353           android:label="@string/app_name"
354           android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >
355
356 #. Add OpenCV library initialization to your activity. Fix errors by adding requited imports.
357
358     .. code-block:: java
359        :linenos:
360
361        private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
362            @Override
363            public void onManagerConnected(int status) {
364                switch (status) {
365                    case LoaderCallbackInterface.SUCCESS:
366                    {
367                        Log.i(TAG, "OpenCV loaded successfully");
368                        mOpenCvCameraView.enableView();
369                    } break;
370                    default:
371                    {
372                        super.onManagerConnected(status);
373                    } break;
374                }
375            }
376        };
377
378        @Override
379        public void onResume()
380        {
381            super.onResume();
382            OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_6, this, mLoaderCallback);
383        }
384
385 #. Defines that your activity implements ``CvCameraViewListener2`` interface and fix activity related
386    errors by defining missed methods. For this activity define ``onCreate``, ``onDestroy`` and
387    ``onPause`` and implement them according code snippet bellow. Fix errors by adding requited
388    imports.
389
390    .. code-block:: java
391       :linenos:
392
393        private CameraBridgeViewBase mOpenCvCameraView;
394
395        @Override
396        public void onCreate(Bundle savedInstanceState) {
397            Log.i(TAG, "called onCreate");
398            super.onCreate(savedInstanceState);
399            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
400            setContentView(R.layout.HelloOpenCvLayout);
401            mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.HelloOpenCvView);
402            mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
403            mOpenCvCameraView.setCvCameraViewListener(this);
404        }
405
406        @Override
407        public void onPause()
408        {
409            super.onPause();
410            if (mOpenCvCameraView != null)
411                mOpenCvCameraView.disableView();
412        }
413
414        public void onDestroy() {
415            super.onDestroy();
416            if (mOpenCvCameraView != null)
417                mOpenCvCameraView.disableView();
418        }
419
420        public void onCameraViewStarted(int width, int height) {
421        }
422
423        public void onCameraViewStopped() {
424        }
425
426        public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
427            return inputFrame.rgba();
428        }
429
430 #. Run your application on device or emulator.
431
432 Lets discuss some most important steps. Every Android application with UI must implement Activity
433 and View. By the first steps we create blank activity and default view layout. The simplest
434 OpenCV-centric application must implement OpenCV initialization, create its own view to show
435 preview from camera and implements ``CvCameraViewListener2`` interface to get frames from camera and
436 process it.
437
438 First of all we create our application view using xml layout. Our layout consists of the only
439 one full screen component of class ``org.opencv.android.JavaCameraView``. This class is
440 implemented inside OpenCV library. It is inherited from ``CameraBridgeViewBase``, that extends
441 ``SurfaceView`` and uses standard Android camera API. Alternatively you can use
442 ``org.opencv.android.NativeCameraView`` class, that implements the same interface, but uses
443 ``VideoCapture`` class as camera access back-end. ``opencv:show_fps="true"`` and
444 ``opencv:camera_id="any"`` options enable FPS message and allow to use any camera on device.
445 Application tries to use back camera first.
446
447 After creating layout we need to implement ``Activity`` class. OpenCV initialization process has
448 been already discussed above. In this sample we use asynchronous initialization. Implementation of
449 ``CvCameraViewListener`` interface allows you to add processing steps after frame grabbing from
450 camera and before its rendering on screen. The most important function is ``onCameraFrame``. It is
451 callback function and it is called on retrieving frame from camera. The callback input is object
452 of ``CvCameraViewFrame`` class that represents frame from camera.
453
454 .. note::
455     Do not save or use ``CvCameraViewFrame`` object out of ``onCameraFrame`` callback. This object
456     does not have its own state and its behavior out of callback is unpredictable!
457
458 It has ``rgba()`` and ``gray()`` methods that allows to get frame as RGBA and one channel gray scale
459 ``Mat`` respectively. It expects that ``onCameraFrame`` function returns RGBA frame that will be
460 drawn on the screen.