2/19/2013

Mean, Covariance calculate source code from 2D data

The function "Get_M_C" calculates mean, covriance value of 2D data.
Input value of the function is 2D vector.
Ouput is struct that include 6 elements is consisted by 2x1 means and 2x2 covariance.


struct mean_cov{
 float mean11;
 float mean21;

 float cov11;
 float cov12;
 float cov21;
 float cov22;
};



mean_cov Get_M_C(vector< pair > &vecMC ){

 mean_cov smc;
 memset(&smc, 0, sizeof(float) * 6 );
 
 //mean first, second
 float sum_1=0;
 float sum_2=0;
 float sum_3=0;

 //mean
 int i;
 for(i=0; i < vecMC.size(); ++i)
 {
  sum_1 = sum_1 + vecMC[i].first;
  sum_2 = sum_2 + vecMC[i].second;  
 }
 smc.mean11 = sum_1 / vecMC.size();
 smc.mean21 = sum_2 / vecMC.size();

 sum_1 = 0;
 sum_2 = 0;
 sum_3 = 0;
 for(i=0; i < vecMC.size(); ++i)
 {
  sum_1 = sum_1 + ( (vecMC[i].first - smc.mean11) * (vecMC[i].first - smc.mean11) );
  sum_3 = sum_3 + ( (vecMC[i].second - smc.mean21) * (vecMC[i].second - smc.mean21) );
  sum_2 = sum_2 + ( (vecMC[i].first - smc.mean11) * (vecMC[i].second - smc.mean21) );
 }
 smc.cov11 = sum_1 / (vecMC.size()-1);
 smc.cov22 = sum_3 / (vecMC.size()-1);
 smc.cov21 = sum_2 / (vecMC.size()-1);
 smc.cov12 = sum_2 / (vecMC.size()-1);

 //cov 11
 //cov 12
 //cov 22
 //cov 21 is same with cov 12
 printf("mean11 = %lf \n", smc.mean11 );
 printf("mean21 = %lf \n", smc.mean21 );
 printf("cov11 = %lf \n", smc.cov11 );
 printf("cov12 = %lf \n", smc.cov12 );
 printf("cov21 = %lf \n", smc.cov21 );
 printf("cov22 = %lf \n", smc.cov22 );

 return smc;
}





This source code is example for using the function Get_M_C
vector< pair < float, float > > m;
mean_cov SampleMC;

for(int h=0; h< img1->height; ++h)
{
     for(int w=0; w< img1->width; ++w)
    {
        unsigned char R,G,B;
        B = (unsigned char)img1->imageData[h*img1->widthStep+w*3+0];
        G = (unsigned char)img1->imageData[h*img1->widthStep+w*3+1];
        R = (unsigned char)img1->imageData[h*img1->widthStep+w*3+2];
        float Cb,Cr;
        GetCbCrFromRGB(R, G, B, &Cb, &Cr);

        m.push_back( make_pair(Cb, Cr) );
    }
}


SampleMC = Get_M_C( m );




No comments:

Post a Comment