Login  Register

Re: Pulling average color from a selection

Posted by Wayne Rasband on Jun 13, 2008; 5:27pm
URL: http://imagej.273.s1.nabble.com/Pulling-average-color-from-a-selection-tp3695920p3695921.html

Andy,

The Calculate_Mean plugin at

     http://rsb.info.nih.gov/ij/plugins/calculate-mean.html

demonstrates how to work with non-rectangular selections.

-wayne


On Jun 13, 2008, at 1:01 PM, Andy wrote:

> 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
>