圖片二值化 和灰度處理方法


直接上代碼了

/**
 * 圖片灰度化和二值化處理
 * Created by kaifa on 2016/2/14.
 */
public class ImageFilter {
    /**
     * 圖片灰度處理
     *
     * @return
     */
    public static Bitmap grayScale(Bitmap bitmap) {
        int width, height;
        height = bitmap.getHeight();
        width = bitmap.getWidth();
        Bitmap bmpGray = null;
        bmpGray = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmpGray);
        Paint paint = new Paint();
        ColorMatrix cm = new ColorMatrix();
        cm.setSaturation(0);
        ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
        paint.setColorFilter(f);
        c.drawBitmap(bitmap, 0, 0, paint);

        return bmpGray;
    }

    /**
     * 圖片二值化處理
     *
     * @param bitmap
     * @return
     */
    public static Bitmap binaryzation(Bitmap bitmap) {

        //得到圖形的寬度和長度  
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        //創建二�?化圖像 �?
        Bitmap binarymap = null;
        binarymap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
        //依次循環,對圖像的像素進行處理 �?
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                //得到當前像素的�?  
                int col = binarymap.getPixel(i, j);
                //得到alpha通道的�?  
                int alpha = col & 0xFF000000;
                //得到圖像的像素RGB的�?  
                int red = (col & 0x00FF0000) >> 16;
                int green = (col & 0x0000FF00) >> 8;
                int blue = (col & 0x000000FF);
                // 用公式X = 0.3×R+0.59×G+0.11×B計算出X代替原來的RGB  
                int gray = (int) ((float) red * 0.3 + (float) green * 0.59 +
                        (float) blue * 0.11);
                //對圖像進行二值化處理  
                if (gray <= 95) {
                    gray = 0;
                } else {
                    gray = 255;
                }
                // 新的ARGB  
                int newColor = alpha | (gray << 16) | (gray << 8) | gray;
                //設置新圖像的當前像素值 �?
                binarymap.setPixel(i, j, newColor);
            }
        }
        return binarymap;
    }
}

忘了在哪里找的了,反正分享出來吧


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM