Android Application Programming With OpenCV 3 - Sample Chapter
Android Application Programming With OpenCV 3 - Sample Chapter
ee
P U B L I S H I N G
pl
C o m m u n i t y
E x p e r i e n c e
D i s t i l l e d
$ 29.99 US
19.99 UK
Sa
m
Joseph Howse
Joseph Howse
Joseph has authored OpenCV for Secret Agents, OpenCV Android Application
Programming, and OpenCV Computer Vision with Python. When he is not writing
books or grooming cats, Joseph provides consulting, training, and software
development services. His company is Nummist Media (http://nummist.com).
Preface
This book will show you how to use OpenCV in an Android app that displays a
camera feed, saves and shares photos, manipulates colors and edges, and tracks
real-world objects in 2D or 3D. Integration with OpenGL is also introduced so that
you can start building augmented reality (AR) apps that superimpose virtual 3D
scenes onto tracked objects in the camera feed.
OpenCV is an open-source, cross-platform library that provides building blocks
for computer vision experiments and applications. It offers high-level interfaces
to capture, process, and present image data. For example, it abstracts away details
about camera hardware and array allocation. OpenCV is widely used in both
academia and industry.
Android is a mobile operating system that is mostly open source. For Java developers,
it offers a high-level application framework called Android SDK. Android apps are
modular insofar as they have standard, high-level interfaces to launch each other and
share data. Mobility, a high level of abstraction, and data sharing are great starting
points for a photo sharing app, similar to the one we will build.
Although OpenCV and Android provide a lot of high-level abstractions (and a lot of
open source code for curious users to browse), they are not necessarily easy to use
for newcomers. Setting up an appropriate development environment and translating
the libraries' broad functionality into application features are both daunting tasks.
This concise book helps us by placing an emphasis on a clean setup, clean application
design, and a simple understanding of each function's purpose.
The need for a book on this subject is particularly great because OpenCV's Java
and Android bindings are quite new and their documentation is not yet mature.
Little has been written about the steps for integrating OpenCV with Android's
standard camera, media, and graphics APIs. Surely, integration is a major part
of an app developer's work, so it is a major focus of this book.
Preface
By the end of our journey together, you will have a taste of the breadth of application
features that are made possible by integrating OpenCV with other Android libraries.
You will have your own small library of reusable classes that you can extend or modify
for your future computer vision projects. You will have a development environment
and the knowledge to use it, and you will be able to make more apps!
Setting Up OpenCV
This chapter is a quick guide to setting up a development environment for Android
and OpenCV. We will also look at the OpenCV sample applications, documentation,
and community.
By the end of this chapter, our development environment will include the following
components:
Java Development Kit (JDK) 7: This includes tools for Java programming.
JDK 7 is the exact version that we require. The more recent version, JDK 8,
is not yet supported for Android development.
[1]
Setting Up OpenCV
There are many possible ways to install and configure these components. We
will cover several common setup scenarios, but if you are interested in further
options, see OpenCV's official documentation at http://docs.opencv.org/doc/
tutorials/introduction/android_binary_package/O4A_SDK.html.
System requirements
All the development tools for Android and OpenCV are cross-platform. The following
operating systems are supported with almost identical setup procedures:
Many other Unix-like systems (though not specifically covered in this book)
To run the OpenCV samples and, later on, our own application, we should have an
Android device with the following specifications:
Autofocus (recommended)
Android Virtual Devices (AVDs) are not recommended. Some parts of OpenCV rely
on low-level camera access and might fail with virtualized cameras.
[2]
Chapter 1
technetwork/java/javase/downloads/jdk7-downloads-1880260.html.
Alternatively, on Debian or Ubuntu, install Oracle JDK 7 from the WebUpd8
PPA, as described at https://launchpad.net/~webupd8team/+archive/
ubuntu/java. Although most Linux distributions have OpenJDK in their
standard repositories, Oracle JDK is recommended instead for Android
development.
Setting Up OpenCV
[4]
Chapter 1
http://sourceforge.net/projects/opencvlibrary/files/opencv-android/.
Look for files that have opencv-android in the name, such as OpenCV-3.0.0android-sdk.zip (the latest version at the time of writing). Download the latest
version and unzip it to any destination, which we will refer to as <opencv>.
[5]
Setting Up OpenCV
Git: This is a Source Control Management (SCM) tool, which we will use
to obtain OpenCV's source code. On Windows or Mac, download and install
Git from http://git-scm.com/. On Linux, install it using your package
manager. For example, on Debian or Ubuntu, open Terminal and run $ sudo
apt-get install git-core.
Apache Ant 1.8.0 or greater: This is a set of build tools for Java. On Linux,
just install Ant using your package manager. For example, on Debian
or Ubuntu, open Terminal and run $ sudo apt-get install ant.
On Windows or Mac, download Ant from http://ant.apache.org/
bindownload.cgi and unzip it to any destination, which we will refer to as
<ant>. Make the following changes to your environment variables:
Python 2.6 or greater (but not 3.0 or greater): This is a scripting language
that is used by some of the OpenCV build scripts. An appropriate version
of Python comes preinstalled on Mac and most Linux systems, including
Debian and Ubuntu. On Windows, download and install Python from
http://www.python.org/getit/. If you have installed multiple versions of
Python on your system, ensure that an installation of Python 2.6 or greater
(but not 3.0 or greater) is the only one in Path (Windows) or PATH (Unix).
The OpenCV build scripts do not run properly with Python 3.0 or greater.
[6]
Chapter 1
Once we have these prerequisites, we can download the OpenCV source code to any
location, which we will refer to as <opencv_source>. Then, we can build it using an
included script. Specifically, we should take the following steps:
On Windows, open Git Bash (Git's command prompt). On Mac, Debian, Ubuntu, or
other Unix-like systems, open Terminal (or another command-line shell).
Run these commands:
$ git clone git://code.opencv.org/opencv.git <opencv_source>
$ cd <opencv_source>/platforms
$ sh ./scripts/cmake_android_arm.sh
$ cd build_android_arm
$ make -j8
The j8 flag specifies that the make command will use 8 threads, which is typically
a good number for a quad-core processor. For a dual-core processor, a better choice
might be the j4 flag (4 threads).
If all goes well, we should get a build of OpenCV4Android in <opencv_source>/
platforms/build_android_arm. We can move it elsewhere if we wish. We will
refer to its final location as <opencv>.
You might wonder what the cmake_android_arm.sh build script is doing. Actually,
it just creates a build directory and runs a CMake command to populate the directory
with a particular configuration of OpenCV. Here are the entire contents of the script
file:
#!/bin/sh
cd `dirname $0`/..
mkdir -p build_android_arm
cd build_android_arm
cmake -DCMAKE_BUILD_WITH_INSTALL_RPATH=ON DCMAKE_TOOLCHAIN_FILE=../android/android.toolchain.cmake $@ ../..
Advanced users, who are familiar with CMake, might want to copy and modify this
script to create a custom configuration of OpenCV. Refer to the code in <opencv_
source>/CMakeLists.txt for definitions of OpenCV's CMake options.
[7]
Setting Up OpenCV
[8]
Chapter 1
Now, we should see a window with several panels, including Package Explorer.
If we are not using TAPD, we need to import the OpenCV sample projects into
our new workspace. Right-click on Package Explorer and select Import from
the context menu:
[9]
Setting Up OpenCV
The Import window should appear. Navigate to General | Existing Projects into
Workspace, and then click on Next >:
On the second page of the Import window enter <opencv> in the Select root
directory: field. Under the Projects: label, a list of detected projects should appear.
(If not, click on Refresh.) The list should include the OpenCV library, samples, and
tutorials. They should all be selected by default.
Downloading the example code
You can download the example code files from your account
at http://www.packtpub.com for all the Packt Publishing
books you purchased. If you purchased this book elsewhere,
you can visit http://www.packtpub.com/support and
register to have the files e-mailed directly to you.
[ 10 ]
Chapter 1
This means that Eclipse has found the OpenCV library, samples, and tutorials and
has recognized them as Eclipse projects. Do not select Copy projects into workspace
because the OpenCV sample and tutorial projects rely on a relative path to the
library project, and this relative path will not be preserved if the projects are copied
into the workspace. Click on Finish to import the projects:
[ 11 ]
Setting Up OpenCV
Once the projects are imported, we might need to fix some configuration issues.
Our development environment might have different paths and different versions
of Android SDK than the ones in the samples' default configuration:
Any resulting errors will be reported in the Problems tab. For likely solutions,
see the section Troubleshooting Eclipse projects, later in this chapter.
We should first resolve any errors in the OpenCV Library
project as the samples and tutorials depend on the library.
Once the OpenCV projects no longer show any errors, we can prepare to test them
on an Android device. Recall that the device must have Android 2.2 (Froyo) or greater
and a camera. To let Eclipse communicate with the device, we must enable the device's
USB debugging option. On the Android device, perform the following steps:
[ 12 ]
Chapter 1
[ 13 ]
Setting Up OpenCV
Plug the Android device into your computer's USB port. In Eclipse, select one of the
OpenCV sample projects in Package Explorer. Then, from the menu system, navigate
to Run | Run as | Android Application:
An Android Device Chooser window should appear. Your Android device should
be listed under Choose a running Android device. If the device is not listed, refer to
the section Troubleshooting the USB connection, later in this chapter.
[ 14 ]
Chapter 1
If the Auto Monitor Logcat window appears, select the Yes radio button and the
verbose drop-down option, and click on OK. This option ensures that all the log
output from the application will be visible in Eclipse:
[ 15 ]
Setting Up OpenCV
On the Android device, you might get a message: OpenCV library package was
not found! Try to install it? Make sure that the device is connected to the Internet
and then touch the Yes button on your device. The Play Store will open to show an
OpenCV package. Install the package and then press the hardware back button to
return to the sample application, which should be ready for use.
For OpenCV 3.0, the samples and tutorials have the following functionality:
Sample native-activity: This displays a camera feed using native (C++) code.
[ 16 ]
Chapter 1
Tutorial 1 Camera Preview: This displays a camera feed. The user can
press the menu to select a different camera feed implementation (Java or
native C++).
Tutorial 3 Camera Control: This applies filters to a camera feed, which has
a customizable resolution. The user can press the menu to select from a list
of filters and a list of resolutions.
[ 17 ]
Setting Up OpenCV
Feel free to browse the projects' source code via Package Explorer to see how they
were made. Alternatively, you might want to return to the official samples and
tutorials later, once we have built our own application over the course of this book.
[ 18 ]
Chapter 1
At compile time, OpenCV and its samples must target Android 3.0 (API level 11) or
greater, though at runtime they also support Android 2.2 (API level 8) or greater:
[ 19 ]
Setting Up OpenCV
[ 20 ]
Chapter 1
[ 21 ]
Setting Up OpenCV
Many connection problems are intermittent and can be resolved by restoring the
USB connection to an initial state. Try the following steps and, after each step,
test whether the problem is resolved:
1. Unplug the Android device from the host computer's USB port.
Then, plug it back in.
2. Disable and re-enable the device's USB debugging option, as described
earlier in the section Building the OpenCV samples with Eclipse.
3. On Mac or Linux, run the following command in Terminal (or another
command prompt):
sudo sh -c "adb kill-server && start-server"
Less commonly, connection problems might relate to drivers or permissions. A onetime setup process, as described next, should resolve such problems.
On Windows, we might need to manually install the USB drivers for the Android
device. Different vendors and devices have different drivers. The official Android
documentation provides links to the various vendors' driver download sites at
http://developer.android.com/tools/extras/oem-usb.html#Drivers.
On Linux, before connecting an Android device via USB, we might need to specify
the device's vendor in a permissions file. Each vendor has a unique ID number, as
listed in the official Android documentation at http://developer.android.com/
tools/device.html#VendorIds. We will refer to this ID number as <vendor_
id>. To create the permissions file, open a command prompt application (such as
Terminal) and run the following commands:
$ cd /etc/udev/rules.d/
$ sudo touch 51-android.rules
$ sudo chmod a+r 51-android-rules
Note that the permissions file needs to have root ownership, so we use sudo while
creating or modifying it. Now, open the file in an editor such as gedit:
$ sudo gedit 51-android-rules
For each vendor, append a new line to the file. Each of these lines should have the
following format:
SUBSYSTEM=="usb", ATTR{idVendor}=="<vendor_id>", MODE="0666",
GROUP="plugdev"
Chapter 1
Tutorials: http://docs.opencv.org/opencv_tutorials.pdf
If the documentation does not seem to answer your question, try talking to the
OpenCV community. Here are some sites where you will find helpful people:
Summary
By now, we should have an Android and OpenCV development environment that
can do everything we need for the application described in this book's remaining
chapters. Depending on the approach we took, we might also have a set of tools
that we can use to reconfigure and rebuild OpenCV for our future needs.
We know how to build the OpenCV Android samples in Eclipse. These samples
cover a different range of functionality to this book's project, but they are useful as
additional learning aids. We also know where to find the documentation and help.
Now that we have the necessary tools and reference materials to hand, our first
ambition as application developers is to control a camera! Throughout the next
chapter, we will use Android SDK and OpenCV to preview, capture, and share
photographs.
[ 23 ]
www.PacktPub.com
Stay Connected: