Multi-Level Thresholding. Otsu's Method
<p>I know this Question is a possible duplicate of <a href="https://stackoverflow.com/questions/22706742/multi-otsumulti-thresholding-with-opencv">Multi otsu(multi-thresholding) with openCV</a> as it's very similar. But I don't have enough privileges to make a comment on that so my question is answered.  </p>

<p>I'm trying to do THREE level threshold using Otsu's method using OPENCV library. I was following the guides posted by @Antoni4, but it only covers two-level thresholding and I wasn't able to expand it to three level.</p>

<p>I know how to original Otsu's method works, maximizing the between class variance, but how I could add an external (or internal) for-loop for calculating the third level threshold I did not know.</p>

<p>I'm using this code for the two-level thresholding:</p>

<pre><code>#include "Shadow01-1.cuh"

void multiThresh(double &amp;optimalThresh1, double &amp;optimalThresh2,double &amp;optimalThresh3, cv::Mat &amp;imgHist, cv::Mat &amp;src) {
double W0K, W1K, W2K, W3K, M0, M1, M2, M3, currVarB, maxBetweenVar, M0K, M1K, M2K, M3K, MT;

unsigned char *histogram = (unsigned char*)(imgHist.data);

int N = src.rows*src.cols;
W0K = 0;
W1K = 0;
M0K = 0;
M1K = 0;
MT = 0;
maxBetweenVar = 0;

for (int k = 0; k &lt;= 255; k++) {
    MT += k * (histogram[k] / (double) N);
}

for (int t1 = 0; t1 &lt;= 255; t1++)
{
    W0K += histogram[t1] / (double) N; //Pi
    M0K += t1 * (histogram[t1] / (double) N); //i * Pi
    M0 = M0K / W0K; //(i * Pi)/Pi

    W1K = 0;
    M1K = 0;

    for (int t2 = t1 + 1; t2 &lt;= 255; t2++)
    {
        W1K += histogram[t2] / (double) N; //Pi
        M1K += t2 * (histogram[t2] / (double) N); //i * Pi
        M1 = M1K / W1K; //(i * Pi)/Pi
        W2K = 1 - (W0K + W1K);
        M2K = MT - (M0K + M1K);

        if (W2K &lt;= 0) break;

        M2 = M2K / W2K;

        currVarB = W0K * (M0 - MT) * (M0 - MT) + W1K * (M1 - MT) * (M1 - MT) + W2K * (M2 - MT) * (M2 - MT);

        if (maxBetweenVar &lt; currVarB)
        {
            maxBetweenVar = currVarB;
            optimalThresh1 = t1;
            optimalThresh2 = t2;
        }

    }
}
</code></pre>

<p>}</p>

<p>I actually don't what are those two lines:</p>

<pre><code>W2K = 1 - (W0K + W1K);
M2K = MT - (M0K + M1K);
</code></pre>

<p>And how I could expand them for the third threshold.</p>

<p>Thanks in advance.</p>