In the previous tutorial, we have demonstrated how to compile nonfree module in OpenCV into Android NDK libraries. In this article, I will show how to use JNI interface to call the NDK functions in the JAVA code of an Android applications. I will reuse some of the project files from the previous tutorial. The following is a step-by-step tutorial, in which we will build a simple Android application with only one "run demo" button, as is shown in the figure below. We still use SIFT as an example. The main program performing SIFT processing is almost the same as the one in the previous tutorial. I only made some necessary changes for the JNI interface. The demo application reads input image from "/sdcard/nonfree/img1.jpg", and write the output image to "sdcard/nonfree/img1_results.jpg". 1. Create new Android application project. Start Eclipse. Create an Android project: nonfree-jni-demo. The package name is com.example.nonfreejnidemo. 2. Create native JNI code files and makefiles In the Android application folder, create a folder "jni", which contains: Application.mk is the same as in the previous tutorial. We modified Android.mk, since after compiling the JNI code, we want a shared library. nonfree_jni.cpp file defines JNI interface. We also implement major SIFT processing here, in which we called OpenCV SIFT functions. 3. Compile libraries In the project root folder, type "ndk-build" to compile the libraries. After this step, you should be able to see three library files under \nonfree-jni-demo\libs\armeabi: 4. Create JNI interface class Add a new class NonfreeJNILib. 5. Implement the Android application. In the layout editor, add a button with text "Rum Demo". In MainActivity.java, we add event function for the click button to start the SIFT processing. Finally, add permission to write the external storage to the Android applications. Add the following code in AndroidManifest.xml. (without this, we cannot write the results image into sdcard. If you don't write card, you can skip this step) 6. Run the application. Create /sdcard/nonfree folder on your test device. adb push nonfree-jni-demo/img/img1.jpg into this folder. Then start the application. Click the "run demo" button, the SIFT processing will start. Since this is a simple demo, I didn't implement any multi-threading scheme. During the SIFT processing, the GUI of the application will freeze. You may want to use multi-threading and message passing in a real application to enhance the GUI experience. Once the processing is done, you will see the results on sdcard. You can also check some intermediate information using logcat. Resources: 2. If you only need SIFT in your project and don't need other functions from OpenCV, you can also consider EZSIFT. Find more information here: http://sourceforge.net/projects/ezsift/ |
Technical notes >