Pulling average color from a selection

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Pulling average color from a selection

Andy-92
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
Reply | Threaded
Open this post in threaded view
|

Re: Pulling average color from a selection

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