2015-06-27 100 views
1

我在測試以下函數時不斷收到此錯誤。它應該對包含0到255像素顏色的圖像的值進行歸一化處理。我發現最小值和最大值將它們更改爲0和255,然後相應地更改所有中間值以適應以前相同的差異比例:浮點異常C

void normalize(uint8_t array[], 
     unsigned int cols, 
     unsigned int rows) 
{ 
    uint8_t minValue = 255; 
    uint8_t maxValue = 0; 

    for (int i = 0; i < cols*rows ; ++i) 
    { 
     if(array[i] < minValue) minValue = array[i]; 
    } 

    for (int i = 0; i < cols*rows; ++i) 
    { 
     if(array[i] < maxValue) maxValue = array[i]; 
    } 

    int difference1 = maxValue - minValue; 

    uint8_t ratios[cols*rows]; 

    for (int i = 0; i < cols*rows ; ++i){ 
    ratios[i] = 0; 
    } 

    //find the ratios 
    for (int i = 0; i < cols*rows ; ++i){ 
    ratios[i] = (array[i]/difference1) - 1; 
    } 

    for (int i = 0; i < cols*rows ; ++i){ 

    if(array[i] == minValue){ 
     array[i] = 0; 
    }else if(array[i] == maxValue){ 
     array[i] = 255; 
    }else{ 
     array[i] = round(ratios[i] * 255); 
    } 
    } 
} 
+2

你得到一個除以零錯誤時'difference1'爲零 –

+2

而'difference1'是0,因爲'minValue'等於' maxValue',只要圖像上有黑色像素。 – francis

+0

謝謝!我完全沒有看到if語句中的錯誤。 – user5056973

回答

2

錯誤計算最大值。

即使代碼應該如下,那不是全部。

// if(array[i] < maxValue) maxValue = array[i]; 
if(array[i] > maxValue) maxValue = array[i]; 

代碼應該仍然工作,如果所有的像素都是相同的顏色(difference1 == 0)。在這種情況下,一個簡單的解決方案是單獨離開array[]

int difference1 = maxValue - minValue; 
if (difference1 > 0) { 
    uint8_t ratios[cols*rows]; 
    ... 
     array[i] = round(ratios[i] * 255); 
    } 
    } 
} 
1

是這樣的正確嗎?

空隙正規化(uint8_t陣列[], 無符號整型COLS, 無符號整型行) {

//each pixel is rounded by 255 * (index-lowest_pixel_val_in_array) divided by (highest value pixel minus lowest value pixel) 

// your code here 
uint8_t minValue = 255; //255 means WHITE 
uint8_t maxValue = 0; // 0 MEANS BLACK 

for (int i = 0; i < cols*rows ; ++i) //PREINCREMENT means if i= 1 and j=++i=2/ 
{ 
    if(array[i] < minValue) 
minValue = array[i]; //make minimum value the array 

    if(array[i] > maxValue) 
maxValue = array[i]; //make maximum value for array 
} 

int difference = maxValue - minValue; //the difference is maximum - minimum 

// uint8_t比率[COLS *行數]; // CHANGED把這個INSIDE

if(difference > 0) //ENSURE MAX != MIN 
{ 
uint8_t ratios[cols*rows]; //CHANGED PUT THIS INSIDE 
for (int i = 0; i < cols*rows ; ++i) //PREINCREMENT means if i= 1 and j=++i. j becomes 2 but for i++ j wuld be 1 
{ 
     ratios[i] = 0; //SET IT 0 INTIALLY. 
     ratios[i] = (array[i]/difference) - 1; //subtract 1st pixel and CALCULATE RATIOS 


     if(array[i] == minValue) 
      { 
      array[i] = 0; //lightest becomes darkest 
      } 

     else if(array[i] == maxValue) 
     { 
      array[i] = 255; //darkest becomes lightest 
      } 

     else 
     { 
      array[i] = round(ratios[i] * 255); //ROUND THE PIXEL 
      } 
} 
} 

}