dev_with_OCV_on_Android.rst 16.9 KB
Newer Older
1 2 3

.. _dev_with_OCV_on_Android:

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 13 14 15 16 17 18 19 20 21 22 23 24 25

This tutorial assumes you have the following installed and configured:

* JDK

* Android SDK and NDK

* Eclipse IDE

* ADT and CDT plugins for Eclipse

     ..

If you need help with anything of the above, you may refer to our :ref:`android_dev_intro` guide.

26 27
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
28 29
these, you may consult our :ref:`O4A_SDK` tutorial.

30 31
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
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 39 40 41
In this section we will explain how to make some existing project to use OpenCV.
Starting with 2.4.2 release for Android, *OpenCV Manager* is used to provide apps with the best
available version of OpenCV.
You can get more information here: :ref:`Android_OpenCV_Manager` and in these
42 43
`slides <https://docs.google.com/a/itseez.com/presentation/d/1EO_1kijgBg_BsjNp2ymk-aarg-0K279_1VZRcPplSuk/present#slide=id.p>`_.

44 45 46

Java
----
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 53
Manager to access OpenCV libraries externally installed in the target system.

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.9-android-sdk/sdk`).
59 60 61 62 63

   .. image:: images/eclipse_opencv_dependency0.png
        :alt: Add dependency from OpenCV library
        :align: center

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.9``.
66 67 68 69 70

   .. image:: images/eclipse_opencv_dependency1.png
        :alt: Add dependency from OpenCV library
        :align: center

71 72
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
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 79 80

.. code-block:: java
    :linenos:

81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
    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()
102
        {
103
            super.onResume();
104
            OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_6, this, mLoaderCallback);
105
        }
106 107

        ...
108 109
    }

110 111 112 113 114 115 116
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
117
finalization method.
118

119 120

Application Development with Static Initialization
121 122
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

123 124 125
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
126
described above.
127

128 129 130
#. Add the OpenCV library project to your workspace the same way as for the async initialization
   above. Use menu :guilabel:`File -> Import -> Existing project in your workspace`,
   press :guilabel:`Browse` button and select OpenCV SDK path
131
   (:file:`OpenCV-2.4.9-android-sdk/sdk`).
132 133 134 135 136

   .. image:: images/eclipse_opencv_dependency0.png
        :alt: Add dependency from OpenCV library
        :align: center

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.9``;
139 140 141 142 143

   .. image:: images/eclipse_opencv_dependency1.png
       :alt: Add dependency from OpenCV library
       :align: center

144
#. If your application project **doesn't have a JNI part**, just copy the corresponding OpenCV
145
   native libs from :file:`<OpenCV-2.4.9-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.9-android-sdk/sdk/native/jni/OpenCV.mk"``
152 153

   .. code-block:: make
154 155 156 157
      :linenos:

      OPENCV_CAMERA_MODULES:=on
      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 167 168 169
      # OpenCV
      OPENCV_CAMERA_MODULES:=on
      OPENCV_INSTALL_MODULES:=on
      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 175
   Eclipse will automatically include all the libraries from the :file:`libs` folder to the
   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 181
   .. code-block:: java
      :linenos:
182

183 184 185 186 187
      static {
          if (!OpenCVLoader.initDebug()) {
              // Handle initialization error
          }
      }
188

189
   If you application includes other OpenCV-dependent native libraries you should load them
190
   **after** OpenCV initialization:
191

192 193
   .. code-block:: java
      :linenos:
194

195 196 197 198 199 200 201 202
      static {
          if (!OpenCVLoader.initDebug()) {
              // Handle initialization error
          } else {
              System.loadLibrary("my_jni_lib1");
              System.loadLibrary("my_jni_lib2");
          }
      }
203

204

205 206 207
Native/C++
----------

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 223

   .. code-block:: make

224
      include C:\Work\OpenCV4Android\OpenCV-2.4.9-android-sdk\sdk\native\jni\OpenCV.mk
225

226
   Should be inserted into the :file:`jni/Android.mk` file **after** this line:
227 228 229

   .. code-block:: make

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 245

   .. code-block:: make

246
      OPENCV_CAMERA_MODULES:=off
247 248 249 250 251

   Skip native OpenCV camera related libs copying to the project ``libs`` folder.

   .. code-block:: make

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 258 259 260

#. The file :file:`Application.mk` should exist and should contain lines:

   .. code-block:: make

261 262
      APP_STL := gnustl_static
      APP_CPPFLAGS := -frtti -fexceptions
263

264
   Also, the line like this one:
265 266 267

   .. code-block:: make

268
      APP_ABI := armeabi-v7a
269

270
   Should specify the application target platforms.
271

272 273
   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,
274
   depending on OpenCV. The following line in the :file:`Application.mk` usually fixes it:
275 276 277

   .. code-block:: make

278
      APP_PLATFORM := android-9
279 280


281 282
#. Either use :ref:`manual <NDK_build_cli>` ``ndk-build`` invocation or
   :ref:`setup Eclipse CDT Builder <CDT_Builder>` to build native JNI lib before (re)building the Java
283
   part and creating an APK.
284

285 286 287 288

Hello OpenCV Sample
===================

289 290
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
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 297
#. 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.
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 308 309
   .. image:: images/dev_OCV_reference.png
        :alt: Reference OpenCV library.
        :align: center
310

311
#. Edit your layout file as xml file and pass the following layout there:
312

313
    .. code-block:: xml
314 315
        :linenos:

316 317 318 319 320
        <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" >
321

322 323 324 325 326 327 328
            <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" />
329

330
        </LinearLayout>
331

332
#. Add the following permissions to the :file:`AndroidManifest.xml` file:
333

334
   .. code-block:: xml
335 336
      :linenos:

337
      </application>
338

339
      <uses-permission android:name="android.permission.CAMERA"/>
340

341 342 343 344
      <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"/>
345

346
#. Set application theme in AndroidManifest.xml to hide title and system buttons.
347

348 349 350
   .. code-block:: xml
      :linenos:

351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
      <application
          android:icon="@drawable/icon"
          android:label="@string/app_name"
          android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >

#. Add OpenCV library initialization to your activity. Fix errors by adding requited imports.

    .. code-block:: java
       :linenos:

       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;
               }
           }
       };
377

378 379 380 381
       @Override
       public void onResume()
       {
           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 387 388
   errors by defining missed methods. For this activity define ``onCreate``, ``onDestroy`` and
   ``onPause`` and implement them according code snippet bellow. Fix errors by adding requited
   imports.
389

390 391 392
   .. code-block:: java
      :linenos:

393
       private CameraBridgeViewBase mOpenCvCameraView;
394

395 396 397 398 399 400 401 402 403 404
       @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);
       }
405

406 407 408 409 410 411 412
       @Override
       public void onPause()
       {
           super.onPause();
           if (mOpenCvCameraView != null)
               mOpenCvCameraView.disableView();
       }
413

414 415 416 417 418
       public void onDestroy() {
           super.onDestroy();
           if (mOpenCvCameraView != null)
               mOpenCvCameraView.disableView();
       }
419

420 421
       public void onCameraViewStarted(int width, int height) {
       }
422

423 424
       public void onCameraViewStopped() {
       }
425

A
Alexander Smorkalov 已提交
426 427
       public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
           return inputFrame.rgba();
428 429 430 431 432 433 434
       }

#. 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
435
preview from camera and implements ``CvCameraViewListener2`` interface to get frames from camera and
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
process it.

First of all we create our application view using xml layout. Our layout consists of the only
one full screen component of class ``org.opencv.android.JavaCameraView``. This class is
implemented inside OpenCV library. It is inherited from ``CameraBridgeViewBase``, that extends
``SurfaceView`` and uses standard Android camera API. Alternatively you can use
``org.opencv.android.NativeCameraView`` class, that implements the same interface, but uses
``VideoCapture`` class as camera access back-end. ``opencv:show_fps="true"`` and
``opencv:camera_id="any"`` options enable FPS message and allow to use any camera on device.
Application tries to use back camera first.

After creating layout we need to implement ``Activity`` class. OpenCV initialization process has
been already discussed above. In this sample we use asynchronous initialization. Implementation of
``CvCameraViewListener`` interface allows you to add processing steps after frame grabbing from
camera and before its rendering on screen. The most important function is ``onCameraFrame``. It is
A
Alexander Smorkalov 已提交
451 452 453 454 455 456 457 458 459 460
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.