Login  Register

Pulling average color from a selection

Posted by Andy-92 on Jun 13, 2008; 5:01pm
URL: http://imagej.273.s1.nabble.com/Pulling-average-color-from-a-selection-tp3695920.html

Hi,
I am trying to calculate the average color of a selection in an image.  The
code I am using seems to pull the average color from the ENTIRE image.

  int[] getAvgColor(Roi roi)
    {
        ImagePlus img = IJ.currentImage();
        img.setRoi(roi);
        ImageProcessor ip = img.getProcessor().duplicate();
        ip = ip.crop();
        ColorProcessor cp = (ColorProcessor)ip;
        int[] avgColor = { 0, 0, 0 };
        int pixNum = cp.getPixelCount();
        IJ.showMessage("PixCount: " + pixNum);
        byte[] r=new byte[pixNum];
        byte[] g=new byte[pixNum];
        byte[] b=new byte[pixNum];
        cp.getRGB(r, g, b);
        int ii;
        for (ii = 0; ii < r.length; ii ++) // each row
        {
            avgColor[0] += ((Byte)r[ii]).intValue();
            avgColor[1] += ((Byte)g[ii]).intValue();
            avgColor[2] += ((Byte)b[ii]).intValue();
        }
        avgColor[0] /= ii;
        avgColor[1] /= ii;
        avgColor[2] /= ii;
        return avgColor;
    }

I don't know why the ip.crop() seems to do nothing.

Thanks in advance!
--Andrew