1. 程式人生 > >Android-OpenCV3(Helloworld)

Android-OpenCV3(Helloworld)

1.先到官網下載最新版本(我的是3.4.3):

    https://sourceforge.net/projects/opencvlibrary/files/opencv-android/

2.建立一個APK:

3.匯入OpenCV模組:

4.設定依賴:

5.修改build.gradle(這一步是為了解決編譯問題)

對比app的buld.gradle:

修改openCVLibrary343模組的引數:

6.app中匯入openCV的so庫:

並把解壓包裡對應版本的so拷貝進去:

加入:

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

在activity_main.xml中加入:

<ImageView
    android:id="@+id/imageView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

把MainActivity.java修改為:

package com.demo.helloopencv;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;


import org.opencv.android.Utils;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageView mImageView = findViewById(R.id.imageView);
        mImageView.setImageBitmap(hivePic());
    }

    private Bitmap hivePic() {
        Log.e(TAG, "hivePic: HHHA:0====>");
        Mat des = new Mat();
        Mat src = new Mat();
        Bitmap srcBit = BitmapFactory.decodeResource(getResources(), R.drawable.test);
        Utils.bitmapToMat(srcBit, src);
        Bitmap grayBit = Bitmap.createBitmap(src.cols(), src.rows(), Bitmap.Config.ARGB_8888);
        Imgproc.cvtColor(src, des, Imgproc.COLOR_BGR2GRAY);
        Utils.matToBitmap(des, grayBit);
        return grayBit;
    }

    static {
        System.loadLibrary("opencv_java3");
    }
}

隨便找一張彩色圖片放入res中,命名為test

編譯下載到手機中執行:

執行效果是彩色圖片變成了灰度圖片: