# Problem of "uchar"

I want to calculate average value in a rectangle without Invalid value(0).
But outputs of my program have problem. num_valid = 0, sumValue = 0 and outputValue = -nan.
Why???

        int num_valid=0;
int sumValue=0;
for(int row = selectRect.y; row < selectRect.height; row++)  //selectRect is a rectangle
{
for(int col=selectRect.x; col<selectRect.width; col++)
{
uchar value = outputImage[RIGHT].at<uchar>(row, col);  //outputImage[RIGHT] is a grayImage
if(value != 0)
{
num_valid++;
sumValue += value;
}
}
}
if(num_valid > selectRect.width * selectRect.height / 2){
printf("invalid\n");
}
else{
float outputValue = sumValue / num_valid;
printf("Out: %d / %d = %f \n", sumValue, num_valid, outputValue);
}

edit retag close merge delete

you probably should not write loops like that in the 1st place , but use countNonZero() and sum().

then even IF your region is not all black, you need to avoid integer division here:

float outputValue = float(sumValue) / num_valid;


Sort by » oldest newest most voted

maybe

 float outputValue = (float)sumValue / (float)num_valid;


or

 float outputValue = (float)( sumValue / num_valid);

more

please use meanStdDev() to find the average pixel value of your ROI, DO NOT WRITE YOUR OWN LOOPS !

Mat roi = img(selectRect);
Scalar m,s;
meanStdDev(roi, m, s);
double avgPixel = m;

more

that would not be exactly the average value, right ? but IF you need this, it would be:

sum(roi) / countNonZero(roi);


Official site

GitHub

Wiki

Documentation