Example of configuring and using OpenCV in Android Studio

Source: Internet
Author: User

Android Studio Configuration and use OpenCV


Introduction: Recently in the project transplant, the project is large, the JNI and OPENCV environment configured in Eclipse no problem, but migrated to studio in a lot of problems, the Internet also found some information reference and learning, thank the predecessors left the summary and experience. about using JNI and configuration in as OpenCV also studied for a period of time, afraid to forget in the future in this record, on the other hand can also give some beginners a shortcut, less go some detours.


1. Download and catalogue introduction

Go to the official website (http://opencv.org/) to download the opencv4android and unzip it (this is OPENCV-2.4.9-ANDROID-SDK). Here is the chart of the directory:

The SDK directory is the class library we need to develop OPENCV;

Some examples of OPENCV applications (including face detection) are stored in the Samples directory, which provides a reference for us to develop OpenCV under Android.

Doc Directory for the OpenCV class library usage instructions and API documentation, etc.;

The apk directory contains the OPENCV application installation package that corresponds to each kernel version, such as;


(To manage the OpenCV class library in your mobile device, you must make sure that the opencv_2.4.3.2_manager_2.4_*.apk is already installed in your phone before you run the OpenCV app. Otherwise the OPENCV application will not run because the OpenCV class library cannot be loaded)


2. Introducing OpenCV to Android Studio

one thing to note here is that you can directly Select the File-->import Module in Android Studio, find the path to the OpenCV decompression, select Sdk/java the folder is imported as a module. But easy to maintain, here's my advice is to find the SDK under the Java directory, copy it to your Studioproject project directory, in the introduction.


3. Update build.gradle information

After importing, you select Project view in the upper-left corner of studio, and under the introduced Opencvlibrary folder, open Build.gradle ( gradle) because of an error in configuration issues in the Note the following information is introduced in the file under openCVLibrary249 ), which is modified:

1) compilesdkversion

2) buildtoolsversion

3) Minsdkversion

4) targetsdkversion (match its content to the information in the Build.gradle in the app folder )

As shown in the following:




Then click Gradle to sync (sync Gradle).

4. Add Module Dependency

Select File--->project Structure, in the Dependencies column of the app module, click the Green plus sign in the upper-right corner, add opencvlibrary, and click OK.


5. Copy the Libs folder into the project

In OpenCV's unpacking package, copy the Sdk-->native-->libs folder, paste it under the App-->src-->main directory under Project view, and rename it to jnilibs.

In this case, the OPENCV environment is configured, which is tested with an example below. Here is a reference to a blog post, here also thank the blogger: http://blog.csdn.net/yanzi1225627/article/details/16917961


6. Sample Demo

Ok! First look at how the opencvactivity is written:

public class Opencvactivity extends activity{private Button btn;    Private ImageView img;    Private Bitmap Srcbitmap;    Private Bitmap Graybitmap;    private static Boolean flag = TRUE;    private static Boolean IsFirst = true;    private static final String TAG = "Gao_chun";        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.LAYOUT.ACTIVITY_OPENCV);        img = (ImageView) Findviewbyid (r.id.img);        BTN = (Button) Findviewbyid (R.ID.BTN);    Btn.setonclicklistener (New Processclicklistener ());        } @Override protected void Onresume () {super.onresume (); Load OpenCV engine and init OpenCV library Opencvloader.initasync (Opencvloader.opencv_version_2_4_9, Getapplicati        Oncontext (), mloadercallback);    LOG.I (TAG, "Onresume sucess load OpenCV ...");      The//OPENCV library loads and initializes the successful callback function private Baseloadercallback mloadercallback = new Baseloadercallback (this) {  @Override public void onmanagerconnected (int status) {//TODO auto-generated method stub s                    Witch (status) {case baseloadercallback.success:log.i (TAG, "successfully loaded");                Break                    default:super.onManagerConnected (status);                    LOG.I (TAG, "failed to load");            Break    }        }    };        public void Procsrc2gray () {Mat Rgbmat = new Mat ();        Mat Graymat = new Mat ();        Srcbitmap = Bitmapfactory.decoderesource (Getresources (), R.drawable.genie);        Graybitmap = Bitmap.createbitmap (Srcbitmap.getwidth (), Srcbitmap.getheight (), Bitmap.Config.RGB_565);        Utils.bitmaptomat (Srcbitmap, Rgbmat);//convert original bitmap to Mat, R G B. Imgproc.cvtcolor (Rgbmat, Graymat, Imgproc.color_rgb2gray);//rgbmat to Gray Graymat Utils.mattobitmap (GrayMat, GrayB ITMAP);   Convert Mat to Bitmap log.i (TAG, "Procsrc2gray sucess ..."); } public class Processclicklistener implements view.onclicklistener{@Override public void OnClick (View                V) {//TODO auto-generated Method stub if (IsFirst) {Procsrc2gray ();            IsFirst = false;                } if (flag) {Img.setimagebitmap (GRAYBITMAP);                Btn.settext ("View original");            Flag = false;                }else{Img.setimagebitmap (SRCBITMAP);                Btn.settext ("grayscale");            Flag = true; }        }    }}

take a look at the simple layout interface activity_opencv.xml:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android"                android:layout_width= "Match_ Parent "                android:layout_height=" match_parent ">    <textview        android:layout_width=" Wrap_content "        android:layout_height= "wrap_content"        android:layout_alignparenttop= "true"        android:text= "OpenCV"/ >    <imageview        android:id= "@+id/img"        android:layout_width= "wrap_content"        android:layout_ height= "Wrap_content"        android:layout_centerinparent= "true"        android:background= "@drawable/genie"/>    <button        android:id= "@+id/btn"        android:layout_width= "wrap_content"        android:layout_ height= "Wrap_content"        android:layout_below= "@id/img"        android:layout_centerhorizontal= "true"        android:text= "grayscale"/> "</RelativeLayout>


After the run:


Follow the steps, basically not much problem, think of the demo or upload for everyone to refer to it, but because of the copy out after the whole package has found that more than 220 m too scary, simply deleted something, the app directory under the build directory to delete content, the src---> main--- > Jnilibs . So library deleted, note : If you download the demo run, you need to OpenCV in the unpacking directory, will sdk-->native-->libs The four directories under the folder are copied to the project's jnilibs directory.


Download Link: http://download.csdn.net/download/gao_chun/9206935


"Reprint Annotated Gao_chun blog:http://blog.csdn.net/gao_chun/article/details/49359535"


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Example of configuring and using OpenCV in Android Studio

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.