0

Lets say I have array of 1000 composed only of the values 0,1,2,3. What I want to do is remove the odd value in a sea of other values, eg. 0,0,0,0,0,1,0,0,0,0 --> 0,0,0,0,0,0,0,0,0,0. A simple moving average doesn´t really work because I always have to return the values 0,1,2,3, so averaging across 0,3,0 --> 1 and that is wrong. I came up with this that appears to do the job, but I was wondering if there is a method to do it more efficiently and nicer. This is for an ImageJ macro.

r = 7; //window length
for(j=r; j<lengthOf(armsPosition)-r;j++){
    count0 = 0; count1 = 0; count2=0;count3 = 0;
    for(m = j - r/2; m <= j + r/2; m++){
        if(armsPosition[m] == 0)
            count0++;
        else if(armsPosition[m] == 1)
            count1++;
        else if(armsPosition[m] == 2)
            count2++;
        else
            count3++;

    }

    if(count0 >= count1 && count0 >= count2 && count0 >= count3)
        armsPositionA[j]=0;
    else if(count1 > count0 && count1 > count2 && count1 > count3)
        armsPositionA[j]=1;
    else if(count2 > count0 && count2 > count1 && count2 > count3)
        armsPositionA[j]=2;
    else 
        armsPositionA[j]=3;
}

Thanks,

hadroque
  • 15
  • 4

1 Answers1

0

If you're not limited to ImageJ's macro language, but open for using any of the supported scripting languages, you can use the StatUtils.mode(double[] sample, int begin, int length) method from Apache commons-math.

The following Groovy script illustrates this:

import org.apache.commons.math3.stat.StatUtils

a = [1,3,4,21,3,2,21,21,21,21,21,21,4,3,5,2,2,1,1,1,1]

println StatUtils.mode((double[])a, 0, 7)

Hope that helps.

Jan Eglinger
  • 3,995
  • 1
  • 25
  • 51
  • Thanks. I have been thinking about changing the whole macro to either scripting or to a full pledge plugin even though that would require quite a lot of learning time, something I don´t really have a the moment. – hadroque May 31 '17 at 14:10