欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android Studio3.5集成OpenCV-android-sdk的使用

程序员文章站 2024-03-24 08:46:04
...

一、OpenCV Android开发环境的搭建
Android Studio3.5.2
OpenCV Android Sdk 3.4.10版本
JDK8:64位
Android NDK r17c
从官网下载的SDK后解压如下所示
Android Studio3.5集成OpenCV-android-sdk的使用Android Studio3.5集成OpenCV-android-sdk的使用

  • apk文件夹中存储的是对应不同cpu的代理(manager)应用
  • samples中存储的是官方给出Demo源码示例,但是遗憾的是这里都是Eclipse项目
  • sdk中存储的就是我们接下来搭建环境需要使用的一些材料

1、新建一个项目OpenCVTest工程,然后选择Empty Activity,然后一直点击下一步。
Android Studio3.5集成OpenCV-android-sdk的使用2、将下载的OpenCV-android-sdk\sdk\中的java模块导入到该项目中,点击 File -> new -> Import Module, 选中 OpenCV-Android-SDK/sdk/java 文件夹,点击确定,就会自动识别处模块,如下图所示:
Android Studio3.5集成OpenCV-android-sdk的使用3、将OpenCV的SDK导入进来后,就修改openCVLibrary3410项目中的build.gradle文件,修改内容如下所示:

apply plugin: 'com.android.library'

android {
    compileSdkVersion 26
    buildToolsVersion "26"

    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 26
    }

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

4、修改openCVLibrary3410项目中的AndroidManifest.xml文件。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="org.opencv"
      android:versionCode="34100"
      android:versionName="3.4.10">
	//该行注释掉
    //<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="26" />
</manifest>

5、在Mouble app中修改build.gradle文件

dependencies {
    implementation project(path: ':openCVLibrary3410')
    implementation fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar')
}
task nativeLibsToJar(type: Jar, description: 'create a jar archive of the native libs') {
    destinationDir file("$buildDir/native-libs")
    baseName 'native-libs'
    from fileTree(dir: 'libs', include: '**/*.so')
    into 'lib/'
}

6、点击 File -> Project Structure,在 Modules app下点击依赖 openCVLibrary3410的模块,然后点击Dependencies中 Module dependency 后选择 openCVLibrary341 后点击完成。
Android Studio3.5集成OpenCV-android-sdk的使用二、代码示例测试
1、先写一个布局文件,里面一个按钮是选择本地相册里面的图片,另外一个按钮是实现图片的处理。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >
    <Button
        android:id="@+id/select_btn"
        android:text="选择图片"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
    <Button
        android:id="@+id/process_btn"
        android:text="处理"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
    <ImageView
        android:id="@+id/imageView"
        android:src="@mipmap/ic_launcher"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</LinearLayout>

2、MainActivity.java中代码如下

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

    private double max_size = 1024;
    private int PICK_IMAGE_REQUEST = 1;
    private ImageView myImageView;
    private Bitmap selectbp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        staticLoadCVLibraries();
        myImageView = (ImageView)findViewById(R.id.imageView);
        myImageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
        Button selectImageBtn = (Button)findViewById(R.id.select_btn);
        selectImageBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // makeText(MainActivity.this.getApplicationContext(), "start to browser image", Toast.LENGTH_SHORT).show();
                selectImage();
            }
        });

        Button processBtn = (Button)findViewById(R.id.process_btn);
        processBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // makeText(MainActivity.this.getApplicationContext(), "hello, image process", Toast.LENGTH_SHORT).show();
                convertGray();
            }
        });

    }

    //OpenCV库静态加载并初始化
    private void staticLoadCVLibraries(){
        boolean load = OpenCVLoader.initDebug();
        if(load) {
            Log.e(TAG, "Open CV Libraries loaded...");
        }
    }

    private void convertGray() {
        Mat src = new Mat();
        Mat temp = new Mat();
        Mat dst = new Mat();
        Utils.bitmapToMat(selectbp, src);
        Imgproc.cvtColor(src, temp, Imgproc.COLOR_BGRA2BGR);
        Log.i("CV", "image type:" + (temp.type() == CvType.CV_8UC3));
        Imgproc.cvtColor(temp, dst, Imgproc.COLOR_BGR2GRAY);
        Utils.matToBitmap(dst, selectbp);
        myImageView.setImageBitmap(selectbp);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri uri = data.getData();
            try {
                Log.d("image-tag", "start to decode selected image now...");
                InputStream input = getContentResolver().openInputStream(uri);
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeStream(input, null, options);
                int raw_width = options.outWidth;
                int raw_height = options.outHeight;
                int max = Math.max(raw_width, raw_height);
                int newWidth = raw_width;
                int newHeight = raw_height;
                int inSampleSize = 1;
                if(max > max_size) {
                    newWidth = raw_width / 2;
                    newHeight = raw_height / 2;
                    while((newWidth/inSampleSize) > max_size || (newHeight/inSampleSize) > max_size) {
                        inSampleSize *=2;
                    }
                }

                options.inSampleSize = inSampleSize;
                options.inJustDecodeBounds = false;
                options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                selectbp = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);

                myImageView.setImageBitmap(selectbp);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 跳转到系统相册选择图片
     */
    private void selectImage() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent,"选择图像..."), PICK_IMAGE_REQUEST);
    }
}

备注:本想下载最新的SDK为4.3.0的,但是不知道为什么SDK的依赖不显示,所以就用OpenCV Android Sdk 3.4.10版本

相关标签: OpenCV

上一篇: Codeforces 1004D

下一篇: CodeForces 703B