Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sum of image pixels

I tried to sum pixels values on black and white area, through dividing the image into a grid of blocks and getting the sum of pixels for each block.

When I printed the values of each, the values were all the same = 255. My question is: Why does this happen? Some blocks have only black pixels and some have black and white?

double* divide (Mat I)
         {
             //double* pointer;
         static double*  sums= new double [9];
        //pointer= sums[0];
          //double sums2[10];

          Mat block;
              //Mat block2;

    int numberblocks=9; 
    int bh;
    int bw;
    //int bh2;
    //int bw2;

    bh=I.cols/numberblocks;
    bw=I.rows/numberblocks; 
    //bh2=u.cols/numberblocks;
    //bw2=u.rows/numberblocks; 
    //
    double blockarea=bh*bw;
    //double num=0;
    //double blockarea2=bh2*bw2;

    //int r=0;
    //int c=0;
    //int err=0;

    for(int a=0;a<9;a++)
    {
       for (int r = 0; r < I.rows; r += bw)
       {
             for (int c = 0; c < I.cols; c += bh)
                 {

                 block  = I(cv::Range(r, min(r + bw, I.rows)),cv::Range(c, min(c + bh, I.cols)));


                  }
       }
       double sum=0;

         for(int i=0;i<block.rows;i++)
         {
             for(int j=0;j<block.cols;j++)
                 {
                sums[a] = sum + block.at<uchar>(i,j); //sums[k-1] + block.at<uchar>(i,j);
             }
         }
         cout<<"sum of"<<a<<"is"<<sums[a]<<endl;


    }


return sums;

}    
like image 295
Storm2012 Avatar asked Jan 27 '26 10:01

Storm2012


2 Answers

I think this will do

     for(int i=0;i<block.rows;i++)
     {
         for(int j=0;j<block.cols;j++)
             {

              sum = sum + block.at<uchar>(i,j); //sums[k-1] + block.at<uchar>(i,j);
         }
     }
     sums[a]=sum;

Debug it to be sure. Without using sum it would be:

     for(int i=0;i<block.rows;i++)
     {
         for(int j=0;j<block.cols;j++)
             {

               sums[a] =  sums[a] + block.at<uchar>(i,j); //sums[k-1] + block.at<uchar>(i,j);
         }
     }         
like image 167
Jav_Rock Avatar answered Jan 28 '26 23:01

Jav_Rock


The row

sums[a] = sum + block.at(i,j);

looks strange. sums[a] has always the value of the last element of block. If this is by chance always 255, you have your explanation.

like image 24
Stefan Avatar answered Jan 29 '26 00:01

Stefan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!