Login  Register

Re: Smoothing a ROI

Posted by Gabriel Landini on Feb 13, 2011; 8:59pm
URL: http://imagej.273.s1.nabble.com/Smoothing-a-ROI-tp3685699p3685701.html

Thanks Dscho for the suggestion.
I ended up thinning the ROI coordinates. Maybe this is useful to somebody
else, so below is the macro.
If somebody spots any problems or improves it please let me know.

Cheers
Gabriel

//---------------------8<-------------------
// smooth_ROI.txt
// G. Landini at bham. ac. uk
// 13/2/2011
// Performs a running average of size 3 on a closed ROI to smooth it

sel=selectionType();
if (sel <2 ||sel>4)
     exit("Only freehand closed ROIs are supported.");

getSelectionCoordinates(x, y);
run("Select None");
makeSelection("polygon", x, y);

l=x.length;
print(l);
nx=newArray(l);
ny=newArray(l);

for (i=1;i<l-1;i++){
 nx[i]=round(((x[i-1]+x[i]+x[i+1])/3)+random-0.5);
 ny[i]=round(((y[i-1]+y[i]+y[i+1])/3)+random-0.5);
}

// l-2 because last coordinate==first
nx[0]=round(((x[l-2]+x[0]+x[1])/3)+random-0.5);
ny[0]=round(((y[l-2]+y[0]+y[1])/3)+random-0.5);
//last
nx[l-1]=nx[0];
ny[l-1]=ny[0];

run("Select None");

// count how many are overlapping
tot=0;
for (i=1;i<l;i++){
  if ( (nx[i]== nx[i-1]) && (ny[i] == ny[i-1] ) )
    tot++;
}

if (tot>0) {
   nex=newArray(l-tot);
   ney=newArray(l-tot);
   nex[0]=nx[0];
   ney[0]=ny[0];

   st=0;
   for (j=1;j<l;j++){
      if ((nx[j]  != nx[j-1]) || (ny[j] != ny[j-1]) )  {
        st++;
        nex[st]=nx[j];
        ney[st]=ny[j];
      }
   }
   nex[l-tot-1]=nex[0];
   ney[l-tot-1]=ney[0];
   makeSelection("polygon", nex, ney);
}
else
   makeSelection("polygon", nx, ny);
 
//---------------------8<-------------------