Skip to content
Advertisement

Why is this image method returning a black image?

I am running the code below. What it is supposed to do is equalize an image passed into it. All the methods and variables run fine except for newPixelVal which is always zero. This then makes my image all black. I cannot figure out why this is returning 0.

public GImage equalize(GImage source) {
        // TODO
        int[][] pixelArray = source.getPixelArray();
        int[] luminousArray = new int[257]; 
        int[] cumulativeLuminousArray = new int[257]; 
        int height = pixelArray.length;
        int width = pixelArray[0].length;
        int k =-1;
        int luminosity =0;
        int l=0;
        int[][]equalizedArray = new int[height][width];
        int newRed = 0;
        int newGreen = 0; 
        int newBlue = 0;
        int newPixelVal = 0;
        int pixelsLessThan = 0;
        int v = 0;
        int totalPixels = height*width;
        for (int i=0; i<height; i++) {
            for(int j=0;j<width;j++) {
                int pixel=pixelArray[i][j];
                int red = (pixel>>16)& 0xFF;
                int green = (pixel>>8)&0xFF;
                int blue=pixel&0xFF;
                
                luminosity = computeLuminosity(red, green, blue);
                luminousArray[luminosity] = luminousArray[luminosity] +1;
                
                
    }}
    
        while(k<=256) {
            k++;
            l=k;
            while(l>=0&&k<=256) {
                cumulativeLuminousArray[k] = cumulativeLuminousArray[k]+luminousArray[l];
                l--;
                
            }
        }
        for (int i=0; i<height; i++) {
            for(int j=0;j<width;j++) {
                int pixel=pixelArray[i][j];
                int red = (pixel>>16)& 0xFF;
                int green = (pixel>>8)&0xFF;
                int blue=pixel&0xFF;
        
                luminosity = computeLuminosity(red, green, blue);
                v = luminosity-1; 
                pixelsLessThan=cumulativeLuminousArray[v];
                newPixelVal = 255*(pixelsLessThan/totalPixels);
                newRed= newPixelVal; 
                newBlue = newPixelVal; 
                newGreen = newPixelVal;
                int newPixel = (0xFF<<24)|(newRed<<16)|(newGreen<<8)|newBlue;
                equalizedArray[i][j]=newPixel;

                
            }
        }
        return new GImage(equalizedArray);
    }

Advertisement

Answer

Got it! The division carried out at newPixelVal is between two int types. It will go to zero since the number of pixels less than is always less than total pixels. The decimal answer is truncated to 0. As soon as I replaced that with the line:

    newPixelVal = (int)(255*(float)pixelsLessThan/(float)totalPixels);

The calculation worked perfectly!

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement