Generating gamma corrected mipmap

Hi guys, I have been trying to produce gamma corrected mipmap with the following code, the idea is do gamma correction before averaging the 4 sample points from a previous mipmap level.
But my mipmap still looks darker after each level. What am i doing wrong here?

I am using 15bits color representation, thats 32 different intensity levels for red, green blue.



//get normalized color form previous mipmap level
double r1 = (double)((mipmap[i-1][index1]& 31744) >> 10)/31;
double r2 = (double)((mipmap[i-1][index2]& 31744) >> 10)/31;
double r3 = (double)((mipmap[i-1][index3]& 31744) >> 10)/31;
double r4 = (double)((mipmap[i-1][index4]& 31744) >> 10)/31;
			
double g1 = (double)((mipmap[i-1][index1] & 992) >> 5)/31;
double g2 = (double)((mipmap[i-1][index2] & 992) >> 5)/31;
double g3 = (double)((mipmap[i-1][index3] & 992) >> 5)/31;
double g4 = (double)((mipmap[i-1][index4] & 992) >> 5)/31;
							
double b1 = (double)(mipmap[i-1][index1] & 31)/31;
double b2 = (double)(mipmap[i-1][index2] & 31)/31;
double b3 = (double)(mipmap[i-1][index3] & 31)/31;
double b4 = (double)(mipmap[i-1][index4] & 31)/31;
							
//use gamma = 2.2
double gamma = 2.2;
							
//raises color value to the power gamma
r1 = Math.pow(r1, gamma);
r2 = Math.pow(r2, gamma);
r3 = Math.pow(r3, gamma);
r4 = Math.pow(r4, gamma);
							
g1 = Math.pow(g1, gamma);
g2 = Math.pow(g2, gamma);
g3 = Math.pow(g3, gamma);
g4 = Math.pow(g4, gamma);
							
b1 = Math.pow(b1, gamma);
b2 = Math.pow(b2, gamma);
b3 = Math.pow(b3, gamma);
b4 = Math.pow(b4, gamma);
							
							
//average the color from 4 samples, then raise to the resultant color value to the power 1/gamma
int r_average = (int)(Math.pow((r1 + r2 + r3 + r4)/4, 1.0/gamma) * 31); 
int g_average = (int)(Math.pow((g1 + g2 + g3 + g4)/4, 1.0/gamma) * 31); 
int b_average = (int)(Math.pow((b1 + b2 + b3 + b4)/4, 1.0/gamma) * 31); 
						
//write to texture memory
mipmap[i][k + j*w] = (short)(r_average <<10 | g_average << 5 | b_average);


mm strange looks right to me, what color do you get when you create a mipmap of a black & withe picture?

This effectively rounds down for every mipmap level, and with only 32 brightness levels per channel, I think this can very well account for the progressive darkening you are seeing.

Instead of simply using Math.round(…) I’d advice you to do mipmapping using floats, all the way through, and as the very last step, convert your float data images to whatever compact format you desire. That way rounding errors won’t accumulate.

public void mipmap(float[3][w*h] rgbIn, float[3][w/2*h/2] rgbOut)