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

動手做一個 Android 實時圖像處理工具

編輯:關於 Android 程式設計

緣起

在機器視覺實驗室待了一年半,我一直按自己的節奏安排學習內容——始終覺得沒有「最好」和「最簡單」的技術,只有自己願意深入去搞的技術。但說慚愧也確實慚愧:師兄們討論各種圖像處理算法時,我對機器視覺的瞭解幾乎為零。

我的主場是 Android,從上層到下層都有涉獵。於是一直有個念頭:能不能把自己的所長和實驗室的主題接起來?既能多和牛人交流,也順便請教一二。

於是有了這款 Android 平台的圖像處理工具。它的定位很明確:實時預覽同一幅畫面在不同算法下的處理結果。相比傳統流程,這個思路有一個天然優勢——

通常做圖像處理,會先在 MATLAB 或 Visual Studio 裡仿真:導入圖片 → 編譯 → 看輸出 → 改參數 → 再來一遍。而用這款工具,手機對著實景,就能實時看到 Sobel、二值化、邊緣提取的效果,參數還能滑動條實時調。對於調參和教學演示,效率差別非常明顯。

目前實現的功能

  • 開啟手機相機預覽圖像;
  • 將採集到的圖像轉換為灰度圖預覽;
  • 將灰度圖像經過 Sobel 算子處理後預覽;
  • 對 Sobel 結果進行二值化;
  • 二值化過程中可實時拖動滑動條調整閾值;
  • 通過拍照按鈕鎖定畫面,再執行邊緣提取。

效果預覽

主界面:

菜單切換到灰度圖:

Sobel 變換:

閾值 50 的二值分割:

邊緣提取:

一、主界面

MainActivity.java

布局比較簡單:一個 ImageView 撐滿預覽框,一個拍照按鈕,一個菜單按鈕。當選擇二值化算法時,額外顯示一個 SeekBar 和一個 EditText 用來實時調整閾值。

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

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

    <Button
        android:id="@+id/takePic_bt"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="15dp"
        android:background="@drawable/shutter"
        android:onClick="onClick_takePic" />

    <Button
        android:id="@+id/menu_bt"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_marginBottom="15dp"
        android:layout_marginLeft="5dp"
        android:background="@drawable/menu"
        android:onClick="onClick_menu" />

    <ListView
        android:id="@+id/list_view"
        android:layout_width="150dp"
        android:layout_height="match_parent"
        android:layout_marginTop="20dp"
        android:divider="#ff555555"
        android:dividerHeight="1.3dp"
        android:listSelector="@android:color/holo_blue_bright"
        android:visibility="gone" />

    <EditText
        android:id="@+id/input_threshold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_margin="20dp"
        android:inputType="numberDecimal"
        android:text="240"
        android:textColor="@android:color/holo_blue_bright"
        android:visibility="gone" />

    <SeekBar
        android:id="@+id/seekbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="20dp"
        android:layout_marginLeft="50dp"
        android:layout_toLeftOf="@id/input_threshold"
        android:max="255"
        android:progress="240"
        android:visibility="gone" />

</RelativeLayout>

菜單與拍照按鈕

public void onClick_menu(View view) {
    if (isMenuVisible) {
        listView.startAnimation(menuInvisible);
        listView.setVisibility(View.GONE);
        isMenuVisible = false;
    } else {
        listView.startAnimation(menuVisible);
        listView.setVisibility(View.VISIBLE);
        isMenuVisible = true;
    }
}

public void onClick_takePic(View view) throws IOException {
    getScreen.takePic();   // 相機拍照,鎖定當前畫面
}

菜單的顯示動畫用了透明度補間動畫,在 res/anim/ 下定義兩個資源,點擊時播放即可,讓界面變化柔和一些。

菜單項點擊

listView.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // 只有二值化需要閾值調節控件
        if (position == 3) {
            seekbar.setVisibility(View.VISIBLE);
            inputThreshold.setVisibility(View.VISIBLE);
        } else {
            seekbar.setVisibility(View.GONE);
            inputThreshold.setVisibility(View.GONE);
        }
        whichToDisplay = position;   // 切換算法
    }
});

閾值雙向同步

SeekBar 和 EditText 需要保持同步,兩邊都要監聽:

// 處理 SeekBar
seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
    @Override
    public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
        inputThreshold.setText(arg0.getProgress() + "");
    }

    @Override
    public void onStartTrackingTouch(SeekBar arg0) { }

    @Override
    public void onStopTrackingTouch(SeekBar arg0) {
        thresholdValue = arg0.getProgress() > 255 ? 255 : arg0.getProgress();
    }
});

// 處理 EditText
inputThreshold.setOnEditorActionListener(new OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        seekbar.setProgress(
                Integer.parseInt(inputThreshold.getText().toString()));
        return false;
    }
});

二、獲取相機圖像並顯示預覽

GetScreen.java

相機的使用可以歸納為六個步驟:

  1. 打開相機 —— Camera.open();
  2. 讀取默認參數 —— Camera.getParameters();
  3. 設置預覽容器 —— Camera.setPreviewTexture();
  4. 開始預覽 —— Camera.startPreview();
  5. 設置預覽回調 —— Camera.setPreviewCallback();
  6. 用完關閉 —— Camera.release()。

