Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import android.graphics.Bitmap;

import android.graphics.Color;

public class Main {
    public static Bitmap binarize(Bitmap bmp) {
        int threshold = Math.round(getOtsuThreshold(bmp));
        int width = bmp.getWidth();
        int height = bmp.getHeight();
        int[] pixels = new int[width * height];
        bmp.getPixels(pixels, 0, width, 0, 0, width, height);

        for (int i = 0; i < width * height; i++) {
            int p = 0;
            if (Color.red(pixels[i]) > threshold)
                p = 255;
            pixels[i] = Color.rgb(p, p, p);
        }

        return Bitmap.createBitmap(pixels, width, height, bmp.getConfig());
    }

    private static int getOtsuThreshold(Bitmap bmp) {
        int[] histogram = getHistogram(bmp);
        int pixelCount = bmp.getWidth() * bmp.getHeight();

        float sum = 0.0f;
        for (int i = 0; i < 256; i++)
            sum += i * histogram[i];

        float sumB = 0.0f;
        int wB = 0;
        float varMax = 0.0f;
        int threshold = 0;

        for (int i = 0; i < 256; i++) {
            wB += histogram[i];
            if (wB == 0)
                continue;
            int wF = pixelCount - wB;

            if (wF == 0)
                break;

            sumB += (float) (i * histogram[i]);
            float mB = sumB / wB;
            float mF = (sum - sumB) / wF;

            float varBetween = (float) wB * (float) wF * (mB - mF) * (mB - mF);

            if (varBetween > varMax) {
                varMax = varBetween;
                threshold = i;
            }
        }

        return threshold;
    }

    /**
     * Return histogram of grayscaled image
     */
    public static int[] getHistogram(Bitmap bmp) {
        int[] histogram = new int[256];
        int width = bmp.getWidth();
        int height = bmp.getHeight();
        int[] pixels = new int[width * height];
        bmp.getPixels(pixels, 0, width, 0, 0, width, height);

        for (int i = 0; i < width * height; i++) {
            int c = Color.red(pixels[i]);
            histogram[c] += 1;
        }

        return histogram;
    }
}