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

Android 影像處理實作:用 Options Menu 完成懷舊、浮雕、模糊、光照與素描效果

編輯:關於 Android 程式設計

「隨手拍」這個專案想做成類似美圖秀秀那樣、底部一排效果按鈕的樣式。在動手做自訂 UI 之前,先用系統原生的 Options Menu 把幾種基本的影像處理效果跑起來,是個成本最低的起點。本文整理相簿載入、懷舊、浮雕、模糊、光照與素描的實作過程,後續再談如何用 PopupWindow 打造更漂亮的效果列。

一、Menu 的效果與限制

Android 手機的 Menu 鍵會彈出選單,通常顯示在螢幕底部或右上角。OptionsMenu 最多顯示兩排、每排三個項目,每個項目都能自帶圖示與文字。若項目超過六個,第六項會變成 More,點下去才展開其餘隱藏選項。

在 Activity 中重寫 onCreateOptionsMenu 即可建立選單:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    menu.add(Menu.NONE, Menu.FIRST + 1, 1, "打開")
        .setIcon(android.R.drawable.ic_menu_slideshow);
    menu.add(Menu.NONE, Menu.FIRST + 2, 2, "懷舊")
        .setIcon(android.R.drawable.ic_menu_edit);
    menu.add(Menu.NONE, Menu.FIRST + 3, 3, "浮雕")
        .setIcon(android.R.drawable.ic_menu_gallery);
    menu.add(Menu.NONE, Menu.FIRST + 4, 4, "模糊")
        .setIcon(android.R.drawable.ic_menu_crop);
    menu.add(Menu.NONE, Menu.FIRST + 5, 5, "光照")
        .setIcon(android.R.drawable.ic_menu_camera);
    menu.add(Menu.NONE, Menu.FIRST + 6, 6, "銳化")
        .setIcon(android.R.drawable.ic_menu_view);
    return true;
}

要注意的是 Android 4.0 之後預設 UI 風格改變,Activity 的 theme 需設為 Theme.Light,圖示才不會有突兀的白底。當然也可以改在 res/menu/main.xml 用宣告式寫法定義選單。上圖示範了不同主題下的顯示差異,這裡使用的都是系統內建圖示,實際專案可替換成自己的素材。

版面配置上,上方放提示文字、下方放 ImageView:

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

    <RelativeLayout
        android:id="@+id/Layout_top"
        android:layout_width="fill_parent"
        android:layout_height="25dp"
        android:layout_alignParentTop="true"
        android:gravity="center">
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="請點擊 menu 處理圖片"
            android:textSize="20sp" />
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/Layout_bottom"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/Layout_top"
        android:background="#EFDFDF"
        android:gravity="center">
        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_gravity="center_horizontal" />
    </RelativeLayout>
</RelativeLayout>

二、選單事件分派

所有點擊行為都集中在 onOptionsItemSelected,用 Menu.FIRST + n 的 id 做分派,再呼叫各自的處理函式:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    switch (id) {
        case Menu.FIRST + 1:
            OpenImage();      break;
        case Menu.FIRST + 2:
            OldRemeberImage(); break;
        case Menu.FIRST + 3:
            ReliefImage();     break;
        case Menu.FIRST + 4:
            FuzzyImage();      break;
        case Menu.FIRST + 5:
            SunshineImage();   break;
        case Menu.FIRST + 6:
            SharpenImage();    break;
    }
    return super.onOptionsItemSelected(item);
}

三個關鍵回呼函式的職責:onCreateOptionsMenu() 建立選單,只在選單第一次顯示時呼叫;onOptionsItemSelected() 處理選中項目;而 menu.add() 的四個參數分別是「組別」、「項目 id(與 onOptionsItemSelected 對應)」、「顯示順序(由小到大、由左至右)」與「顯示文字」。

三、載入相簿圖片

先宣告需要的成員變數並取得 ImageView:

private ImageView imageShow;   // 顯示圖片
private Bitmap bmp;            // 原始圖片
private final int IMAGE_OPEN = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    imageShow = (ImageView) findViewById(R.id.imageView1);
}

打開相簿靠的是 ACTION_PICK:

public void OpenImage() {
    Intent intent = new Intent(Intent.ACTION_PICK,
        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(intent, IMAGE_OPEN);
}

回傳的處理是效能的關鍵。若直接把原始大圖解碼進記憶體,很容易 OOM。正確做法是先帶著 inJustDecodeBounds = true 只讀取尺寸資訊,算出縮放比例後再真正解碼:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK && requestCode == IMAGE_OPEN) {
        Uri imageFileUri = data.getData();
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;
        int height = dm.heightPixels;
        try {
            BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
            bmpFactoryOptions.inJustDecodeBounds = true;
            bmp = BitmapFactory.decodeStream(
                getContentResolver().openInputStream(imageFileUri), null, bmpFactoryOptions);
            int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight / (float) height);
            int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth / (float) width);
            if (heightRatio > 1 && widthRatio > 1) {
                bmpFactoryOptions.inSampleSize = Math.max(heightRatio, widthRatio);
            }
            bmpFactoryOptions.inJustDecodeBounds = false;
            bmp = BitmapFactory.decodeStream(
                getContentResolver().openInputStream(imageFileUri), null, bmpFactoryOptions);
            imageShow.setImageBitmap(bmp);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

四、五種效果的演算法實作

以下效果的原理都建立在「逐像素讀取 RGB → 套用公式 → 寫回新 Bitmap」這個框架上,差別只在公式。

1. 懷舊效果

本質上是一個色彩矩陣轉換,把 RGB 三個通道重新混合,讓整體色調偏黃偏暖:

private void OldRemeberImage() {
    /* R = 0.393r + 0.769g + 0.189b
       G = 0.349r + 0.686g + 0.168b
       B = 0.272r + 0.534g + 0.131b */
    int width = bmp.getWidth();
    int height = bmp.getHeight();
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
    int[] pixels = new int[width * height];
    bmp.getPixels(pixels, 0, width, 0, 0, width, height);
    for (int i = 0; i < height; i++) {
        for (int k = 0; k < width; k++) {
            int pixColor = pixels[width * i + k];
            int pixR = Color.red(pixColor);
            int pixG = Color.green(pixColor);
            int pixB = Color.blue(pixColor);
            int newR = (int) (0.393 * pixR + 0.769 * pixG + 0.189 * pixB);
            int newG = (int) (0.349 * pixR + 0.686 * pixG + 0.168 * pixB);
            int newB = (int) (0.272 * pixR + 0.534 * pixG + 0.131 * pixB);
            pixels[width * i + k] = Color.argb(255,
                newR > 255 ? 255 : newR,
                newG > 255 ? 255 : newG,
                newB > 255 ? 255 : newB);
        }
    }
    bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
    imageShow.setImageBitmap(bitmap);
}

效果如下圖,畫面呈現泛黃的老照片質感。

2. 浮雕效果

浮雕的關鍵是「用相鄰像素的差值加上 127 的中灰」。想像 ABC 三點,B 點的新值 = C 點 − B 點 + 127,於是平坦區域趨近中灰,只有邊緣會浮現明暗:

private void ReliefImage() {
    int width = bmp.getWidth();
    int height = bmp.getHeight();
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
    int[] pixels = new int[width * height];
    bmp.getPixels(pixels, 0, width, 0, 0, width, height);
    for (int i = 1; i < height - 1; i++) {
        for (int k = 1; k < width - 1; k++) {
            int pixColor = pixels[width * i + k];
            int pixR = Color.red(pixColor);
            int pixG = Color.green(pixColor);
            int pixB = Color.blue(pixColor);
            pixColor = pixels[(width * i + k) + 1];
            int newR = Color.red(pixColor) - pixR + 127;
            int newG = Color.green(pixColor) - pixG + 127;
            int newB = Color.blue(pixColor) - pixB + 127;
            pixels[width * i + k] = Color.argb(255,
                Math.min(255, Math.max(0, newR)),
                Math.min(255, Math.max(0, newG)),
                Math.min(255, Math.max(0, newB)));
        }
    }
    bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
    imageShow.setImageBitmap(bitmap);
}

3. 模糊效果

最直覺的模糊是把周圍九點平均;若改用高斯權重,中心權重最高、邊緣最低,畫面會更自然:

private void FuzzyImage() {
    int[] gauss = new int[] {1, 2, 1, 2, 4, 2, 1, 2, 1}; // 高斯矩陣
    int delta = 16;  // 除數,越小畫面越亮
    int width = bmp.getWidth();
    int height = bmp.getHeight();
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
    int[] pixels = new int[width * height];
    bmp.getPixels(pixels, 0, width, 0, 0, width, height);
    for (int i = 1; i < height - 1; i++) {
        for (int k = 1; k < width - 1; k++) {
            int pos = 0, newR = 0, newG = 0, newB = 0;
            for (int m = -1; m <= 1; m++) {
                for (int n = -1; n <= 1; n++) {
                    int pixColor = pixels[(i + m) * width + k + n];
                    newR += Color.red(pixColor) * gauss[pos];
                    newG += Color.green(pixColor) * gauss[pos];
                    newB += Color.blue(pixColor) * gauss[pos];
                    pos++;
                }
            }
            pixels[i * width + k] = Color.argb(255,
                Math.min(255, Math.max(0, newR / delta)),
                Math.min(255, Math.max(0, newG / delta)),
                Math.min(255, Math.max(0, newB / delta)));
        }
    }
    bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
    imageShow.setImageBitmap(bitmap);
}

這個 3×3 版本的效果其實還好而已,作者自己也提到對高斯模糊的理解還不夠透徹,真正的做法應該把半徑與 σ 參數化,並做完整的權重正規化。

4. 光照效果

以畫面中心為光源,半徑取長寬的較小值,越靠近中心的像素被加上的亮度越多,衰減是線性的:

private void SunshineImage() {
    int width = bmp.getWidth();
    int height = bmp.getHeight();
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
    int centerX = width / 2;
    int centerY = height / 2;
    int radius = Math.min(centerX, centerY);
    float strength = 150F;  // 光照強度,100~150 較自然
    int[] pixels = new int[width * height];
    bmp.getPixels(pixels, 0, width, 0, 0, width, height);
    for (int i = 1; i < height - 1; i++) {
        for (int k = 1; k < width - 1; k++) {
            int pixColor = pixels[width * i + k];
            int pixR = Color.red(pixColor);
            int pixG = Color.green(pixColor);
            int pixB = Color.blue(pixColor);
            int newR = pixR, newG = pixG, newB = pixB;
            int distance = (int) (Math.pow(centerY - i, 2) + Math.pow(centerX - k, 2));
            if (distance < radius * radius) {
                int result = (int) (strength * (1.0 - Math.sqrt(distance) / radius));
                newR = pixR + result;
                newG = pixG + result;
                newB = pixB + result;
            }
            pixels[width * i + k] = Color.argb(255,
                Math.min(255, Math.max(0, newR)),
                Math.min(255, Math.max(0, newG)),
                Math.min(255, Math.max(0, newB)));
        }
    }
    bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
    imageShow.setImageBitmap(bitmap);
}

5. 銳化效果

銳化的思路是強化邊緣與輪廓,與平滑剛好相反。用拉普拉斯算子做卷積是最經典的作法:

private void SharpenImage() {
    // 拉普拉斯算子模板 {-1,-1,-1, -1,9,-1, -1,-1,-1}
    int[] laplacian = new int[] {-1, -1, -1, -1, 9, -1, -1, -1, -1};
    int width = bmp.getWidth();
    int height = bmp.getHeight();
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
    int[] pixels = new int[width * height];
    bmp.getPixels(pixels, 0, width, 0, 0, width, height);
    float alpha = 0.3F;  // 混合透明度
    for (int i = 1; i < height - 1; i++) {
        for (int k = 1; k < width - 1; k++) {
            int idx = 0, newR = 0, newG = 0, newB = 0;
            for (int n = -1; n <= 1; n++) {
                for (int m = -1; m <= 1; m++) {
                    int pixColor = pixels[(i + n) * width + k + m];
                    newR += Color.red(pixColor) * laplacian[idx] * alpha;
                    newG += Color.green(pixColor) * laplacian[idx] * alpha;
                    newB += Color.blue(pixColor) * laplacian[idx] * alpha;
                    idx++;
                }
            }
            pixels[i * width + k] = Color.argb(255,
                Math.min(255, Math.max(0, newR)),
                Math.min(255, Math.max(0, newG)),
                Math.min(255, Math.max(0, newB)));
        }
    }
    bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
    imageShow.setImageBitmap(bitmap);
}

作者坦言這個效果在 Android 上不如預期,邊緣還會出現虛線;同樣的模板用 C++ 處理 24 位元 bmp 卻能漂亮地描出輪廓。左圖是 Android 的輸出,右圖是課堂上用 C++ 做的多模板比較,差異明顯。

額外效果:冰凍與素描

冰凍效果的做法是讓每個通道去減掉另外兩個通道、放大 1.5 倍再取絕對值,最後夾在 0~255 之間,畫面會浮現冷藍的結霜感(原始靈感來自 eoeAndroid 社群亞瑟的分享):

private void IceImage() {
    int width = bmp.getWidth();
    int height = bmp.getHeight();
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
    int[] pixels = new int[width * height];
    bmp.getPixels(pixels, 0, width, 0, 0, width, height);
    for (int i = 0; i < height; i++) {
        for (int k = 0; k < width; k++) {
            int pixColor = pixels[width * i + k];
            int pixR = Color.red(pixColor);
            int pixG = Color.green(pixColor);
            int pixB = Color.blue(pixColor);
            int newColor;
            newColor = (pixR - pixG - pixB) * 3 / 2;
            int newR = Math.min(255, Math.abs(newColor));
            newColor = (pixG - pixB - pixR) * 3 / 2;
            int newG = Math.min(255, Math.abs(newColor));
            newColor = (pixB - pixG - pixR) * 3 / 2;
            int newB = Math.min(255, Math.abs(newColor));
            pixels[width * i + k] = Color.argb(255, newR, newG, newB);
        }
    }
    bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
    imageShow.setImageBitmap(bitmap);
}

素描效果則是「灰階反相 + 高斯模糊 + 顏色減淡」的組合技,也是所有效果裡最複雜的一個:

private void SuMiaoImage() {
    int width = bmp.getWidth();
    int height = bmp.getHeight();
    int[] pixels = new int[width * height];
    int[] linpix = new int[width * height];
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
    bmp.getPixels(pixels, 0, width, 0, 0, width, height);
    // 1. 轉灰階,同時存一份反相圖
    for (int i = 1; i < width - 1; i++) {
        for (int j = 1; j < height - 1; j++) {
            int pixColor = pixels[width * i + j];
            int gray = (int) (0.3 * Color.red(pixColor)
                            + 0.59 * Color.green(pixColor)
                            + 0.11 * Color.blue(pixColor));
            linpix[width * i + j] = Color.argb(255, gray, gray, gray);
            gray = 255 - gray;
            pixels[width * i + j] = Color.argb(255, gray, gray, gray);
        }
    }
    // 2. 高斯模糊(半徑 10)
    int[] copixels = gaussBlur(pixels, width, height, 10, 10 / 3);
    // 3. 顏色減淡合成
    int[] result = colorDodge(linpix, copixels);
    bitmap.setPixels(result, 0, width, 0, 0, width, height);
    imageShow.setImageBitmap(bitmap);
}

其中高斯模糊刻意拆成水平、垂直兩次一維卷積,這是為了把複雜度從 O(n·r²) 降到 O(n·r),而且核心權重是依 σ 現場產生的:

public static int[] gaussBlur(int[] data, int width, int height, int radius, float sigma) {
    float pa = (float) (1 / (Math.sqrt(2 * Math.PI) * sigma));
    float pb = -1.0f / (2 * sigma * sigma);
    float[] gaussMatrix = new float[radius * 2 + 1];
    float gaussSum = 0f;
    for (int i = 0, x = -radius; x <= radius; ++x, ++i) {
        float g = (float) (pa * Math.exp(pb * x * x));
        gaussMatrix[i] = g;
        gaussSum += g;
    }
    for (int i = 0; i < gaussMatrix.length; ++i) {
        gaussMatrix[i] /= gaussSum;
    }
    // 先做 x 方向卷積,再做 y 方向卷積(此處省略重複的迴圈骨架)
    return data;
}

顏色減淡的公式是 result = base + base * mix / (255 - mix),結果上限 255:

private static int colorDodgeFormular(int base, int mix) {
    int result = base + (base * mix) / (255 - mix);
    return result > 255 ? 255 : result;
}

在 Menu 的對應分支裡呼叫 IceImage() 或 SuMiaoImage() 就能套用這些效果。除了本文提到的幾種,LOMO、底片、黑白等效果也都能用同一套像素框架拼出來。後續會再寫如何用 PopupWindow 做出美圖秀秀那種效果列,以及人脸偵測的相關應用。

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