Tuesday, 6 August 2013

ArrayIndexOutOfBoundsException while calculating Mean / Average values from array of pixels

ArrayIndexOutOfBoundsException while calculating Mean / Average values
from array of pixels

I am trying to implement a Mean/Average 3x3 filter in Android using Bitmaps.
The application keeps on shutting down everytime I try to apply this
filter. The error I get ArrayIndexOutOfBoundsException when I try to apply
this filter on an image.
My code is as follows:
protected Bitmap filterImage(Bitmap image) {
int width = image.getWidth();
int height = image.getHeight();
// 3x3
int size = 3;
int filterWidth = size;
int filterHeight = size;
int A = 0, R, G, B;
int[] pixels = new int[width * height];
image.getPixels(pixels, 0, width, 0, 0, width, height);
//int tempR, tempG, tempB;
int meanR = 0;
int meanG = 0;
int meanB = 0;
int[] RArray = new int[filterWidth * filterHeight];
int[] GArray = new int[filterWidth * filterHeight];
int[] BArray = new int[filterWidth * filterHeight];
int sumR;
int sumG;
int sumB;
Bitmap returnBitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int index = 0;
for (int filterX = -filterWidth / 2; filterX < filterWidth /
2; filterX++) {
for (int filterY = -filterHeight / 2; filterY <
filterHeight / 2; filterY++) {
A = (pixels[x+filterX+width*(y+filterY)])>>24 & 0xFF;
R = (pixels[x+filterX+width*(y+filterY)] >> 16) & 0xFF;
G = (pixels[x+filterX+width*(y+filterY)] >> 8) & 0xFF;
B = pixels[x+filterX+width*(y+filterY)] & 0xFF;
RArray[index] = R;
GArray[index] = G;
BArray[index] = B;
++index;
}
}
sumR = 0;
sumG = 0;
sumB = 0;
for (int i = 0; i < RArray.length; i++) {
sumR += RArray[i];
sumG += GArray[i];
sumB += BArray[i];
}
meanR = sumR / RArray.length;
meanG = sumG / GArray.length;
meanB = sumB / BArray.length;
returnBitmap.setPixel(x, y, Color.argb(A, meanR, meanG, meanB));
}
}
return returnBitmap;
}

No comments:

Post a Comment