使用OpenCV前手機必須安裝OpenCV Manager,且必須進行初始化
安裝OpenCV可以從Google play上進行安裝或者用adb的方式將OpenCV-android-sdk\apk底下的apk安裝進去
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.test.MainActivity" > <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_alignParentTop="true" /> </RelativeLayout>
Code:
package com.example.test; import org.opencv.android.BaseLoaderCallback; import org.opencv.android.LoaderCallbackInterface; import org.opencv.android.OpenCVLoader; import org.opencv.android.Utils; import org.opencv.core.Mat; import org.opencv.core.Point; import org.opencv.core.Scalar; import org.opencv.imgproc.Imgproc; import android.app.Activity; import android.graphics.Bitmap; import android.os.Bundle; import android.widget.ImageView; import android.widget.Toast; public class MainActivity extends Activity { private ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = (ImageView) findViewById(R.id.imageView1); // 初始化OpenCV,版本為3.0.0 OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_0_0, this, baseLoaderCallback); } private BaseLoaderCallback baseLoaderCallback = new BaseLoaderCallback(this) { @Override public void onManagerConnected(int status) { if (status == LoaderCallbackInterface.SUCCESS) { Mat mat = new Mat(); // 取得imageView大小 Bitmap bitmap = Bitmap.createBitmap(imageView.getWidth(), imageView.getHeight(), Bitmap.Config.RGB_565); // 將Bitmap轉成Mat Utils.bitmapToMat(bitmap, mat); // 寫入文字C.Y.Fang, 位置, 字體, 字體比例, 字體顏色 Imgproc.putText(mat, "C.Y.Fang", new Point(100, 100), 3, 1, new Scalar(0, 100, 100)); Bitmap bm = bitmap; // 將Map轉Bitmap Utils.matToBitmap(mat, bm); // 設定給ImageView imageView.setImageBitmap(bm); } else { Toast.makeText(getApplicationContext(), "載入失敗", 1).show(); super.onManagerConnected(status); } } }; }
執行結果: