Build and install OpenCV and contrib lib on Ubuntu / Android

I am going to show you how to clone the opencv source from Git repository. After cloing the source, I will build and install it.

Build for ubuntu

Download the source of opencv and opencv_contrib from github and checkout to the tag, 3.1.0:
cd ~/<my_working _directory>
git clone https://github.com/Itseez/opencv.git
git clone https://github.com/Itseez/opencv_contrib.git
cd ~/<my_working _directory>/opencv
git checkout -b 3.1.0 3.1.0
cd ~/<my_working _directory>/opencv_contrib
git checkout -b 3.1.0 3.1.0

Use cmake: 
cd opencv
mkdir release
cd release
cmake -DOPENCV_EXTRA_MODULES_PATH=../../opencv_contrib/modules/ CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local ..

If your environment contains CUDA, by default, it will build it with CUDA. If you don't want to build it with CUDA,  add -DWITH_CUDA=OFF to your cmake command line.

Start to build and install to /usr/local/include and /usr/local/lib. You can change the installed dir by change CMAKE_INSTALL_PREFIX
make -j8 # -j8 runs 8 jobs in parallel.
         # Change 8 to number of hardware threads available.
sudo make install

You can check your current opencv version:
$ pkg-config --modversion opencv

It will be 3.1.0 !

You can also look at the headers or libs installed. Using pkg-config can tell you where they are: 
$ pkg-config --cflags opencv
$ pkg-config --libs opencv

Actually, you can use the latest stable OpenCV version available in sourceforge without building the source.

How to speed up building process?
You can use Ninja to speed up instead of using Makefile
cd opencv
mkdir release
cd release
cmake -G Ninja -DOPENCV_EXTRA_MODULES_PATH=../../opencv_contrib/modules/ CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local ..
ninja -j8
ninja install

Build for Android version:

export ANDROID_NDK=[YourNDKPath]
cd ~/<my_working _directory>git clone https://gist.github.com/tzutalin/f07f5633fd599001101006561689062b
sh build-android-opencv.sh

You can change your target API in build_android_opencv.sh. For example, you can build the target for arm by changing the variable, ANDROID_ABI, in build_android_opencv.sh which you clone from the above commands.

The final output will be installed and located in ~/<my_working _directory>/android_opencv/

Alternatively, you can refer to https://github.com/tzutalin/build-opencv-for-android