Showing posts with label OpenCV. Show all posts
Showing posts with label OpenCV. Show all posts

Friday, December 7, 2018

Use pkg-config with CMake

Say you want to build a binary which uses OpenCV library. For example, the following would be a typical command for compiling your program
$ g++ `pkg-config --cflags opencv` main.cpp `pkg-config --libs opencv` -o opencv_example

Now, the question is how do we do this with CMake? The following would be what you would write in CMakeLists.txt
project(opencv_example)

# this is where we get pkg-config info
find_package(PkgConfig REQUIRED)
pkg_check_modules(OPENCV REQUIRED opencv)

# this is where you compile your app
add_executable(opencv_example main.cpp)
target_link_libraries(opencv_example ${OPENCV_LIBRARIES})
target_include_directories(opencv_example PUBLIC ${OPENCV_INCLUDE_DIRS})
target_compile_options(opencv_example PUBLIC ${OPENCV_CFLAGS_OTHER})

Happy hacking!

Sunday, April 15, 2018

OpenCV on PyCharm

PyCharm is such a nice IDE for developing in Python. I really love it. However, with OpenCV module, I realized that PyCharm didn't recognize cv2 module.

After some search, here is a very simple solution! Credit goes to here.
When you import cv2, simply copy paste the whole thing below:

import cv2

# this is just to unconfuse pycharm
try:
    from cv2 import cv2
except ImportError:
    pass

That's it!

Friday, September 15, 2017

Multithreading in Python

In the previous post, I investigated a way to preprocess images using multiple processes. In this post, I will investigate a way to preprocess images using multiple threads.

The real difference from the multiprocessing code is not much. Instead of using multiprocessing.Pool class, use multiprocessing.pool.ThreadPool class. Below is the code:

The execution time for multithreading is a bit slower than that of multiprocessing, but I am not sure if this is always the case, as the difference is not significant.

single thread elapsed time: 364
threads elapsed time: 184
threads elapsed time: 115

Multiprocessing with Python

I have been training a simple neural network on my desktop, and I realized that GPU wasn't running at its full capacity, i.e., there must be some bottleneck from, most likely, CPU side. My guess is image preprocessing from CPU is taking longer than GPU computation for each batch. In order to reduce the time for CPU to preprocess the images, I started investigating multiprocessing option in Python.

Below is a simple code for running OpenCV's Canny function across multiple processes using Python's built-in multiprocess module:


Running the script yields approximately linear time reduction for 2 processes and sub-linear for 4 processes, due to other bottleneck, such as disk IO.

single process elapsed time: 364
2 processes elapsed time: 181
4 processes elapsed time: 108

Thursday, May 4, 2017

Setup Deep Learning Development Environment in Ubuntu

In this tutorial, I will go through step by step instructions to setup deep learning development environment for Ubuntu. We will install the following python packages on fresh Ubuntu 16.04:
opencv
tensorflow
keras
matplotlib
numpy
scipy
sklearn
tk

Let's dig it! First, I would install virtualenv, in case you need multiple python environments.
$ sudo apt-get install virtualenv -y

To create an environment, simply run
$ virtualenv ENV
where replace ENV with the deep learning environment name you would like.

To activate the new environment,
$ source ~/ENV/bin/activate
where again replace ENV with the name chosen above.

Next, we need to install pip, which helps us install these python packages with ease.
$ sudo apt-get install python-pip -y

You may want to upgrade pip to the latest version:
$ pip install --upgrade pip

Next, let's install python packages within the environment.
$ pip install tensorflow keras numpy scipy matplotlib sklearn

For OpenCV and TK, we need to install it from apt-get:
$ sudo apt-get install libopencv-dev python-opencv python-tk -y

That's it! Now you are ready to develop your neural network with tensorflow backend keras! If you want to test out if your environment is successfully setup, check out this post.

Tuesday, May 2, 2017

Displaying Exact Values for Digital Color Meter on Mac OS X

Mac OS X's built-in app Digital Color Meter is an extremely useful tool for me, and I love it. However, the only problem is that it is not exact.

I manually created an image with RGB values of arbitrary numbers, say (38, 205, 86) using OpenCV. I then opened up the image with Preview, and measured the color with Digital Color Meter. Unfortunately, its output was close but not exact.

I also noticed that there is an drop down menu, such as
Display in native values
Display in P3
...

After playing around with all of these options, I am very happy to report that the option Display in sRGB produces exact match with the pixel!


Tuesday, April 18, 2017

Local Thresholding from Zxing Library (C++)

In this tutorial, I will go over how to call local threshold method in zxing library, ported to C++ (zxing-cpp) instead of Java. If you want to implement it in Java, refer to this tutorial. I will assume that OpenCV library is installed on the system.

First, one needs to download zxing-cpp
$ git clone https://github.com/glassechidna/zxing-cpp.git
$ mkdir build && cd build

To integrate zxing-cpp with system's OpenCV, one needs to first search for OpenCVConfig.cmake file:
$ find / -iname opencvconfig.cmake 2>/dev/null
/usr/local/Cellar/opencv3/3.2.0/share/OpenCV/OpenCVConfig.cmake

In my case, I installed OpenCV from Homebrew, and its config cmake file is in /usr/local/Cellar/opencv3/3.2.0/share/OpenCV/ directory. Export OpenCV_DIR environment variable to point to this path:
$ export OpenCV_DIR='/usr/local/Cellar/opencv3/3.2.0/share/OpenCV/'

Now, we are ready to compile and install:
$ cmake -G "Unix Makefiles" ..
$ make -j2
$ sudo make install

Next, change directory to your working directory and create zxing.cpp source file as below:

To compile, we first need to copy MatSource.h into zxing include directory. I am assuming that you have cloned the zxing-cpp repository into ~/zxing-cpp-master.
$ sudo cp ~/zxing-cpp-master/opencv/src/zxing/MatSource.h /usr/local/include/zxing/
where /usr/local/include/zxing is the folder that contains zxing-cpp library's header files.

We also need to locate where zxing-cpp library file is installed. You can look it up from the output after sudo make install command above, or search the file as shown below.
$ find / -name libzxing.a 2>/dev/null
/usr/local/lib/libzxing.a

Finally, we are ready to compile.
$ g++ zxing.cpp `pkg-config --libs opencv` -lzxing -L/usr/local/lib/

Make sure to replace /usr/local/lib/ above after -L option with the directory where libzxing.a file is installed in your system.

To execute, run the following:
$ ./a.out some_image.jpg

You should see local threshold binary image of your input image file.

Monday, April 17, 2017

Local Thresholding from Zxing Library (Java)

Although OpenCV has its own local threshold method, such as adaptiveThreshold, I was looking for something a bit sophisticated and better. After some search, I came across Zxing's HybridBinarizer class that does the job much better than simple adaptiveThreshold from OpenCV. So, below is a very rough code to make use of this excellent library in Java. If you want to do this in C++, refer to this tutorial.



I admit that the code above is a bit messy, but it is just for testing out to see this actually works. In writing the code, I would like to acknowledge the following especially helpful references.

To compile the file and run it, first, create Test.java with the code above. Then, download Zxing's core library file (most recent version at the time of writing this is core-3.3.0.jar) form here. Then, run the following, assuming the jar file is in the same directory.

$ javac Test.java -cp ".:core-3.3.0.jar"
$ java -cp ".:core-3.3.0.jar" Test image_to_test.jpg

This will output the local thresholded image binary_output.jpg to the same folder. If you want to know more about java and javac -cp option, refer to this tutorial.

Tuesday, February 7, 2017

How to Load Java OpenCV Library to Android Studio

In this tutorial, I will go through a step by step method to load Java OpenCV Library to Android Studio.

First, download OpenCV for Android from here. Extract the zip file, and you should see OpenCV-android-sdk folder.

Next, in Android Studio, open up a project where you want to integrate OpenCV Java library. Then, click File - New - Import Module and select OpenCV-android-sdk/sdk/java folder. Android Studio will ask about import option, and just accept the default.

You should see OpenCVLibrary module in your Android project. Select its build.gradle file and set appropriate versions for compileSdkVersion, buildToolsVersion, etc.

