使用自动阈值进行分段

Segmentation with Automatic Thresholding

本文关键字:分段 阈值      更新时间:2023-10-16

我想通过C++使用自动阈值算法进行图像分割,但我的代码没有处理我预期的图像。我使用用户定义的类来加载和保存 BMP,它对我来说做得很好。它对某些图像有好处,但对某些图像也不起作用。你建议我开发我的代码是什么。这是我的代码:

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;
            }
    }

替换

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

img[width*i + j] > threshold