Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

JNI 呼叫 OpenCV 與直接使用 Android 版 OpenCV:圖片效果轉換實作對照

編輯:關於 Android 開發

JNI 呼叫 OpenCV 與直接使用 Android 版 OpenCV:圖片效果轉換實作對照

先看幾張實際跑出來的效果圖。如果程式執行時提示需要安裝某某 Manager,別緊張,只要下載 OpenCV for Android 的套件包,解壓之後把對應的 Manager 安裝檔裝上手機就可以了。

以上就是實際的執行成果。關於 JNI 的呼叫細節這裡不展開,重點放在「同一張圖,如何切換出不同視覺效果」這段程式碼上。

一、主程式:按鈕切換色彩空間

整個 Demo 的做法很直觀:先把一張原圖讀進 ImageView,然後在點擊不同按鈕時,把原圖丟進 OpenCV 的 Imgproc.cvtColor 做色彩空間轉換,再把結果貼回畫面。另外也示範了一條走 JNI 的路徑,用 System.loadLibrary("image_proc") 載入自己編的 so,直接在原生層處理像素陣列。

package com.example.opencvdemo1;

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.imgproc.Imgproc;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import com.example.openjni.ImageProc;

public class MainActivity extends Activity implements OnClickListener {
    private Button mBtn_type1, mBtn_type2, mBtn_type3, mBtn_type4,
                   mBtn_type5, mBtn_type6, mBtn_type7, mBtn_src;
    private ImageView mIv_src;
    private Bitmap mDes_Bitmap;
    private boolean isGray = false;

    private BaseLoaderCallback loaderCallback = new BaseLoaderCallback(this) {
        public void onManagerConnected(int status) {
            switch (status) {
                case LoaderCallbackInterface.SUCCESS:
                    System.loadLibrary("image_proc");
                    break;
                case LoaderCallbackInterface.INIT_FAILED:
                case LoaderCallbackInterface.INSTALL_CANCELED:
                case LoaderCallbackInterface.MARKET_ERROR:
                case LoaderCallbackInterface.INCOMPATIBLE_MANAGER_VERSION:
                    break;
                default:
                    super.onManagerConnected(status);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    public void init() {
        mBtn_type1 = (Button) findViewById(R.id.btn_type1);
        mBtn_type2 = (Button) findViewById(R.id.btn_type2);
        mBtn_type3 = (Button) findViewById(R.id.btn_type3);
        mBtn_type4 = (Button) findViewById(R.id.btn_type4);
        mBtn_type5 = (Button) findViewById(R.id.btn_type5);
        mBtn_type6 = (Button) findViewById(R.id.btn_type6);
        mBtn_type7 = (Button) findViewById(R.id.btn_type7);
        mBtn_src   = (Button) findViewById(R.id.btn_src);
        mIv_src    = (ImageView) findViewById(R.id.iv_img);

        mDes_Bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.a);
        mIv_src.setImageBitmap(mDes_Bitmap);

        mBtn_type1.setOnClickListener(this);
        mBtn_type2.setOnClickListener(this);
        mBtn_type3.setOnClickListener(this);
        mBtn_type4.setOnClickListener(this);
        mBtn_type5.setOnClickListener(this);
        mBtn_type6.setOnClickListener(this);
        mBtn_type7.setOnClickListener(this);
        mBtn_src.setOnClickListener(this);
    }

    /** 透過 JNI 做灰階處理 */
    public Bitmap procSrc2GrayJni() {
        int w = mDes_Bitmap.getWidth();
        int h = mDes_Bitmap.getHeight();
        int[] pixels = new int[w * h];
        mDes_Bitmap.getPixels(pixels, 0, w, 0, 0, w, h);
        int[] resultInt = ImageProc.grayProc(pixels, w, h);
        Bitmap bitmap = Bitmap.createBitmap(w, h, Config.ARGB_8888);
        bitmap.setPixels(resultInt, 0, w, 0, 0, w, h);
        return bitmap;
    }

    /** 直接呼叫 Android 版 OpenCV 做色彩空間轉換 */
    public Bitmap procSrc2Gray(int type) {
        Mat rgbMat = new Mat();
        Mat grayMat = new Mat();
        Bitmap grayBitmap = Bitmap.createBitmap(
                mDes_Bitmap.getWidth(), mDes_Bitmap.getHeight(), Config.RGB_565);
        Utils.bitmapToMat(mDes_Bitmap, rgbMat);   // 原圖轉 Mat,R G B
        Imgproc.cvtColor(rgbMat, grayMat, type);  // rgbMat 轉成目標色彩空間
        Utils.matToBitmap(grayMat, grayBitmap);   // Mat 轉回 Bitmap
        Log.i("TAG", "procSrc2Gray sucess...");
        return grayBitmap;
    }

    @Override
    protected void onResume() {
        super.onResume();
        OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_9, this, loaderCallback);
    }

    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
            case R.id.btn_type1:
                mIv_src.setImageBitmap(procSrc2Gray(Imgproc.COLOR_RGB2GRAY)); break;
            case R.id.btn_type2:
                mIv_src.setImageBitmap(procSrc2Gray(Imgproc.COLOR_RGB2HLS)); break;
            case R.id.btn_type3:
                mIv_src.setImageBitmap(procSrc2Gray(Imgproc.COLOR_RGB2HSV)); break;
            case R.id.btn_type4:
                mIv_src.setImageBitmap(procSrc2Gray(Imgproc.COLOR_RGB2Lab)); break;
            case R.id.btn_type5:
                mIv_src.setImageBitmap(procSrc2Gray(Imgproc.COLOR_RGB2Luv)); break;
            case R.id.btn_type6:
                mIv_src.setImageBitmap(procSrc2Gray(Imgproc.COLOR_RGB2XYZ)); break;
            case R.id.btn_type7:
                mIv_src.setImageBitmap(procSrc2Gray(Imgproc.COLOR_RGB2YUV)); break;
            case R.id.btn_src:
                mIv_src.setImageBitmap(mDes_Bitmap); break;
            default:
                break;
        }
    }
}

