0

This site gives an implementation of the approach with between class variance. I want, however, to do it with within class variance(unfortunately I can't post the formula, but you can see it on the site), which is considered to be slower. This is my approach:

double varb,varf = 0;
int sum,wB,wF,treshold = 0 
double varMin = Float.MAX_VALUE;
for (int t=0 ; t<256; t++) {
    for(int i =1; i <=t; i++) {
        sum+= i*hist[i];
    }
    for(int i =1; i <=t; i++) {
        wB += hist[i];
    }
    sumB += (float) (t * histo[t]);
    wF = N - wB;
    double mB =(double) N*sumB / wB; // Mean Background
    double mF = (double) N*(sum - sumB) / wF; // sum is the sum of all grey values

    for(int i =1; i <=t; i++) {
        varb += (i-mB)*(i-mB)*(hist[i]/N)/wB;
    }
    for(int i =t+1; i <256; i++) {
        varb += (i-mF)*(i-mF)*(hist[i]/N)/wF;
    }
    double var = wB*varb/N + wF * varf/N;
    if (var < varMin) {  //checks for the smallest variance
        varMin = var;
        threshold = t;
    }
}

I am getting always zero. What can I do?

Dreikäsehoch
  • 131
  • 2
  • 7

1 Answers1

1

There is an obvious bug in the code in all the 4 loops that you use to accumulate values for a given t:

for(int i =1; i <=t; i++) {
    sum+= i*hist[i];
}
for(int i =1; i <=t; i++) {
    wB += hist[i];
}

sum and wB are not reset before these loops, meaning that, for each new t, you add these values to those computed for previous t. Correct is:

sum = 0;
wB = 0;
for(int i =1; i <=t; i++) {
    sum+= i*hist[i];
    wB += hist[i];    // (also no need for looping twice over `hist`)
}

The other two loops:

for(int i =1; i <=t; i++) {
    varb += (i-mB)*(i-mB)*(hist[i]/N)/wB;
}
for(int i =t+1; i <256; i++) {
    varb += (i-mF)*(i-mF)*(hist[i]/N)/wF;
}

Here the same happens, but also you use varb twice, and never use varf. Correct:

varb = 0;
varf = 0;
for(int i =1; i <=t; i++) {
    varb += (i-mB)*(i-mB)*(hist[i]/N)/wB;
}
for(int i =t+1; i <256; i++) {
    varf += (i-mF)*(i-mF)*(hist[i]/N)/wF;
}

Your code doesn't show where you compute sumGrayvalues and mitt, let's assume you did those right. Then you can also see that sum and wB can be computed from the previous iteration of t, by adding just a single element from hist.

(I haven't run the code, I don't do Java, so I'm not sure if there are other issues.)

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120