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???
Please help me.
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); }
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: