Tolga Karahan
Tolga Karahan

Reputation: 69

Segmentation with Automatic Thresholding

I want to do image segmentation with automatic thresholding algorithm via C++, but my code didn't process image that I had expected. I used user-defined classes to load and save BMP and it did well to me. It's doing some good with some images but doesn't work with some images too. What do you suggest me to develop my code. Here is my code:

int Segmentation::getThreshold() {

    int distance[256] = { 0 };
    int t1 = 10;
    int t2 = 200;
    int t1O = 0;
    int t2O = 0;
    int threshold = 0;
    int meanT1 = 1000;
    int meanT2 = 2000;
    double sd1 = 1;
    double sd2 = 1;

    while (t1 != t1O || t2 != t2O) {

        int weighT1 = 0;
        int weighT2 = 0;
        meanT1 = 0;
        meanT2 = 0;

        for (int i = 0; i < 256; i++) {
            if (abs(histogram[t1] - histogram[i]) < abs(histogram[t2] - histogram[i]))
                distance[i] = 1;
            if (abs(histogram[t1] - histogram[i]) >= abs(histogram[t2] - histogram[i]))
                distance[i] = 2;
        }

        for (int j = 0; j < 256; j++) {
            if (distance[j] == 1) {
                meanT1 += histogram[j] * j;
                weighT1 += histogram[j];
            }
            if (distance[j] == 2) {
                meanT2 += histogram[j] * j;
                weighT2 += histogram[j];
            }
        }

        meanT1 = meanT1 / weighT1;
        meanT2 = meanT2 / weighT2;

        if (histogram[meanT1] != histogram[t1O] || histogram[meanT2] != histogram[t2O]) {
            t1O = t1;
            t1 = meanT1;
            t2O = t2;
            t2 = meanT2;
        }
        else {
            t1 = meanT1;
            t2 = meanT2;
            break;
        }


    }
    threshold = (t1 + t2) / 2;
    cout << "Threshold is: " << threshold << endl;
    return threshold;

    void Segmentation::getSegmentation() {

        int threshold;
        threshold = getThreshold();

        for (int i = 0; i<width; i++)
            for (int j = 0; j < height; j++) {
                if (histogram[img[width*i + j]] > histogram[threshold])
                    img[width*i + j] = 0;
                else
                    img[width*i + j] = 255;
            }
    }

Upvotes: 0

Views: 491

Answers (1)

user1196549
user1196549

Reputation:

Replace

histogram[img[width*i + j]] > histogram[threshold]

by

img[width*i + j] > threshold

Upvotes: 1

Related Questions