2017-04-03 78 views
0

我想通過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; 
      } 
    } 

回答

1

通過

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

謝謝,夥計更換

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

。它提供了更好的結果。 –