官方文檔強調了兩個容易出錯的地方:步驟 3 和 4 的順序不能顛倒,以及相機用完必須釋放,否則其他程序無法啟動相機。實測如果不釋放,退出時也會拋異常。

另一個要注意的是:回調傳入的圖像數據是 YUV420SP(又稱 NV21)格式,需要轉換成 RGB 才能方便處理。這裡用了一個 decodeYUV420SP() 方法,具體實現見源碼。轉成 RGB 後就能直接生成 Bitmap 顯示到 ImageView 上。

自動對焦

這部分反而最麻煩。思路是:週期性計算畫面平均亮度,如果亮度趨於穩定,說明畫面不再晃動,此時對焦成功率最高。

亮度計算用標準公式:

bright = 0.299 * r + 0.587 * g + 0.114 * b;
private void autoFocus() {
    long currentTime = System.currentTimeMillis();

    bright = Pictures.getLight(rgb);

    if (Math.abs(bright - lastBright) > focusThreshold) {
        // 亮度變化明顯,畫面還在動,重置穩定計時
        lastBright = bright;
        hasFocus = false;
        stableTime = currentTime;
    } else {
        // 亮度穩定超過 500ms 且尚未對焦過,執行一次對焦
        if (!hasFocus && currentTime - stableTime >= 500) {
            camera.autoFocus(new AutoFocusCallback() {
                @Override
                public void onAutoFocus(boolean success, Camera camera) { }
            });
            hasFocus = true;
        }
    }
}

hasFocus 標志位保證兩次穩定畫面之間只對焦一次,避免對焦函數被高頻調用而卡頓。

三、圖像算法

Pictures.java

這裡才真正涉及算法。為了便於複用,每個算法都寫成靜態方法:

  • decodeYUV420SP() —— YUV420SP 轉 RGB;
  • getLight() —— 計算圖像平均亮度;
  • getLightArray() —— 獲取八位灰度圖像數組;
  • convertToGrey() —— 彩色圖轉灰度圖;
  • sobel() —— Sobel 算子求邊緣;
  • turnTo2() —— 二值化處理;
  • findFrame() —— 邊緣提取。

核心:預覽回調

所有處理都集中在 onPreviewFrame() 中,這是整個軟件的心臟:

@Override
public void onPreviewFrame(byte[] data, Camera camera) {
    rgb = new int[Pictures.PIC_LENGTH];
    sobelPic = new int[Pictures.PIC_LENGTH];
    grey = new int[Pictures.PIC_LENGTH];

    Pictures.decodeYUV420SP(rgb, data, width, height);

    switch (MainActivity.whichToDisplay) {
        case 1:   // 灰度圖
            Pictures.convertToGrey(rgb, grey);
            display = grey;
            break;

        case 2:   // Sobel
            Pictures.convertToGrey(rgb, grey);
            Pictures.sobel(grey, width, height, sobelPic);
            display = sobelPic;
            break;

        case 3:   // 二值化
            Pictures.convertToGrey(rgb, grey);
            Pictures.sobel(grey, width, height, sobelPic);
            Pictures.turnTo2(sobelPic);
            display = sobelPic;
            break;

        default:  // 原圖
            display = rgb;
    }

    bitmap = Bitmap.createBitmap(display, width, height, Config.RGB_565);
    MainActivity.setImageView(bitmap);

    autoFocus();
}

流程很清晰:YUV 轉 RGB → 按菜單選項執行對應算法鏈 → 生成 Bitmap 顯示 → 執行一次對焦判定。

性能上的坦白

必須指出,這個實現有明顯的性能問題:

  • 每幀都在 new 數組。rgb、grey、sobelPic 應該提為成員變量復用,否則 GC 頻繁觸發會造成明顯掉幀。
  • 每幀都創建 Bitmap。應复用同一個 Bitmap,通過 setPixels() 更新內容。
  • 主線程做圖像處理。onPreviewFrame 運行在相機的預覽線程上,算法計算量大時會阻塞。更合理的架構是把原始數據丟到獨立的 Handler 線程或線程池中處理,處理完再切回主線程更新 UI。
  • 降低分辨率。通過 Camera.Parameters.setPreviewSize() 主動降低預覽分辨率(如 320×240),演算法驗證階段完全夠用,計算量卻能降一個數量級。
  • API 已過時。Camera 類在 API 21 起被標記 deprecated,新項目應使用 Camera2 或 CameraX,配合 ImageReader 獲取 YUV 數據,並能獲得更好的幀率控制。

結語

這個工具的價值不在代碼質量,而在把「編譯-運行-看結果」的循環壓縮到即時。對於理解 Sobel 的核是怎麼影響邊緣效果的、閾值該怎麼取,眼見為實比看公式有效得多。

目前支持的算法還不多,後續學到更多會慢慢加進來。如果你在學習圖像處理,強烈建議自己動手做一個類似的小工具——寫一遍 Sobel 卷積,比讀十篇文章都管用。

有任何意見或問題,歡迎一起討論。

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