Now, you need to add dependency. Open up your app's build.gradle file and add
compile project(':openCVLibrary310')
into dependencies { ... } section.

Next, you will need to make sure that your app loads in the OpenCV library. Go to the activity class file that first uses OpenCV Library, and add static statement, similar to below:

...
import org.opencv.android.OpenCVLoader;

public class MainActivity extends Activity {
    final static String TAG = "Main Activity";

    static {
        if(!OpenCVLoader.initDebug()){
            Log.d(TAG, "OpenCV not loaded");
        } else {
            Log.d(TAG, "OpenCV loaded");
        }
    }
...

Finally, you will need to copy native binary files. Copy OpenCV-android-sdk/sdk/native/libs folder as src/main/jniLibs folder in your app's directory.

That's it! You should now be able to use OpenCV functions in your app!

Sunday, November 27, 2016

How to Compile OpenCV with Debugging Symbols

Here is how to compile OpenCV with debugging symbols so that you can view OpenCV Library's source code as you debug.

When configuring with cmake, run with the following option:
$ cmake -DCMAKE_BUILD_TYPE:STRING=RelWithDebInfo ...

This option will add -O2 -g -DNDEBUG flags to the compiler when you build OpenCV.

For Ubuntu/Debian, take a look this post to see how to compile OpenCV from sources.

By the way, if you build OpenCV with clang, then you probably want to use lldb instead of gdb. If you compile with g++, then you may want to gdb instead of lldb. If you are having trouble running gdb on your Mac, check out this post.

Saturday, November 26, 2016

Using Qt as OpenCV HighGUI Backend for Mac OS X

Although I am in love with my new Macbook 12", I must admit that its X11 is quite annoying when used as OpenCV HighGUI's backend--it does not resize the image!

I was so frustrated with it that I looked for an alternative backend, and here it is: Qt5. In this tutorial, I will go over the method of building OpenCV3 on Mac OS X with Qt5 as HighGUI's backend. For simplicity, I will make use of homebrew.

First, you will need to tap into science:
$ brew tap homebrew/science

Next, install opencv3 with qt5 option:
$ brew install opencv3 --with-qt5

This option will add -D WITH_QT=ON in OpenCV's cmake option, thus linking Qt.

That's it! If you are wondering what are other available options, run
$ brew options opencv3

For more info on the package, run
$ brew info opencv3

That's it! You should now be able to launch HighGUI window via Qt5!

Monday, November 7, 2016

OpenCV for Android Integration with NDK in Studio 2.2+

Starting with Android Studio 2.2+, NDK integration has become much easier. Thanks a lot, Google!

In the previous post, I showed you how to import OpenCV Android Tutorial 2 sample app into Android Studio and build with NDK integration, which admittedly was quite complicated. I am happy to present much easier method here in terms of NDK integration, starting from Android Studio 2.2.

The only difference from the past post lies in the App module's build.gradle file. The new file should resemble this:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "24.0.3"

    defaultConfig {
        applicationId "org.opencv.samples.tutorial2"
        minSdkVersion 8
        targetSdkVersion 22

        ndk {
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }

    externalNativeBuild {
        ndkBuild {
            path 'src/main/jni/Android.mk'
        }
    }

}

dependencies {
    compile project(':openCVLibrary310')
}

That's it! This will now let Android Studio successfully load C/C++ source files in the src/main/jni directory with valid syntax correction, etc.

Wednesday, November 2, 2016

Install Latest Version of OpenCV on Debian from Sources

Here is how to install the latest OpenCV version on Debian from sources. If you are looking for tutorials on Mac OS X, you may want to check out this post.

Before doing anything, make sure to install necessary packages:
$ sudo apt-get install -y build-essential cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev

By the way, if you are not sure how to setup sudo in Debian, please take a look here.

Now, download the latest sources from its official Github repository. This will take some time.
$ git clone https://github.com/opencv/opencv.git

Else, you may want to just check out Linux component from here.

Create release folder and run cmake:
$ mkdir opencv/release && cd opencv/release
$ cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D BUILD_EXAMPLES=YES ..

For more OpenCV cmake options, take a look here starting at line 171. If you would like to be able to debug the OpenCV library, you will need to compile with debug symbols. This post explains how to do so.

Now, we are ready to compile and install:
$ make -j $(nproc)
$ sudo make install

Let's test and see if you can link the library. Create test.cpp file with the following:
#include <opencv2/core.hpp>
#include <iostream>
using namespace cv;
int main() {
Mat test(3,2,CV_8UC1); 
std::cout << test << std::endl;

return 0;
}

Compile and run:
$ g++ test.cpp $(pkg-config --libs opencv)
$ ./a.out
./a.out: error while loading shared libraries: libopencv_shape.so.3.1: cannot open shared object file: No such file or directory

OK. This is because ldconfig hasn't been updated.
$ sudo ldconfig
$ ./a.out
[ 10,  60;
  71,   0;
   0,   0]

Enjoy!

Saturday, October 15, 2016

How to Integrate OpenCV for Android Tutorial 2 and Tutorial 3 Modules

OpenCV Android Tutorial 2 shows how to setup JNI to import C++ native code, while Tutorial 3 shows how to control Android camera to take a picture. In this tutorial, I will go over step by step how to integrate Tutorial 2 and Tutorial 3 modules; that is, we will be building an app that will both let us import native C++ OpenCV code and control Android camera to take picture.

To me, it seems easier to integrate JNI into Tutorial 3 module, so the following will simply add JNI capability to Tutorial 3 module.

First, import Tutorial 3 module from OpenCV Android.

Next, edit openCVTutorial3CameraControl/build.gradle file to use NDK, similar to below:
import org.apache.tools.ant.taskdefs.condition.Os
apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "24.0.3"

    defaultConfig {
        applicationId "org.opencv.samples.tutorial3"
        minSdkVersion 8
        targetSdkVersion 22

        ndk {
            moduleName "camera_control" // this is the native module name
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }

    sourceSets.main {
        jniLibs.srcDir 'src/main/libs'
        jni.srcDirs = []
    }

    task ndkBuild(type: Exec) {
        if (Os.isFamily(Os.FAMILY_WINDOWS)) {
            commandLine 'ndk-build.cmd', '-C', file('src/main').absolutePath
        } else {
            commandLine '/home/linuxnme/Android/Sdk/ndk-bundle/build/ndk-build', '-C', file('src/main').absolutePath // replace with your path
        }
    }

    tasks.withType(JavaCompile) {
        compileTask -> compileTask.dependsOn ndkBuild
    }
}

dependencies {
    compile project(':openCVLibrary310')
}

Make sure to note NDK module name; in my case it is set to camera_control. Also, make sure to compile openCVLibrary with the same SdkVersion by editing the library's build.gradle file.

Next, edit Tutorial3Activity.java file to look like following:
...
public class Tutorial3Activity extends Activity implements CvCameraViewListener2, OnTouchListener {
    private static final String TAG = "OCVSample::Activity";
...
    public native void FindFeatures(long matAddrGr, long matAddrRgba);
    private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            switch (status) {
                case LoaderCallbackInterface.SUCCESS:
                {
                    Log.i(TAG, "OpenCV loaded successfully");
                    System.loadLibrary("camera_control");
                    mOpenCvCameraView.enableView();
                    mOpenCvCameraView.setOnTouchListener(Tutorial3Activity.this);
                } break;
                default:
                {
                    super.onManagerConnected(status);
                } break;
            }
        }
    };
...

   public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
        Mat mRgba =  inputFrame.rgba();
        Mat mGray = inputFrame.gray();
        FindFeatures(mGray.getNativeObjAddr(), mRgba.getNativeObjAddr());
        return mRgba;
    }
...

Make sure to use the same native module name.

Next, copy jni folder from Tutorial 2. Edit Application.mk file to set
APP_ABI := all

Edit Android.mk file to change JNI module name:
LOCAL_MODULE    := camera_control

Also, edit line 12 of this file to correctly point to your jni folder of OpenCV Android SDK.

Edit jni_part.cpp to correct the function names as below:
...
extern "C" {
JNIEXPORT void JNICALL Java_org_opencv_samples_tutorial3_Tutorial3Activity_FindFeatures(JNIEnv*, jobject, jlong addrGray, jlong addrRgba);

JNIEXPORT void JNICALL Java_org_opencv_samples_tutorial3_Tutorial3Activity_FindFeatures(JNIEnv*, jobject, jlong addrGray, jlong addrRgba)
{
    Mat& mGr  = *(Mat*)addrGray;
    Mat& mRgb = *(Mat*)addrRgba;
    vector<KeyPoint> v;
...

Enjoy Android development!

Friday, September 2, 2016

Image Stitching with OpenCV 3.1.0

With OpenCV, stitching images to make a panorama is very easy. I will go over how to create a beautiful panorama image using OpenCV 3.1.0. Because there is a bug in OpenCV 3.1.0 Stitcher class when OpenCL is enabled, we will need to turn it off when building.

To build OpenCV 3.1.0 from source files, download it first from here or run
$ wget https://github.com/Itseez/opencv/archive/3.1.0.zip

Unzip it
$ unzip 3.1.0.zip
$ cd opencv-3.1.0

Create build folder
$ mkdir build && cd build

Create Makefile
$ cmake -D CMAKE_BUILD_TYPE=RELEASE -D BUILD_EXAMPLES=ON -D CMAKE_BUILD_PREFIX=/usr/local/ -D WITH_OPENCL=OFF ..

If you encounter some ippicv hash error, try with ipp off:
$ cmake -D CMAKE_BUILD_TYPE=RELEASE -D BUILD_EXAMPLES=ON -D CMAKE_BUILD_PREFIX=/usr/local/ -D WITH_OPENCL=OFF -D WITH_IPP=OFF ..

Next, let's build the library!

For Linux systems,
$ make -j `nproc`

For Mac OS X,
$ make -j `sysctl -n hw.ncpu`

After some time, the build should end successfully. Let's test stitch function out. It turns out that there is an example code in the source:
$ vim ../samples/cpp/stitching.cpp
$ vim ../samples/cpp/stitching_detailed.cpp

Actually, we just built this example file, and its executable is located in build/bin directory
$ cd bin/
$ ls cpp-example-stitching*

To test it, simply provide the image files to be stitched
$ ./cpp-example-stitching image1.jpg image2.jpg
$ ./cpp-example-stitching_detailed image1.jpg image2.jpg --features orb

You may want to download the files from here. If successful, the resultant panorama image files should have been produced
$ eog result.jpg

For Mac OS X, run
$ open -a Preview result.jpg

You may also want to run other OpenCV test and example files in the bin folder. To run tests, you will need to copy OpenCV extra data and set OPENCV_TEST_DATA_PATH variable:
$ git clone git://github.com/Itseez/opencv_extra.git
$ export OPENCV_TEST_DATA_PATH=`pwd`/opencv_extra/testdata

Now, you can run test files:
./opencv_test_stitching

Finally, to install it on the system, one needs to run
$ sudo make install

Enjoy your panorama image!

Monday, August 22, 2016

VirtualBox: Share Files between Mac OS X Host and Windows Guest

VirtualBox supports Shared Folders feature so that one can access files directionally between the host and guest systems. In this post, I will go over how to share files between VirtualBox Windows guess and Mac OS X host.




First, open up VirtualBox, and select your Windows virtual machine. Click on the Settings icon to open up the settings window, and click on Shared Folders tab. 




On the right hand side, click on a small button that reads Adds new shared folder. On the drop down menu for Folder Path, choose Other...




Finally, simply choose the folder in your host system (i.e., Mac OS X) which will be shared with the guest system (i.e., Windows). Check Auto-mount option.




Now, the setting is complete. Fire up your virtual machine, and you should be able to see your shared drive as a network drive when you open up My Computer window. The shared drive address should be \\vboxsrv

Saturday, July 23, 2016

How to Compile Mixed Processing OpenCV Tutorial App on Android Studio

The second OpenCV for Android tutorial app, namely Mixed Processing, differs from Camera Preview app in that it also has a C++ source file, thus requiring Android NDK. To compile this project in Android Studio, the first several steps are identical to Camera Preview app, so follow instructions in my previous post. In summary, these steps that are required to integrate OpenCV for Android SDK statically are:

1. Download OpenCV for Android and unzip
2. Import the tutorial project to Android Studio
3. Adjust the Android API and SDK Tools version in the app and library module build.gradle files
4. Copy OpenCV Android native library folder into the app module folder and rename it as jniLibs
5. Add OpenCV static initializing code to the main activity java file
6. Add appcompat dependency in the app module build.gradle file (for API 23 or above only)
7. Add camera permission code in the java file (for API 23 or above only)
8. Change the theme in AndroidManifest.xml file (for API 23 or above only)

Even after all the above changes, the project will still not compile because it contains native C++ file, which we must let Android Studio know what to do with. So, here we go again! I will assume the project directory of ~/AndroidStudioProjects/tutorial-2-mixedprocessing. Before we do anything further, make sure to install Android NDK from SDK Manager.

When you try to compile the project, it will complain with the following error message:
Error:(12, 0) NDK integration is deprecated in the current plugin.
Consider trying the new experimental plugin
Set "android.useDeprecatedNdk=true" in gradle.properties to continue using the current NDK integration

Let's do what it asks for. You probably do not have this gradle.properties file yet, so let's create it.
$ echo "android.useDeprecatedNdk=true" > ~/AndroidStudioProjects/tutorial-2-mixedprocessing/gradle.properties

When you try to build the project, it will now complain with two errors:
Error:(2, 33) opencv2/core/core.hpp: No such file or directory
...
Error:Execution failed for task ':openCVTutorial2MixedProcessing:compileDebugNdk'.
> com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '~/Library/Android/Sdk/ndk-bundle/ndk-build'' finished with non-zero exit value 2

Let's tackle these errors one by one. Open up the app module's build.gradle file, and edit it similar to below:
import org.apache.tools.ant.taskdefs.condition.Os

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "org.opencv.samples.tutorial2"
        minSdkVersion 8
        targetSdkVersion 23

        ndk {
            moduleName "mixed_sample"
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }

    sourceSets.main {
        jniLibs.srcDir 'src/main/libs'
        jni.srcDirs = []
    }

    task ndkBuild(type: Exec) {
        if (Os.isFamily(Os.FAMILY_WINDOWS)) {
            commandLine 'ndk-build.cmd', '-C', file('src/main').absolutePath
        } else {
            commandLine '~/Library/Android/Sdk/ndk-bundle/ndk-build', '-C', file('src/main').absolutePath // replace with your path
        }
    }

    tasks.withType(JavaCompile) {
        compileTask -> compileTask.dependsOn ndkBuild
    }
}

dependencies {
    compile project(':openCVLibrary310')
    compile 'com.android.support:appcompat-v7:23.0.0'
}

Note that you must replace ~/Library/Android/Sdk/ndk-bundle/ndk-build with the NDK path in your system. You can check this in local.settings file, which will have a line similar to
ndk.dir=~/Library/Android/Sdk/ndk-bundle
You can simply use this path followed by /ndk-build, as shown above.

Now try to build the project again, and you will see the first error message is gone. To solve the last error, edit the app module's jni/Android.mk file as shown below:
LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)
include ~/Downloads/opencv3.1/OpenCV-android-sdk/sdk/native/jni/OpenCV.mk // Replace this with  your own path where you have extracted OpenCV for Android

LOCAL_MODULE    := mixed_sample
LOCAL_SRC_FILES := jni_part.cpp
LOCAL_LDLIBS +=  -llog -ldl

include $(BUILD_SHARED_LIBRARY)

Again, make sure to replace ~/Downloads/opencv3.1/OpenCV-android-sdk/sdk/native/jni/OpenCV.mk with the appropriate path.

Finally, if you plan to run the app on x86 emulator or devices, you must also edit app module's jni/Application.mk file and replace APP_ABI := armeabi-v7a with APP_ABI := all.

 At last, you should be able to compile and run this Mixed Processing tutorial app on your device or emulator!

By the way, if you think you are missing the menu (Such as Samsung Galaxy phones), press-and-hold the back button; it will show the menu items in the full-screen mode.

How to Compile CameraPreview OpenCV Tutorial App on Android Studio

First, download the latest OpenCV for Android from here. At the time of writing this post, the latest version is OpenCV 3.1.0. I will assume that you have downloaded the file in ~/Downloads folder.

Unzip the contents by running
$ unzip OpenCV-3.1.0-android-sdk.zip

Next, open up Android Studio, and select Import project (Eclipse ADT, Gradle, etc.) and choose ~/Downloads/OpenCV-android-sdk/samples/tutorial-1-camerapreview

Choose the import destination directory as desired. I will assume it to be ~/AndroidStudioProjects/tutorial-1-camerapreview

Check all three boxes and click on finish.

Now, you should be prompted with an auto-generated Eclipse Android Project Import Summary. In the messages box below, you may probably see
Error:Cause: failed to find target with hash string 'android-14' in: /data/Android/Sdk
Install missing platform(s) and sync project

To fix this, open up build.gradle files for both the openCVLibrary module and openCVTutorial module. Make sure to change compile and target SDK versions appropriately. I will use API 23 and Build Tools 23.0.3 throughout this post, but your versions may differ from me. For example, gradle.build file for the openCVLibrary should read

apply plugin: 'com.android.library'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        minSdkVersion 8
        targetSdkVersion 23
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

and openCVTutorial module's build.gradle should read

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "org.opencv.samples.tutorial1"
        minSdkVersion 8
        targetSdkVersion 23
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

dependencies {
    compile project(':openCVLibrary310')
}

Now, you should be able to successfully compile the project. Try running the app on your device or emulator. You will probably be encountered with Package Not Found message, unless you already have OpenCV Manager installed on your device. You should be able to successfully run the app after installing OpenCV Manager!

In case you do not want to require OpenCV Manager on the device, it is possible to link the OpenCV library as a static library. To do this, you will first need to copy the native library folder to the project directory and name it as jniLibs:
$ cp -r ~/Downloads/OpenCV-android-sdk/sdk/native/libs ~/AndroidStudioProjects/tutorial-1-camerapreview/openCVTutorial1CameraPreview/src/main/jniLibs

Next, you will need to insert static initialization code into the main activity java file at ~/AndroidStudioProjects/tutorial-1-camerapreview/openCVTutorial1CameraPreview/src/main/java/org/opencv/samples/tutorial1/Tutorial1Activity.java:

...
public class Tutorial1Activity extends Activity implements CvCameraViewListener2 {
    static {
        if (!OpenCVLoader.initDebug()) {
            Log.v("OpenCV", "ERROR: OpenCV Library Load Failed");
        } else {
            Log.v("OpenCV", "OpenCV Library Load Successful");
        }
    }
...

where 7 lines starting from static have been inserted.

You should now be able to compile and run the app without OpenCV Manager app on the device. Sometimes, you need to clean build and rebuild the project, or select File -> Invalidate Caches / Restart option to get it take effect. If it still says it requires OpenCV Manager, make sure to delete the original app from the device, rebuild the app, and re-run the app.

NOTE - if you are compiling for Android API 23 or above, you will need to set permission for the camera. Follow the instructions below:

1. Add a dependency in openCVTutorial module's build.gradle file to read
...
dependencies {
    compile project(':openCVLibrary310')
    compile 'com.android.support:appcompat-v7:23.0.0'
}
...

Make sure to insert the appropriate repository version in place of v7:23.0.0; Else, you could always install one.

2. Let the main activity extend AppCompatActivity and add permission request code in the main java file:
...
import android.Manifest;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
...
public class Tutorial1Activity extends AppCompatActivity implements CvCameraViewListener2 {
...
    public void onCreate(Bundle savedInstanceState) {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.CAMERA},
                0);
...

This is the bare minimum code to access camera for API 23 and above. For more details and practical coding, please refer to Android's official document.

3. In openCVTutorial module's AndroidManifest.xml file, replace android:theme="@android:style/Theme.NoTitleBar.Fullscreen" with android:theme="@style/Theme.AppCompat.Light".

Now, you should be able to run the app without OpenCV Manager installed! If you are running on the emulator, make sure to go to the advanced option to emulate back camera.