二、Imgproc 這個類能幹什麼

Imgproc 是 OpenCV 裡專門負責影像處理的類別,灰階、素描、底片風格這類效果都能靠它完成。它在 Java 層之所以能被呼叫,背後正是透過 JNI 把能力橋接進 Android。

以下幾個 native 方法值得先認識:

// 邊緣偵測,可把圖片轉成類似線稿的描邊風格
private static native void Canny_0(long image_nativeObj, long edges_nativeObj,
        double threshold1, double threshold2, int apertureSize, boolean L2gradient);

// 與上面功能相同,只是參數較少
private static native void Canny_1(long image_nativeObj, long edges_nativeObj,
        double threshold1, double threshold2);

// 高斯濾波,用於模糊化
private static native void GaussianBlur_0(long src_nativeObj, long dst_nativeObj,
        double ksize_width, double ksize_height, double sigmaX, double sigmaY,
        int borderType);

private static native void GaussianBlur_1(long src_nativeObj, long dst_nativeObj,
        double ksize_width, double ksize_height, double sigmaX, double sigmaY);

private static native void GaussianBlur_2(long src_nativeObj, long dst_nativeObj,
        double ksize_width, double ksize_height, double sigmaX);

// 霍夫圓檢測
private static native void HoughCircles_0(long image_nativeObj, long circles_nativeObj,
        int method, double dp, double minDist, double param1, double param2,
        int minRadius, int maxRadius);

private static native void HoughCircles_1(long image_nativeObj, long circles_nativeObj,
        int method, double dp, double minDist);

參數含義大致如下:

Canny:第一個參數是待處理的影像矩陣,第二個是輸出矩陣,第三、第四個是雙閾值。閾值調得越大,被判定為邊緣的點就越少;第五個參數會影響邊緣細化(apertureSize)的程度,實際要用時需要自己反覆試,找到適合該圖的組合;最後一個參數則是是否採用更精確的 L2 梯度計算。

GaussianBlur:第一個是原始影像矩陣,第二個是輸出矩陣,第三、第四個是高斯模板的寬與高,第五、第六個 sigmaX / sigmaY 分別是水平與垂直方向的濾波係數,最後的 borderType 決定邊緣像素採用的插值方式。

三、三個常用效果的實作

/** 高斯模糊處理 */
public Bitmap gaosiBlur() {
    Mat rgbMat = new Mat();
    Mat grayMat = new Mat();
    Bitmap gaosiBitmap = Bitmap.createBitmap(
            mDes_Bitmap.getWidth(), mDes_Bitmap.getHeight(), Config.ARGB_8888);
    Utils.bitmapToMat(mDes_Bitmap, rgbMat);
    Size size = new Size();
    size.height = 17;
    size.width = 17;
    Imgproc.GaussianBlur(rgbMat, grayMat, size, 2, 2, Imgproc.BORDER_DEFAULT);
    Utils.matToBitmap(grayMat, gaosiBitmap);
    return gaosiBitmap;
}

/** 透視變換 */
public Bitmap getwarpPerspective() {
    Mat srcMat = new Mat();
    Mat dstMat = new Mat();
    Utils.bitmapToMat(mDes_Bitmap, srcMat);
    Mat perspectiveTransform = Imgproc.getPerspectiveTransform(srcMat, dstMat);
    Size size = new Size();
    size.height = mDes_Bitmap.getHeight();
    size.width = mDes_Bitmap.getWidth();
    Bitmap dstBitmap = Bitmap.createBitmap(
            mDes_Bitmap.getWidth(), mDes_Bitmap.getHeight(), Config.RGB_565);
    Core.perspectiveTransform(srcMat, dstMat, perspectiveTransform);
    Imgproc.warpPerspective(srcMat, dstMat, perspectiveTransform, size);
    Utils.matToBitmap(dstMat, dstBitmap);
    return dstBitmap;
}

/** 邊緣檢測 */
public Bitmap getCanny() {
    Mat rgbMat = new Mat();
    Mat grayMat = new Mat();
    Bitmap grayBitmap = Bitmap.createBitmap(
            mDes_Bitmap.getWidth(), mDes_Bitmap.getHeight(), Config.ARGB_8888);
    Utils.bitmapToMat(mDes_Bitmap, rgbMat);
    Imgproc.Canny(rgbMat, grayMat, 0, 150);
    Utils.matToBitmap(grayMat, grayBitmap);
    return grayBitmap;
}

Demo 下載:https://download.csdn.net/detail/u012808234/9374169

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved