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

Launcher 圖標矩形化改造實踐:OpenCV 圖像識別的落地與取捨

編輯:關於 Android 程式設計

一、需求

把 Launcher 上的應用圖標統一改造為矩形形態,效果如下:

二、實現方案

核心思路是引入 OpenCV 做圖像輪廓識別與形狀判斷。坦白說,在接這個需求之前我完全沒接觸過 OpenCV,所以整個過程更像是邊學邊幹的探索記錄。

2.1 三類圖標,三種策略

第一類:背板顏色單一的圖標,例如 Google、BBC News。這類圖標直接放進矩形框時,若原本圓角弧度較大,四個角會露出空白。當時考慮過兩條路:

· 摳圖方案——提取圖標中心的特征(Google 的「g」、BBC News 的「BBC NEWS」字樣),畫一個圓角矩形,取背板顏色作為填充色,兩者合成新圖標。技術上可用 Imgproc.grabCut(mat, mask, rect, bgdModel, fgdModel, 1, Imgproc.GC_INIT_WITH_RECT) 實現,但實測準確度不理想,也可能是我的用法不對。
· 背板顏色延伸方案——把邊緣顏色向外擴展,填滿矩形化後可能露出的空白處。這個方向實現難度更高,加上項目進度壓力,最終沒有深入。

遺憾的是,這一類圖標的自動化處理最終沒有完成。

第二類:背板五顏六色、沒有明顯主特征的圖標,例如憤怒的小鳥、歐洲戰爭。既然摳圖和顏色延伸都不可行,就退而求其次:截取中心圓形並加白色背板。UE 最終提供的素材是中心透明的,因此實現上只需把原圖標按可見區域的實際大小縮小到一定比例,再疊上背板圖即可。

第三類:原圖標本身就是矩形且長寬比接近目標,只需適當縮放並做圓角處理,效果基本與原圖一致,僅尺寸略作調整、明顯的直角轉為圓角。

2.2 三種典型場景的效果對照

場景一:規則矩形圖標,按比例縮放加圓角。

原圖 1
截圓加白背板後

場景二:原圖標為不規則形狀,或尺寸明顯偏小(代碼中自訂了一個閾值來判定「偏小」,這個閾值本身不是重點)。此時應取圖標主色調作為背板顏色並疊加漸變效果。

原圖 2
截圓加白背板後

場景三:原圖標為矩形且長寬比接近目標,只做縮放與圓角。

原圖 3
截圓加白背板後

三、技術要點

3.1 預置圖標替換

在原本呼叫 Utilities.createIconBitmap 的位置,先做一層預置圖標判斷。修改點在 IconCache 的 CacheLocked() 方法中:

if (!getEntryFromDB(componentName, user, entry, useLowResIcon)) {
    if (info != null) {
        if (CustomUtil.sWhetherUseRectangleIcon) {
            Drawable icon = Utilities.findPrePlacedIconResource(componentName, mContext);
            if (icon != null) {
                entry.icon = Utilities.createIconBitmap(icon, mContext);
            } else {
                entry.icon = Utilities.createRectangleIconBitmap(
                        info.getBadgedIcon(mIconDpi), mContext);
            }
        } else {
            entry.icon = Utilities.createIconBitmap(info.getBadgedIcon(mIconDpi), mContext);
        }
    }
}

預置圖標的查找邏輯——把 ComponentName 轉成檔名風格後從 assets 讀取:

public static Drawable findPrePlacedIconResource(ComponentName componentName, Context context) {
    if (componentName != null
            && !TextUtils.isEmpty(componentName.getPackageName())
            && !TextUtils.isEmpty(componentName.getClassName())) {
        String filename = componentName.toString()
                .replace("ComponentInfo{", "")
                .replace("}", "")
                .replace("/", "_");
        return findPrePlacedIconResource(filename, context);
    }
    return null;
}

public static Drawable findPrePlacedIconResource(String fileName, Context context) {
    Drawable icon = null;
    if (!TextUtils.isEmpty(fileName)) {
        InputStream is = null;
        try {
            StringBuilder sb = new StringBuilder();
            is = context.getAssets().open(
                    sb.append(REPLACE_ICON_PATH).append(fileName).append(REPLACE_ICON_FORMAT).toString());
            if (is != null) {
                icon = Drawable.createFromStream(is, null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try { is.close(); } catch (IOException e) { e.printStackTrace(); }
            }
        }
    }
    return icon;
}

3.2 判斷圖標是否為矩形、長寬比是否達標

先取出圖標的最外層輪廓:

public static MatOfPoint findFirstContour(Bitmap b) {
    Mat RGBMat = new Mat();
    Mat oriMatCompare = new Mat();
    Utils.bitmapToMat(b.copy(Bitmap.Config.ARGB_8888, false), oriMatCompare);
    Imgproc.cvtColor(oriMatCompare, RGBMat, Imgproc.COLOR_RGBA2RGB);

    Mat grayMatForCompare = new Mat();
    Mat mHierarchy = new Mat();
    Imgproc.cvtColor(RGBMat, grayMatForCompare, Imgproc.COLOR_RGBA2GRAY);

    List<MatOfPoint> contours = new ArrayList<>();
    Imgproc.findContours(grayMatForCompare, contours, mHierarchy,
            Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE);
    return contours.iterator().next();
}

圖標的最外層輪廓,其中百度地圖為預置圖標

然後與一個「標準矩形圖標」的輪廓做比對,判斷是否需要改造:

public static boolean isBitmapNeedtoChange(MatOfPoint contour, MatOfPoint compareContour) {
    MatOfPoint2f approxContour = new MatOfPoint2f();
    MatOfPoint2f mMOP2f1 = new MatOfPoint2f();
    contour.convertTo(mMOP2f1, CvType.CV_32FC2);

    // 取得近似多邊形輪廓
    Imgproc.approxPolyDP(mMOP2f1, approxContour, Imgproc.CV_POLY_APPROX_DP, true);

    // 最小外接矩形
    org.opencv.core.Rect boundingRect = Imgproc.boundingRect(mMOP2f1);
    org.opencv.core.Rect boundingRectOfCompare = Imgproc.boundingRect(compareContour);

    DecimalFormat df = new DecimalFormat("######0.00");
    // 外接矩形面積與實際輪廓面積的差額比,用來衡量「有多接近矩形」
    double areaD = (boundingRect.area() - Imgproc.contourArea(approxContour)) / boundingRect.area();
    double rate1 = (double) boundingRect.width / (double) boundingRect.height;
    double rate2 = (double) boundingRectOfCompare.width / (double) boundingRectOfCompare.height;

    // 兩個條件同時滿足才認為已達標:
    // 1) 面積差額比足夠小;2) 長寬比與標準圖標的偏差足夠小
    if (areaD < 0.1 && Math.abs(rate1 - rate2) / rate2 < 0.05) {
        return true;
    }
    return false;
}

這兩個閾值(0.1 與 0.05)並非理論推導而來,而是安裝大量真實 APK、反覆對照視覺效果調出來的經驗值。

3.3 判斷是否需要加主色調背板

也就是判斷「原圖標是否為不規則形狀或尺寸偏小」。思路是取圖標邊界到輪廓中心線上若干點的距離,看它們是否大致相等,或輪廓到邊界的距離是否落在閾值內:

public static boolean shouldBitmapAddMainColorBg(Bitmap b, MatOfPoint contour, Context context) {
    org.opencv.core.Point[] contourArray = contour.toArray();
    Mat mat = new Mat();
    Utils.bitmapToMat(b.copy(Bitmap.Config.ARGB_8888, false), mat);

    int point2Didsance = mat.rows() / 4;
    org.opencv.core.Point tempPtXMiddle = new org.opencv.core.Point(mat.rows() / 2, 0);
    org.opencv.core.Point tempPtYMiddle = new org.opencv.core.Point(0, mat.cols() / 2);
    org.opencv.core.Point tempPtX2 = new org.opencv.core.Point(mat.rows() / 2 + point2Didsance, 0);
    org.opencv.core.Point tempPtY2 = new org.opencv.core.Point(0, mat.cols() / 2 + point2Didsance);

    MatOfPoint2f polygon = new MatOfPoint2f(contourArray);
    double positionCheckXMiddle = Imgproc.pointPolygonTest(polygon, tempPtXMiddle, true);
    double positionCheckYMiddle = Imgproc.pointPolygonTest(polygon, tempPtYMiddle, true);
    double positionCheckX2 = Imgproc.pointPolygonTest(polygon, tempPtX2, true);
    double positionCheckY2 = Imgproc.pointPolygonTest(polygon, tempPtY2, true);

    double distance = context.getResources().getDimensionPixelSize(R.dimen.visible_contour_distance);

    // 若兩組距離不一致,說明輪廓不是矩形邊線;若中點距離超出閾值,說明形狀不規則
    if (((Math.abs(positionCheckX2) != Math.abs(positionCheckXMiddle))
            || Math.abs(positionCheckY2) != Math.abs(positionCheckYMiddle))
            ? true
            : (Math.abs(positionCheckXMiddle) > distance || Math.abs(positionCheckYMiddle) > distance)) {
        return true;
    }
    return false;
}

這個方法樸素得甚至有點「土」,但實在沒想到更好的判據,後續再研究。

3.4 縮放並做圓角

滿足「場景三」條件時,按標準圖標比例縮放,並對可見矩形區域做圓角:

public static Bitmap bitmapAddRoundCorner(Context context, Bitmap bitmap, MatOfPoint contour,
                                          MatOfPoint compareContour, int iconSize) {
    org.opencv.core.Rect rect = getBitmapBoundingRect(contour);
    org.opencv.core.Rect compareRect = Imgproc.boundingRect(compareContour);

    float resizeRate = Math.abs((float) rect.height / (float) compareRect.height);
    float bitmatZoomedSize = resizeRate * iconSize;
    int resizeRectW = (int) (Math.abs(rect.width) * resizeRate);
    int resizeRectH = Math.abs(compareRect.height);

    Bitmap resizeBitmap = zoomBitmap(bitmap, bitmatZoomedSize, bitmatZoomedSize);

    Bitmap bg = Bitmap.createBitmap(iconSize, iconSize, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bg);
    int srcLeft = ((int) bitmatZoomedSize - resizeRectW) / 2;
    int srcTop = ((int) bitmatZoomedSize - resizeRectH) / 2;
    int dstLeft = (iconSize - resizeRectW) / 2;
    int dstTop = (iconSize - resizeRectH) / 2;

    Rect src = new Rect(srcLeft, srcTop, resizeRectW + srcLeft, resizeRectH + srcTop);
    Rect dst = new Rect(dstLeft, dstTop, resizeRectW + dstLeft, resizeRectH + dstTop);
    RectF rectf = new RectF(dst);

    Paint photoPaint = new Paint();
    photoPaint.setAntiAlias(true);
    photoPaint.setDither(true);
    int roundPx = context.getResources().getDimensionPixelSize(R.dimen.round_size);
    canvas.drawRoundRect(rectf, roundPx, roundPx, photoPaint);

    photoPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(resizeBitmap, src, dst, photoPaint);
    canvas.setBitmap(null);
    return bg;
}

3.5 取主色調並生成漸變背板

static Bitmap bitmapAddBgUseMainColor(Context context, Bitmap b) {
    final float FLAT_ASPECT_RATIO = 0.792f;
    int iconSize = getIconBitmapSize();
    int height = (int) (iconSize * FLAT_ASPECT_RATIO);

    // 從圖標的六色調色板中挑選主色
    Bitmap bg = FallbackAlgorithm.getProcessedIcon(context, b, new Point(iconSize, height));

    // 疊上預設的透明背板
    Drawable bg2 = context.getResources().getDrawable(R.drawable.carving);
    Bitmap blankbg = Bitmap.createBitmap(iconSize, iconSize, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(blankbg);
    bg2.setBounds(0, 0, iconSize, iconSize);
    bg2.draw(canvas);

    Paint p = new Paint();
    p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OVER));
    canvas.drawBitmap(bg, 0, (iconSize - bg.getHeight()) / 2, null);
    canvas.setBitmap(null);
    return blankbg;
}

取色與渲染的核心類 FallbackAlgorithm 要點如下:用 Palette 從原圖提取六種 Swatch(Vibrant、DarkVibrant、Muted、DarkMuted、LightVibrant、LightMuted),按一個經驗係數 POPULATION_STEP_COEF = 10 逐個比較人口/面積權重挑出最合適的一組;接著在 HSL 空間做修正(若色相落在 35°—70° 這個偏黃區間,就把飽和度壓到 0.2、亮度提到 0.8,避免背板過於刺眼);最後用 softlight 函數由主色推導出亮暗兩端,生成線性漸變,並以圓角矩形裁切、疊上帶模糊的陰影層。

public static Bitmap getProcessedIcon(Context context, Bitmap originalIcon, Point targetResolution) {
    Bitmap finalIcon = Bitmap.createBitmap(targetResolution.x, targetResolution.y, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(finalIcon);

    Palette palette = Palette.from(originalIcon).generate();
    ChosenSwatch chosenSwatch = new ChosenSwatch();
    chosenSwatch.updateChoice(palette.getVibrantSwatch());
    chosenSwatch.updateChoice(palette.getDarkVibrantSwatch());
    chosenSwatch.updateChoice(palette.getDarkMutedSwatch());
    chosenSwatch.updateChoice(palette.getMutedSwatch());
    chosenSwatch.updateChoice(palette.getLightMutedSwatch());
    chosenSwatch.updateChoice(palette.getLightVibrantSwatch());

    Palette.Swatch swatch = chosenSwatch.mSwatch;
    RGB rgb;
    if (swatch == null) {
        rgb = hsl2rgb(new HSL(50, 0.2f, 0.8f));
    } else {
        HSL hsl = new HSL(swatch.getHsl());
        if (hsl.h >= 35 && hsl.h < 70) {
            hsl.s = 0.2f;
            hsl.l = 0.8f;
        } else {
            hsl.l = Math.min(0.30f, 0.75f * hsl.l);
        }
        rgb = hsl2rgb(hsl);
    }

    RGB gradientLight = softlight(rgb, 0.75f);
    RGB gradientDark  = softlight(rgb, 0.25f);

    // 陰影層
    final int SHADOW_SCALE_DOWN = 4;
    Bitmap smallerOriginal = Bitmap.createScaledBitmap(originalIcon,
            originalIcon.getWidth() / SHADOW_SCALE_DOWN,
            originalIcon.getHeight() / SHADOW_SCALE_DOWN, true);
    BlurMaskFilter blur = new BlurMaskFilter(5, BlurMaskFilter.Blur.NORMAL);
    Paint blurPaint = new Paint();
    blurPaint.setMaskFilter(blur);
    blurPaint.setColor(Color.BLACK);
    int[] offsetXY = new int[2];
    Bitmap shadow = smallerOriginal.extractAlpha(blurPaint, offsetXY);

    // 漸變背板(圓角)
    Shader shader = new LinearGradient(0, 0, 0, finalIcon.getHeight(),
            gradientLight.getColor(), gradientDark.getColor(), Shader.TileMode.CLAMP);
    Paint paint = new Paint();
    paint.setShader(shader);
    int roundPx = context.getResources().getDimensionPixelSize(R.dimen.round_size);
    canvas.drawRoundRect(new RectF(0, 0, finalIcon.getWidth(), finalIcon.getHeight()), roundPx, roundPx, paint);

    // 依邊界留白與最小內容比例反推縮放係數
    final float BORDER_MARGIN = 1.25f;
    float maxRatio = Math.min(1f, Math.min(
            1f * finalIcon.getWidth()  / BORDER_MARGIN / originalIcon.getWidth(),
            1f * finalIcon.getHeight() / BORDER_MARGIN / originalIcon.getHeight()));
    final float MIN_CONTENT_SIZE = 1.618f;
    float minRatio = Math.max(
            1f * finalIcon.getWidth()  / MIN_CONTENT_SIZE / originalIcon.getWidth(),
            1f * finalIcon.getHeight() / MIN_CONTENT_SIZE / originalIcon.getHeight());
    float ratio = Math.max(maxRatio, minRatio);

    final float SHADOW_RATIO = 0.9f;
    float finalShadowWidth  = SHADOW_RATIO * ratio * (originalIcon.getWidth()  - 2 * SHADOW_SCALE_DOWN * offsetXY[0]);
    float finalShadowHeight = SHADOW_RATIO * ratio * (originalIcon.getHeight() - 2 * SHADOW_SCALE_DOWN * offsetXY[1]);
    float finalShadowLeft = (finalIcon.getWidth() - finalShadowWidth) / 2;
    float finalShadowTop  = (finalIcon.getHeight() - finalShadowHeight) / 2
                            - SHADOW_RATIO * SHADOW_SCALE_DOWN * offsetXY[1];
    Paint shadowPaint = new Paint();
    shadowPaint.setAlpha(0x40);
    shadowPaint.setFilterBitmap(true);
    canvas.drawBitmap(shadow, null,
            new RectF(finalShadowLeft, finalShadowTop,
                      finalShadowLeft + finalShadowWidth, finalShadowTop + finalShadowHeight), shadowPaint);

    float finalWidth  = ratio * originalIcon.getWidth();
    float finalHeight = ratio * originalIcon.getHeight();
    Paint iconPaint = new Paint();
    iconPaint.setFilterBitmap(true);
    canvas.drawBitmap(originalIcon, null,
            new RectF((finalIcon.getWidth() - finalWidth) / 2, (finalIcon.getHeight() - finalHeight) / 2,
                      (finalIcon.getWidth() + finalWidth) / 2, (finalIcon.getHeight() + finalHeight) / 2), iconPaint);
    return finalIcon;
}

其中 BORDER_MARGIN = 1.25、MIN_CONTENT_SIZE = 1.618、SHADOW_RATIO = 0.9、陰影 alpha 0x40 這幾個數字,全部都是依視覺效果反覆調出來的經驗值,代碼裡也相應標註了 Empirical value。

3.6 截圓加白背板

場景二與場景三篩選後的圖標,最終都走這條路徑。關鍵在於:先量出原圖標可見區域的實際寬高,再用「內接圓直徑 ÷ 較短邊」的比例去縮放,這樣圖標放進白背板後視覺大小才會一致:

public static Bitmap bitmapAddWhiteBg(Context context, int iconSize, Bitmap b, MatOfPoint contour) {
    org.opencv.core.Point[] contourArray = contour.toArray();
    Mat mat = new Mat();
    Utils.bitmapToMat(b.copy(Bitmap.Config.ARGB_8888, false), mat);

    // 從中心與邊緣共四個方向測量輪廓距離,推算出可見區域範圍
    org.opencv.core.Point tempPtXMiddle = new org.opencv.core.Point(mat.cols() / 2, 0);
    org.opencv.core.Point tempPtYMiddle = new org.opencv.core.Point(0, mat.rows() / 2);
    org.opencv.core.Point tempPtX2 = new org.opencv.core.Point(mat.cols() / 2, mat.rows());
    org.opencv.core.Point tempPtY2 = new org.opencv.core.Point(mat.cols(), mat.rows() / 2);

    MatOfPoint2f polygon = new MatOfPoint2f(contourArray);
    double positionCheckXMiddle = Math.abs(Imgproc.pointPolygonTest(polygon, tempPtXMiddle, true));
    double positionCheckYMiddle = Math.abs(Imgproc.pointPolygonTest(polygon, tempPtYMiddle, true));
    double positionCheckX2 = Math.abs(Imgproc.pointPolygonTest(polygon, tempPtX2, true));
    double positionCheckY2 = Math.abs(Imgproc.pointPolygonTest(polygon, tempPtY2, true));

    // 準備背板
    Drawable iconbgDrawable = context.getResources().getDrawable(R.drawable.baseboard);
    Bitmap addbg = Bitmap.createBitmap(iconSize, iconSize,
            iconbgDrawable.getOpacity() != PixelFormat.OPAQUE
                    ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
    Canvas canvasBg = new Canvas(addbg);
    iconbgDrawable.setBounds(0, 0, iconSize, iconSize);
    iconbgDrawable.draw(canvasBg);

    Paint p = new Paint();
    p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OVER));

    double visibleH = iconSize - positionCheckXMiddle - positionCheckX2;
    double visibleW = iconSize - positionCheckYMiddle - positionCheckY2;
    float innerCirleDiameter = context.getResources().getDimension(R.dimen.visible_inner_circle_d);
    float visibleWhiteBgH = context.getResources().getDimension(R.dimen.visible_whitle_bg_h);

    // 以「較短可見邊 ÷ 內接圓直徑」作為縮放基準,保證視覺尺寸統一
    double resizeRate = innerCirleDiameter / Math.min(visibleW, visibleH);
    double resizeIconsizeX = resizeRate * iconSize;
    double resizeIconsizeY = resizeRate * iconSize;
    double cutRateH = 1;

    // 若縮放後高度超出背板可見區,則需相應裁切
    if (visibleH * resizeRate > visibleWhiteBgH) {
        cutRateH = visibleWhiteBgH / visibleH;
        b = Bitmap.createBitmap(b, 0,
                Math.max(0, (int) ((b.getHeight() - b.getHeight() * cutRateH) / 2)),
                b.getWidth(), Math.min((int) (b.getHeight() * cutRateH), b.getHeight()),
                new Matrix(), true);
    }

    Bitmap resizeBitmap = zoomBitmap(b, (float) resizeIconsizeX, (float) resizeIconsizeY * (float) cutRateH);
    canvasBg.drawBitmap(resizeBitmap,
            (float) ((iconSize - resizeIconsizeX) / 2),
            (float) ((iconSize - resizeIconsizeY * cutRateH) / 2), p);
    canvasBg.setBitmap(null);
    return addbg;
}

四、最終效果

五、回顧與反思

整套方案的骨幹是「輪廓識別 → 分類判斷 → 分流處理」,OpenCV 在輪廓提取(findContours)、近似多邊形(approxPolyDP)、最小外接矩形(boundingRect)與內外判別(pointPolygonTest)這幾件事上確實稱手。

但也要承認方案的短板:絕大部分閾值都是靠大量真機樣本反覆調視覺效果定的,缺乏理論依據;「不規則形狀」的判定方法比較粗糙;而背板顏色單一這一類圖標的自動化處理始終沒有做出來,只能依賴預置圖標資源硬編碼。如果重做一次,我會優先嘗試基於模板匹配或輕量分類模型的方案,把這些經驗閾值換成更可解釋的判據。

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