I am trying to convert color image into grayscale using the average of red, green, blue. But it comes out with errors.
Here is my code
imgWidth = myBitmap.getWidth(); imgHeight = myBitmap.getHeight(); for(int i =0;i<imgWidth;i++) { for(int j=0;j<imgHeight;j++) { int s = myBitmap.getPixel(i, j)/3; myBitmap.setPixel(i, j, s); } } ImageView img = (ImageView)findViewById(R.id.image1); img.setImageBitmap(myBitmap);
But when I run my application on Emulator, it's force close. Any idea?
I have solved my problem use the following code:
for(int x = 0; x < width; ++x) { for(int y = 0; y < height; ++y) { // get one pixel color pixel = src.getPixel(x, y); // retrieve color of all channels A = Color.alpha(pixel); R = Color.red(pixel); G = Color.green(pixel); B = Color.blue(pixel); // take conversion up to one single value R = G = B = (int)(0.299 * R + 0.587 * G + 0.114 * B); // set new pixel color to output bitmap bmOut.setPixel(x, y, Color.argb(A, R, G, B)); } }
Right-click the picture that you want to change, and then click Format Picture on the shortcut menu. Click the Picture tab. Under Image control, in the Color list, click Grayscale or Black and White.
For grayscale images, the result is a two-dimensional array with the number of rows and columns equal to the number of pixel rows and columns in the image. Low numeric values indicate darker shades and higher values lighter shades. The range of pixel values is often 0 to 255.
The main reason why grayscale representations are often used for extracting descriptors instead of operating on color images directly is that grayscale simplifies the algorithm and reduces computational requirements.
I = rgb2gray( RGB ) converts the truecolor image RGB to the grayscale image I . The rgb2gray function converts RGB images to grayscale by eliminating the hue and saturation information while retaining the luminance. If you have Parallel Computing Toolbox™ installed, rgb2gray can perform this conversion on a GPU.
You can do this too :
ColorMatrix matrix = new ColorMatrix(); matrix.setSaturation(0); imageview.setColorFilter(new ColorMatrixColorFilter(matrix));
Try the solution from this previous answer by leparlon:
public Bitmap toGrayscale(Bitmap bmpOriginal) { int width, height; height = bmpOriginal.getHeight(); width = bmpOriginal.getWidth(); Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); Canvas c = new Canvas(bmpGrayscale); Paint paint = new Paint(); ColorMatrix cm = new ColorMatrix(); cm.setSaturation(0); ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm); paint.setColorFilter(f); c.drawBitmap(bmpOriginal, 0, 0, paint); return bmpGrayscale; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With