Take Monochrome Picture (black And White) With Android
Solution 1:
If you like the image to be 1bit black/white you can use a simple (& slow) threshold algorithm
publicstatic Bitmap createBlackAndWhite(Bitmap src) {
intwidth= src.getWidth();
intheight= src.getHeight();
// create output bitmapBitmapbmOut= Bitmap.createBitmap(width, height, src.getConfig());
// color informationint A, R, G, B;
int pixel;
// scan through all pixelsfor (intx=0; x < width; ++x) {
for (inty=0; y < height; ++y) {
// get pixel color
pixel = src.getPixel(x, y);
A = Color.alpha(pixel);
R = Color.red(pixel);
G = Color.green(pixel);
B = Color.blue(pixel);
intgray= (int) (0.2989 * R + 0.5870 * G + 0.1140 * B);
// use 128 as threshold, above -> white, below -> blackif (gray > 128)
gray = 255;
elsegray=0;
// set new pixel color to output bitmap
bmOut.setPixel(x, y, Color.argb(A, gray, gray, gray));
}
}
return bmOut;
}
But depending on what that will not look good, for better results you need a dithering algorithm, see Algorithm overview - this one is the threshold method.
For 256 levels of gray conversion:
according to http://www.mathworks.de/help/toolbox/images/ref/rgb2gray.html you calculate the gray value of each pixel as gray = 0.2989 * R + 0.5870 * G + 0.1140 * B
which would translate to
publicstatic Bitmap createGrayscale(Bitmap src) {
intwidth= src.getWidth();
intheight= src.getHeight();
// create output bitmapBitmapbmOut= Bitmap.createBitmap(width, height, src.getConfig());
// color informationint A, R, G, B;
int pixel;
// scan through all pixelsfor (intx=0; x < width; ++x) {
for (inty=0; y < height; ++y) {
// get pixel color
pixel = src.getPixel(x, y);
A = Color.alpha(pixel);
R = Color.red(pixel);
G = Color.green(pixel);
B = Color.blue(pixel);
intgray= (int) (0.2989 * R + 0.5870 * G + 0.1140 * B);
// set new pixel color to output bitmap
bmOut.setPixel(x, y, Color.argb(A, gray, gray, gray));
}
}
return bmOut;
}
But that is pretty slow since you have to do that for millions of pixels separately.
https://stackoverflow.com/a/9377943/995891 has a much nicer way of achieving the same.
// code from that answer put into method from abovepublicstatic Bitmap createGrayscale(Bitmap src) {
intwidth= src.getWidth();
intheight= src.getHeight();
BitmapbmOut= Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvascanvas=newCanvas(bmOut);
ColorMatrixma=newColorMatrix();
ma.setSaturation(0);
Paintpaint=newPaint();
paint.setColorFilter(newColorMatrixColorFilter(ma));
canvas.drawBitmap(src, 0, 0, paint);
return bmOut;
}
Solution 2:
G = Color.red(pixel);
G = Color.green(pixel);
B = Color.red(pixel);
B = Color.blue(pixel);
See if this changes (in bold) helps.
Post a Comment for "Take Monochrome Picture (black And White) With Android"