浮点异常C

时间:2015-06-27 21:41:15

标签: c exception floating-point

我在测试以下功能时不断收到此错误消息。它应该规范化包含颜色0到255的像素的图像的值。我找到了最小值和最大值,将它们更改为0和255,然后相应地更改了所有中间值,以适应之前相同的差异比率:

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 个答案:

答案 0 :(得分:2)

错误计算`max。

即使代码应如下所示,也不是全部。

// 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 :(得分:1)

这样的事情是否正确?

void normalize(uint8_t array [],         unsigned int cols,         unsigned int rows) {

//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 ratios [cols * rows]; //改变了这个内部

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

}