Ask Your Question
0

Problem of "uchar"

asked 2017-05-11 05:30:55 -0500

nistar gravatar image

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);
        }
edit retag flag offensive close merge delete

Comments

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;
berak gravatar imageberak ( 2017-05-11 05:45:40 -0500 )edit

2 answers

Sort by ยป oldest newest most voted
0

answered 2017-05-11 10:45:04 -0500

Laurentiu gravatar image

maybe

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

or

 float outputValue = (float)( sumValue / num_valid);
edit flag offensive delete link more
0

answered 2017-05-11 05:51:48 -0500

berak gravatar image

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[0];
edit flag offensive delete link more

Comments

But how to eliminate the point of value 0

nistar gravatar imagenistar ( 2017-05-15 00:56:17 -0500 )edit

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

sum(roi)[0] / countNonZero(roi);
berak gravatar imageberak ( 2017-05-15 01:07:16 -0500 )edit
Login/Signup to Answer

Question Tools

1 follower

Stats

Asked: 2017-05-11 05:30:55 -0500

Seen: 87 times

Last updated: May 11 '17