コード例 #1
0
/*!
    \fn CvBinGabAdaFeatureSelect::init_weights()
 */
void CvBinGabAdaFeatureSelect::init_weights()
{
  weights = cvCreateMat(nsamples, 1, CV_32FC1);
  double posweight, negweight;
  posweight = 1.0/npositive/2.0;
  negweight = 1.0/nnegative/2.0;
  if( possub > 0 )  // face recogntion
  {
    for(int i = 0; i < nsamples; i++)
    {
      int id = (int)cvGetReal1D(classIdx, i);
      if(id == possub) cvSetReal1D(weights, i, posweight);
      else cvSetReal1D(weights, i, negweight);
    }
  }
  else   //gender detection
  {
    for(int i = 0; i < nsamples; i++)
    {
      int id = (int)cvGetReal1D(classIdx, i);
      bool sex = ((CvXm2vts*)database)->getGender( id );
      if(sex) cvSetReal1D(weights, i, posweight);
      else cvSetReal1D(weights, i, negweight);
    }
  }
}
コード例 #2
0
void mitk::UndistortCameraImage::SetUndistortImageFastInfo(float in_dF1, float in_dF2,
                                                 float in_dPrincipalX, float in_dPrincipalY,
                                                 float in_Dist[4], float ImageSizeX, float ImageSizeY)
{
  //create new matrix
  m_DistortionCoeffs  = cvCreateMat(4, 1, CV_64FC1);
  m_CameraMatrix      = cvCreateMat(3, 3, CV_64FC1);


  //set the camera matrix [fx 0 cx; 0 fy cy; 0 0 1].
  cvSetReal2D(m_CameraMatrix, 0, 0, in_dF1);
  cvSetReal2D(m_CameraMatrix, 0, 1, 0.0);
  cvSetReal2D(m_CameraMatrix, 0, 2, in_dPrincipalX);

  cvSetReal2D(m_CameraMatrix, 1, 0, 0.0);
  cvSetReal2D(m_CameraMatrix, 1, 1, in_dF2);
  cvSetReal2D(m_CameraMatrix, 1, 2, in_dPrincipalY);

  cvSetReal2D(m_CameraMatrix, 2, 0, 0.0);
  cvSetReal2D(m_CameraMatrix, 2, 1, 0.0);
  cvSetReal2D(m_CameraMatrix, 2, 2, 1.0);

  //set distortions coefficients
  cvSetReal1D(m_DistortionCoeffs, 0, in_Dist[0]);
  cvSetReal1D(m_DistortionCoeffs, 1, in_Dist[1]);
  cvSetReal1D(m_DistortionCoeffs, 2, in_Dist[2]);
  cvSetReal1D(m_DistortionCoeffs, 3, in_Dist[3]);

  m_mapX = cvCreateMat(ImageSizeY, ImageSizeX, CV_32FC1);
  m_mapY = cvCreateMat(ImageSizeY, ImageSizeX, CV_32FC1);

  //cv::initUndistortRectifyMap(m_CameraMatrix, m_DistortionCoeffs, m_mapX, m_mapY);
  cvInitUndistortMap(m_CameraMatrix, m_DistortionCoeffs, m_mapX, m_mapY);
}
コード例 #3
0
/*!
    \fn CvGaborFeature::_XM2VTSBin(const char *pathname, int possub, const CvMat *index) const
 */
CvTrainingData* CvGaborFeature::_XM2VTSBin(const char *pathname, int possub, const CvMat *index) const
{
    int nopic = 4;
    int nosub = 200; 
    CvSize size = cvGetSize(index);
    int numpos = size.width;
    int numneg = (nosub-1)*4;
    int numsample = numneg + numpos;
    CvTrainingData *bindata = new CvTrainingData; 
    bindata->init(2, numsample, 1);
    CvMat *mat = cvCreateMat(numsample, 1, CV_32FC1);
    double v;
    int n = 0;
    int begin = (possub -1)*4;
    int end = (possub -1)*4+numpos;

    while(n < numsample)
    {
      int i, j;
      if ( n < begin )
      {
	i = (int)(n/4) + 1;
        j = (int)fmod((double)n,(double)4) + 1;
        v = XM2VTSdata(pathname, i, j);
        cvSetReal1D(mat, n, v);
	bindata->setclsidxofsample(2, n);
      }
      else if ((n >= begin) && ( n < end))   //postive samples
      {
	i = possub;
        j = n - begin + 1;
	v = XM2VTSdata(pathname, i, (int)cvGetReal1D(index,(j-1)));
	cvSetReal1D(mat, n, v);
	bindata->setclsidxofsample(1, n);

      }
      else  //negative
      {
	i = (int)((n - end)/4) + possub + 1;
        j = (int)fmod((double)(n-end),(double)4)+1;
	v = XM2VTSdata(pathname, i, j);
        cvSetReal1D(mat, n, v);
	bindata->setclsidxofsample(2, n);

      }
      n++;
    }
    bindata->setdata(mat);
    cvReleaseMat(&mat);
    bindata->statclsdist();
    return bindata;


}
コード例 #4
0
/*!
    \fn CvGaborFeature::_XM2VTSBin_F(const char *pathname, int possub) const
 */
CvTrainingData* CvGaborFeature::_XM2VTSBin_F(const char *pathname, int possub) const
{
  CvMat *index = cvCreateMat(1, 4, CV_32FC1);
  cvSetReal1D(index,0,1);
  cvSetReal1D(index,1,2);
  cvSetReal1D(index,2,3);
  cvSetReal1D(index,3,4);
  
  CvTrainingData *bindata = _XM2VTSBin_F(pathname, possub, index);
  cvReleaseMat(&index);
  return bindata;
}
コード例 #5
0
/*!
\fn CvGaborFeature::_XM2VTSMulti(const char *pathname, const CvMat* picIndex, const CvMat* subIndex) const
 */
CvTrainingData* CvGaborFeature::_XM2VTSMulti(const char *pathname, const CvMat* picIndex, const CvMat* subIndex) const
{
  CvSize size = cvGetSize(picIndex);
  int npic = size.width;
  size = cvGetSize(subIndex);
  int nosub = size.width;
  int nsample = nosub*npic;
  int n = 0;
  CvTrainingData *data = new CvTrainingData;
  data->init(nosub, nsample, 1);
  CvMat *mat = cvCreateMat(nsample, 1, CV_32FC1);
  double v;

  for (int i = 1; i <= nosub; i++)
  {
    for (int j = 1; j <= npic; j++)
    {
      v = XM2VTSdata( pathname, (int)cvGetReal1D(subIndex, (i-1)), (int)cvGetReal1D(picIndex, (j-1)) );
      cvSetReal1D(mat, n, v);
      data->setclsidxofsample(i, n);
      n++;
    }
  }
  data->setdata(mat);
  cvReleaseMat(&mat);
  data->statclsdist();
  return data; 
}
コード例 #6
0
/*!
    \fn CvGaborFeature::_FERETBin(const CvFeret* feret, const CvPoolParams* param) const
 */
CvTrainingData* CvGaborFeature::_FERETBin(const CvFeret* feret, const CvPoolParams* param) const
{
  int numsample = feret->getNum();
  CvTrainingData *bindata = new CvTrainingData; 
  bindata->init(2, numsample, 1);
  CvMat *mat = cvCreateMat(numsample, 1, CV_32FC1);
  double v;
  int n = 0;
  string mainpath = feret->getMainpath();
  for (int i = 0; i < feret->getSub(); i++)
  {
    CvSubject sub = feret->getSubject(i);
    for (int j = 0; j < sub.getnum(); j++)
    {
      
      string imgname = sub.getname(j);;
      int id = sub.getId();
      if( param->isReduced() ) v = FERETdata( mainpath.c_str(), id, imgname.c_str(), param->isReduced() );
      else v = FERETdata( mainpath.c_str(), id, imgname.c_str());
      cvSetReal1D( mat, n, v );
      
      bindata->setclsidxofsample( 1, n );
      std::cout << " Go : " << n<< "\r" << std::flush;
      n++;
    }
  }
  cout << endl;
  bindata->setdata(mat);
  cvReleaseMat(&mat);
  bindata->statclsdist();
  return bindata;
}
コード例 #7
0
/*!
    \fn CvGaborFeature::_XM2VTSBin(const char *pathname, int possub) const
 */
CvTrainingData* CvGaborFeature::_XM2VTSBin(const char *pathname, int possub) const
{
    int nopic = 4;
    int nosub = 200;
    int numsample = nopic*nosub;
    CvTrainingData *bindata = new CvTrainingData; 
    bindata->init(2, numsample, 1);
    CvMat *mat = cvCreateMat(numsample, 1, CV_32FC1);
    double v;
    int n = 0;
    for (int i = 1; i <= nosub; i++)
    {
      for (int j = 1; j <= nopic; j++)
      {
        
        v = XM2VTSdata(pathname, i, j);
        cvSetReal1D(mat, n, v);
        if (i == possub) bindata->setclsidxofsample(1, n);
        else bindata->setclsidxofsample(2, n);
        std::cout << " Go : " << n<< "\r" << std::flush;
        n++;
      }
    }
    cout << endl;
    bindata->setdata(mat);
    cvReleaseMat(&mat);
    bindata->statclsdist();
    return bindata;
}
コード例 #8
0
/*!
\fn CvGaborFeature::_XM2VTSBin(const char *pathname) const
 */
CvTrainingData* CvGaborFeature::_XM2VTSBin(const char *pathname) const
{
  int nopic = 8;
  int nosub = 200;
  int numsample = nopic*nosub;
  CvTrainingData *bindata = new CvTrainingData; 
  bindata->init(2, numsample, 1);
  CvMat *mat = cvCreateMat(numsample, 1, CV_32FC1);
  double v;
  int n = 0;
  for (int i = 1; i <= nosub; i++)
  {
    for (int j = 1; j <= nopic; j++)
    {
      
      v = XM2VTSdata(pathname, i, j);
      cvSetReal1D(mat, n, v);

      bindata->setclsidxofsample(1, n);
      n++;
    }
  }
  bindata->setdata(mat);
  cvReleaseMat(&mat);
  bindata->statclsdist();
  return bindata;
}
コード例 #9
0
/*!
    \fn CvGaborFeature::_XM2VTSGender_F(const CvXm2vts* xm2vts, int ntpic) const
 */
CvTrainingData* CvGaborFeature::_XM2VTSGender_F(const CvXm2vts* xm2vts, int ntpic) const
{
  int nosub = 200;
  int nopic = 8;
  
  /*    Generate filename   */
  char *filename = new char[100];
  char *ch_scale = new char[5];
  char *ch_orient = new char[5];
  char *ch_name = new char[10];
  strcpy( filename, xm2vts->getPath() );
  sprintf( ch_scale, "%d", iNu );
  strcat(filename, ch_scale);
  strcat(filename, "/");
  
  sprintf( ch_orient, "%d", iMu );
  strcat( filename, ch_orient );
  strcat(filename, "/");
  sprintf(ch_name, "%d_%d.xml", ix, iy);
  strcat(filename, ch_name);
  delete [] ch_scale;
  delete [] ch_orient;
  delete [] ch_name;
  /*  Generate filename   */
  
  /* Get data from the file */
  CvMat* mat = (CvMat*)cvLoad( filename, NULL, NULL, NULL );
  
  int numsample = nosub*ntpic;
  CvTrainingData *bindata = new CvTrainingData;
  CvMat* tmpmat = cvCreateMat(numsample, 1, CV_32FC1);
  bindata->init(2, numsample, 1);
  
  int n = 0;
  double v;
  for(int sub = 0; sub < nosub; sub++)
  {
    int ind;
    bool gender = xm2vts->getGender( sub+1 );
    if (gender) ind = 1;
    else ind = 2;
    for(int i = 0; i < ntpic; i++)
    {
      v = cvGetReal1D( mat, sub*nopic + i);
      cvSetReal1D( tmpmat, sub*ntpic+i, v);
      bindata->setclsidxofsample( ind, sub*ntpic+i);
    }
  }
  
  
  bindata->setdata(tmpmat);
  
  cvReleaseMat(&tmpmat);
  cvReleaseMat(&mat);
  delete [] filename;
  bindata->statclsdist();
  return bindata;
}
コード例 #10
0
/*!
    \fn CvBinGabAdaFeatureSelect::setDB(CvFaceDB* db)
 */
void CvBinGabAdaFeatureSelect::setDB(CvFaceDB* db)
{
  database = db->clone();
  char * dbname = database->getName();
  if( !strcmp(dbname, "XM2VTS")) this->db_type = XM2VTS;
  else if ( !strcmp(dbname, "FERET")) this->db_type = FERET;
  printf("...............a %s database copied!\n\n", dbname);
  
  if(db_type == XM2VTS)
  {
    nClass = ((CvXm2vts*)database)->get_num_sub();
    nperClass = ((CvXm2vts*)database)->get_num_pic();
    nsamples = nClass*nperClass;
    classIdx = cvCreateMat(nsamples, 1, CV_32SC1);
    int n = 0;
    for(int i = 0; i < nClass; i++)
    {
      for(int j = 0; j < nperClass; j++)
      {
        cvSetReal1D(classIdx, n, i+1);
        n++;
      }
    }
  }
  else if(db_type == FERET)
  {
    nClass = ((CvFeret*)database)->getSub();
    nsamples = ((CvFeret*)database)->getNum();
    classIdx = cvCreateMat(nsamples, 1, CV_32SC1);
    int n = 0;
    for(int i = 0; i < nClass; i++)
    {
      CvSubject subject = ((CvFeret*)database)->getSubject(i);
      int num = subject.getnum();
      int id = subject.getId();
      for(int j = 0; j < num; j++)
      {
        cvSetReal1D(classIdx, n, id);
        n++;
      }
    }
  }
}
コード例 #11
0
ファイル: MixGaussian.cpp プロジェクト: hiromu/HandyARNanoha
void MixGaussian::MakeLookUpTable()
{
	CvMat * SampleMat = cvCreateMat(3, 1, CV_64FC1);

	for(int R = 0; R < 256 ; R++) {
		printf(".");
		for(int G = 0; G < 256 ; G++) {
			for(int B = 0; B < 256 ; B++) {
				cvSetReal1D(SampleMat, 0, (double)R);
				cvSetReal1D(SampleMat, 1, (double)G);
				cvSetReal1D(SampleMat, 2, (double)B);

				_Probability[R][G][B] = GetProbability(SampleMat);
			}
		}
	}

	cvReleaseMat(&SampleMat);
}
コード例 #12
0
ファイル: MixGaussian.cpp プロジェクト: hiromu/HandyARNanoha
bool MixGaussian::LoadFile(char *filename)
{
	FILE *fp = fopen(filename, "rt");
	if(!fp) return false;

	int nMixture = 0;
	fscanf(fp, "%d", &nMixture);

	int nDim = 0;
	fscanf(fp, "%d", &nDim);
	_nDim = nDim;

	CvMat *MeanMat = cvCreateMat(nDim, 1, CV_64FC1);
	CvMat *CovMat = cvCreateMat(nDim, nDim, CV_64FC1);
	cvSetZero(CovMat);
	float Weight = 0;

	for(int i = 0; i < nMixture ; i++) {
		float value;
		// Set Mean
		for(int j = 0; j < nDim ; j++) {
			fscanf(fp, "%f", &value);
			cvSetReal1D(MeanMat, j, value);
		}
		// Set diagonal Covariance
		for(int j = 0; j < nDim ; j++) {
			fscanf(fp, "%f", &value);
			cvSetReal2D(CovMat, j, j, value);
		}
		// Set Weight
		fscanf(fp, "%f", &value);
		Weight = value;

		// add a gaussian
		AddGaussian(MeanMat, CovMat, Weight);
	}
	cvReleaseMat(&MeanMat);
	cvReleaseMat(&CovMat);

	fclose(fp);
	return true;
}
コード例 #13
0
/*!
    \fn CvBinGabAdaFeatureSelect::svmpredict(IplImage *img, CvSVM *svm, int nfeatures)
 */
float CvBinGabAdaFeatureSelect::svmpredict(IplImage *img, CvSVM *svm, int nfeatures)
{
  if( nfeatures > new_pool->getSize())
  {
    perror("Number of features exceeds the maximal!\n");
    exit(-1);
  }
  
  CvMat *test_sample = cvCreateMat(1, nfeatures, CV_32FC1);
  double vfeature;
  for (int i = 0; i < nfeatures; i++)
  {
      /* load feature value */
    CvGaborFeature *feature;
    feature = new_pool->getfeature( i );
    vfeature = feature->val( img );
    cvSetReal1D( test_sample, i, vfeature );
  }
  
  float result = svm->predict( test_sample );
  //printf("The class number is %f\n", result);
  
  return result;
}
コード例 #14
0
ファイル: random_trees.cpp プロジェクト: EduFill/hbrs-ros-pkg
int RandomTrees::train(const char* samples_filename, const char* model_filename, const double ratio, double &train_error, double &test_error)
{
	CvMat* data = 0;
	CvMat* responses = 0;
	CvMat* var_type = 0;
	CvMat* sample_idx = 0;

	this->tree_parameters_.nactive_vars = (int)sqrt(this->number_of_features_);

	int ok = read_num_class_data( samples_filename, this->number_of_features_, &data, &responses );
	int nsamples_all = 0, ntrain_samples = 0;
	int i = 0;
	double train_hr = 0, test_hr = 0;
	CvRTrees forest;
	CvMat* var_importance = 0;

	if( !ok )
	{
		cout << "Could not read the sample in" << samples_filename << endl;;
		return -1;
	}

	cout << "The sample file " << samples_filename << " is loaded." << endl;
	nsamples_all = data->rows;
	ntrain_samples = (int)(nsamples_all * ratio);


	// create classifier by using <data> and <responses>
	cout << "Training the classifier ..." << endl;

	// 1. create type mask
	var_type = cvCreateMat( data->cols + 1, 1, CV_8U );
	cvSet( var_type, cvScalarAll(CV_VAR_ORDERED) );
	cvSetReal1D( var_type, data->cols, CV_VAR_CATEGORICAL );

	// 2. create sample_idx
	sample_idx = cvCreateMat( 1, nsamples_all, CV_8UC1 );
	{
		CvMat mat;
		cvGetCols( sample_idx, &mat, 0, ntrain_samples );
		cvSet( &mat, cvRealScalar(1) );

		cvGetCols( sample_idx, &mat, ntrain_samples, nsamples_all );
		cvSetZero( &mat );
	}

	// 3. train classifier
	forest.train( data, CV_ROW_SAMPLE, responses, 0, sample_idx, var_type, 0, this->tree_parameters_);
	cout << endl;


	// compute prediction error on train and test data
	for( i = 0; i < nsamples_all; i++ )
	{
		double r;
		CvMat sample;
		cvGetRow( data, &sample, i );

		r = forest.predict( &sample );
		r = fabs((double)r - responses->data.fl[i]) <= FLT_EPSILON ? 1 : 0;

		if( i < ntrain_samples )
			train_hr += r;
		else
			test_hr += r;
	}

	test_hr /= (double)(nsamples_all-ntrain_samples);
	train_hr /= (double)ntrain_samples;

	train_error = 1 - train_hr;
	test_error = 1 - test_hr;

	cout << "Recognition rate: train = " << train_hr*100 << ", test = " << test_hr*100 << endl;
	cout << "Number of trees: " << forest.get_tree_count() << endl;

	// Print variable importance
	var_importance = (CvMat*)forest.get_var_importance();
	if( var_importance )
	{
		double rt_imp_sum = cvSum( var_importance ).val[0];
		printf("var#\timportance (in %%):\n");
		for( i = 0; i < var_importance->cols; i++ )
			printf( "%-2d\t%-4.1f\n", i,100.f*var_importance->data.fl[i]/rt_imp_sum);
	}

	// Save Random Trees classifier to file if needed
	if( model_filename )
		forest.save( model_filename );

	//cvReleaseMat( &var_importance );		//causes a segmentation fault
	cvReleaseMat( &sample_idx );
	cvReleaseMat( &var_type );
	cvReleaseMat( &data );
	cvReleaseMat( &responses );

	return 0;
}
コード例 #15
0
ファイル: core_c.cpp プロジェクト: neutmute/emgucv
void cveSetReal1D(CvArr* arr, int idx0, double value)
{
   cvSetReal1D(arr, idx0, value);
}
コード例 #16
0
/*!
\fn CvGaborFeature::_XM2VTSBin_F(const char *pathname, int possub, const CvMat *index) const
 */
CvTrainingData* CvGaborFeature::_XM2VTSBin_F(const char *pathname, int possub, const CvMat *index) const
{
  int nosub = 200;
  int nopic = 8;
  int ntpic = 4;
  /*    Generate filename   */
  char *filename = new char[100];
  char *ch_scale = new char[5];
  char *ch_orient = new char[5];
  char *ch_name = new char[10];
  strcpy( filename, pathname );
  sprintf( ch_scale, "%d", iNu );
  strcat(filename, ch_scale);
  strcat(filename, "/");
  
  sprintf( ch_orient, "%d", iMu );
  strcat( filename, ch_orient );
  strcat(filename, "/");
  sprintf(ch_name, "%d_%d.xml", ix, iy);
  strcat(filename, ch_name);
  delete [] ch_scale;
  delete [] ch_orient;
  delete [] ch_name;
  /*  Generate filename   */
  
  CvMat* mat = (CvMat*)cvLoad( filename, NULL, NULL, NULL );
   
  CvSize size = cvGetSize( index );
  CvSize size1 = cvGetSize( mat );
  int num = size1.height;
  int num_example = size.height;
  int numneg = ( nosub - 1 )*4;
  int numpos = num_example - numneg;


  int numsample = numneg + numpos;
  CvTrainingData *bindata = new CvTrainingData;
  CvMat* tmpmat = cvCreateMat(numsample, 1, CV_32FC1);
  bindata->init(2, numsample, 1);
  
  int n = 0;
  double v;
  for(int sub = 0; sub < nosub; sub++)
  {
    if(sub == (possub-1))
    {
      for(int i = 0; i < numpos; i++)
      {
        double ind = cvGetReal1D(index, i);
        v = cvGetReal1D(mat, sub*nopic+(int)(ind-1));
        cvSetReal1D(tmpmat, sub*ntpic+i, v);
        bindata->setclsidxofsample( 1, sub*ntpic+i );
        n++;
      }
    }
    else if (sub < (possub -1))
    {
      for(int pic = 0; pic < nopic; pic++) 
      {
        if(pic < 4) 
        {
          v = cvGetReal1D(mat, sub*nopic+pic);
          cvSetReal1D(tmpmat, sub*ntpic+pic, v);
          bindata->setclsidxofsample( 2, sub*ntpic+pic );
        }
        n++;
      }
    }
    else if (sub > (possub -1))
    {
      for(int pic = 0; pic < nopic; pic++) 
      {
        if(pic < 4) 
        {
          v = cvGetReal1D(mat, sub*nopic+pic);
          cvSetReal1D(tmpmat, (sub-1)*ntpic+numpos+pic, v);
          bindata->setclsidxofsample( 2, (sub-1)*ntpic+numpos+pic );
        }
        n++;
      }
    }
  }
  bindata->setdata(tmpmat);
  
  cvReleaseMat(&tmpmat);
  cvReleaseMat(&mat);
  delete [] filename;
  bindata->statclsdist();
  return bindata;
}
コード例 #17
0
void CTWithWater::imageAndDepthToWorld(double u, double v, double d,
                                       double* x, double* y, double* z,
                                       bool undistort)
{
    double xx, yy, t;
    CvMat* r = cvCreateMat(3, 1, CV_32FC1);

    if(undistort)
    {
        CvMat* I = cvCreateMat(1, 1, CV_32FC2);
        CvMat* Io = cvCreateMat(1, 1, CV_32FC2);
        cvSet2D(I, 0, 0, cvScalar(u,v));
        
        cvUndistortPoints(I, Io, m_CameraMatrix, m_DistCoeffs, NULL, m_CameraMatrixNorm);
        CvScalar s = cvGet2D(Io, 0, 0);
        
        xx = s.val[0];//cvGetReal1D(Io, 0);
        yy = s.val[1];//cvGetReal1D(Io, 1);
        
        cvReleaseMat(&I);
        cvReleaseMat(&Io);            
    }
    else
    {
        xx = u;
        yy = v;
    }

    xx = (xx - cvGetReal2D(m_CameraMatrixNorm, 0, 2))/cvGetReal2D(m_CameraMatrixNorm, 0, 0);
    yy = (yy - cvGetReal2D(m_CameraMatrixNorm, 1, 2))/cvGetReal2D(m_CameraMatrixNorm, 1, 1);

    cvSetReal1D(r, 0, xx); 
    cvSetReal1D(r, 1, yy);
    cvSetReal1D(r, 2, 1.0);

    /* Rt_(3,:)*r = sum of third column of R times elements of r */
    t = xx*cvGetReal2D(m_R, 0, 2) + yy*cvGetReal2D(m_R, 1, 2) + cvGetReal2D(m_R, 2, 2);
    if(t == 0)
    {
        t = 1.0;
    }

    if(d <= 0)
    {
        /* d<= 0 => above water surface */
        t = (-m_dCameraHeightAboveWater-d)/t;

        /* r = t*R'*r + C */
        cvGEMM(m_R, r, t, m_CameraWorld, 1.0, r, CV_GEMM_A_T);
    }
    else
    {
        /* d > 0 => below water surface */

        t = -m_dCameraHeightAboveWater/t;
        
        /* S = t*R'*r */
        cvGEMM(m_R, r, t, NULL, 0, m_S, CV_GEMM_A_T);

        double Sx = cvGetReal1D(m_S, 0);
        double Sy = cvGetReal1D(m_S, 1);    
        double phi = atan2(Sy, Sx);
        double rS = sqrt(Sx*Sx + Sy*Sy);

        double rP = calculateRpFromRs(rS, d, m_dCameraHeightAboveWater);
        cvSetReal1D(r, 0, rP*cos(phi));
        cvSetReal1D(r, 1, rP*sin(phi));
        cvSetReal1D(r, 2, -m_dCameraHeightAboveWater-d);

        cvAdd(r, m_CameraWorld, r);
    }

    *x = cvGetReal1D(r, 0);
    *y = cvGetReal1D(r, 1);
    *z = cvGetReal1D(r, 2);    
                           
    cvReleaseMat(&r);

}
コード例 #18
0
ファイル: hand_final.c プロジェクト: sumitsrv/vk
void tips(IplImage *img)
{
	FILE *tipgraph = fopen("tipgraph.dat","w");
	//FILE *freq = fopen("freq.dat", "w");

	int i, j, curr_pixel, step, x[640];
	tipcount=0;
	uchar *data = (uchar*)img->imageData;
	step = img->widthStep;
	CvMat *dst = cvCreateMat(1, 640, CV_32FC1 );
    CvMat *src = cvCreateMat(1, 640, CV_32FC1 );
	
	for(i=0; i<width; i++)
	{
		x[i] = 0;
		for(j=0; j<height; j++)
		{
			curr_pixel = data[j*step + i];
			if((curr_pixel == 255) )
			{
				//data[x[i]*step + i] = 0;
				x[i] = j;
			}
			//else data[j*step + i] = 0;
		}
		cvSetReal1D(src, i, x[i]);
		fprintf(tipgraph, "%d\n", x[i]);
			//printf("hi");
	}
	
    cvDFT(src, dst, CV_DXT_SCALE, 0);
    for(i=0; i<width; i++)
    {
		//fprintf(freq, "%f\n", abs(cvGetReal1D(dst, i)));
		if(i>20) cvSetReal1D(dst, i, 0);
	}
    cvDFT(dst, src, CV_DXT_INVERSE, 0);
    for(i=1; i<width-1; i++)
    {
		if((cvGetReal1D(src, i+1) - cvGetReal1D(src, i) <= 0 && cvGetReal1D(src, i) - cvGetReal1D(src, i-1) >= 0) 
		//|| (cvGetReal1D(src, i+1) - cvGetReal1D(src, i) <= 0 && cvGetReal1D(src, i+1) - cvGetReal1D(src, i) >=-5 && cvGetReal1D(src, i) - cvGetReal1D(src, i-1) <= 0 && cvGetReal1D(src, i) - cvGetReal1D(src, i-1) >= -5)
		)
		{
			tips_position[tipcount][0] = 0;
			for(j=-3; j<=3; j++)
			{
				if((i+j)<640 && (i+j)>0)
				{
					tips_position[tipcount][0] +=  x[i+j];
				}
			}
			tips_position[tipcount][0] = (tips_position[tipcount][0])/7;
				
			if(tips_position[tipcount][0] > 40)
			{
				if((tipcount > 1) && (i-tips_position[tipcount-1][1]) < 55)
				{
					tips_position[tipcount-1][0] = (tips_position[tipcount-1][0] + tips_position[tipcount][0]) / 2;
					tips_position[tipcount-1][1] = (tips_position[tipcount-1][1] + i) / 2;
				}
				else
				{
					tips_position[tipcount++][1] = i;
				}
			}
		}
		
		fprintf(tipgraph, "%f\n", cvGetReal1D(src, i));
	}
    //printf("%d\t",tipcount);
	fclose(tipgraph);
	correlated_tips();
	//fclose(freq);		
}
コード例 #19
0
/*!
    \fn CvBinGabAdaFeatureSelect::svmlearning(const char* path, int nofeatures, CvSVM * svm)
 */
void CvBinGabAdaFeatureSelect::svmlearning(const char* path, int nofeatures, CvSVM * svm)
{
  if( db_type == XM2VTS )
  {
    printf("Training an SVM classifier  ................\n");
    CvXm2vts *xm2vts = (CvXm2vts*)database;
    int nTrainingExample = 200*4;
    CvMat* trainData = cvCreateMat(nTrainingExample, nofeatures, CV_32FC1);
    CvMat* response = cvCreateMat(nTrainingExample, 1, CV_32FC1);
    
    for (int i = 0; i < nofeatures; i++)
    {
      /* load feature value */
      CvGaborFeature *feature;
      feature = new_pool->getfeature(i);
      printf("Getting the %d feature ............\n", i+1);
      
      char *filename = new char[50];
      //training validation
      double l, t;
      int fal = 0;
      for(int sub = 1; sub <= 200; sub++)
      {
        if (((CvXm2vts*)database)->getGender( sub )) t = 1.0;
        else t = 2.0;
        
        for(int pic = 1; pic <= 4; pic++)
        {
          sprintf(filename, "%s/%d_%d.bmp", path, sub, pic);
          IplImage *img = cvLoadImage( filename, CV_LOAD_IMAGE_ANYCOLOR );
          IplImage *grayimg = cvCreateImage(cvGetSize(img), IPL_DEPTH_8U, 1);
          if ( img->nChannels == 1 )  cvCopy( img, grayimg, NULL );
          else if (img->nChannels == 3)   cvCvtColor( img, grayimg, CV_RGB2GRAY );
          
          double vfeature = feature->val( img );
          cvSetReal2D( trainData, ((sub-1)*4+(pic-1)), i, vfeature );
          cvSetReal1D( response, ((sub-1)*4+(pic-1)), t );
          cvReleaseImage(&img);
          cvReleaseImage(&grayimg);
        }
      }
      delete [] filename;
    }
    
    
    printf("building the svm classifier .........................\n");
    CvTermCriteria term_crit = cvTermCriteria( CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 200, 0.8);
  /*Type of SVM, one of the following types:
    CvSVM::C_SVC - n-class classification (n>=2), allows imperfect separation of classes with penalty multiplier C for outliers.
    CvSVM::NU_SVC - n-class classification with possible imperfect separation. Parameter nu (in the range 0..1, the larger the value, the smoother the decision boundary) is used instead of C.
    CvSVM::ONE_CLASS - one-class SVM. All the training data are from the same class, SVM builds a boundary that separates the class from the rest of the feature space.
    CvSVM::EPS_SVR - regression. The distance between feature vectors from the training set and the fitting hyperplane must be less than p. For outliers the penalty multiplier C is used.
    CvSVM::NU_SVR - regression; nu is used instead of p. */
    int _svm_type = CvSVM::NU_SVC;
  /*The kernel type, one of the following types:
    CvSVM::LINEAR - no mapping is done, linear discrimination (or regression) is done in the original feature space. It is the fastest option. d(x,y) = x•y == (x,y)
    CvSVM::POLY - polynomial kernel: d(x,y) = (gamma*(x•y)+coef0)degree
    CvSVM::RBF - radial-basis-function kernel; a good choice in most cases: d(x,y) = exp(-gamma*|x-y|2)
    CvSVM::SIGMOID - sigmoid function is used as a kernel: d(x,y) = tanh(gamma*(x•y)+coef0) */
    
    int _kernel_type = CvSVM::POLY;
    
    double _degree = 3.0;
    double _gamma = 1.0;
    double _coef0 = 0.0;
    double _C = 1.0;
    double _nu = 1.0;
    double _p = 1.0;
    
    CvSVMParams  params( CvSVM::C_SVC, CvSVM::POLY, _degree, _gamma, _coef0, _C, _nu, _p,
                         0, term_crit );
    
    svm->train( trainData, response, 0, 0, params );
    
    svm->save( "svm.xml", "svm" );
    cvReleaseMat(&response);
    cvReleaseMat(&trainData);
  }
}
コード例 #20
0
void OpencvRFclassifier::learn(std::vector< std::vector<float> >& pfeatures, std::vector<int>& plabels){

     if (_rf){
	delete _rf;
	_trees.clear();	
	_tree_weights.clear();
     }
     _rf = new CvRTrees;
 	

     int rows = pfeatures.size();
     int cols = pfeatures[0].size();	 	
     
     printf("Number of samples and dimensions: %d, %d\n",rows, cols);
     if ((rows<1)||(cols<1)){
	return;
     }

//      clock_t start = clock();    
     std::time_t start, end;
     std::time(&start);	


     CvMat *features = cvCreateMat(rows, cols, CV_32F);	
     CvMat *labels = cvCreateMat(rows, 1 , CV_32F);	
     float* datap = features->data.fl;
     float* labelp = labels->data.fl;	 	


     int numzeros=0; 	
     for(int i=0; i < rows; i++){
	 labelp[i] = plabels[i];
	 numzeros += ( labelp[i] == -1? 1 : 0 );
	 for(int j=0; j < cols ; j++){
	     datap[i*cols+j]  = (float)pfeatures[i][j];	
	 }
     }
     printf("Number of merge: %d\n",numzeros);



     // 1. create type mask
     CvMat* var_type = cvCreateMat( features->cols + 1, 1, CV_8U );
     cvSet( var_type, cvScalarAll(CV_VAR_NUMERICAL) );
     cvSetReal1D( var_type, features->cols, CV_VAR_CATEGORICAL );

     // define the parameters for training the random forest (trees)

     float priors[] = {1,1};  // weights of each classification for classes
     // (all equal as equal samples of each digit)

     CvRTParams params = CvRTParams( _max_depth, // max depth :the depth of the tree
                                     10, // min sample count:  minimum samples required at a leaf node for it to be split
                                     0, // regression accuracy: N/A here
                                     false, // compute surrogate split, no missing data
                                     15, // max number of categories (use sub-optimal algorithm for larger numbers)
                                     priors, // the array of prior for each class
                                     false,  // calculate variable importance
                                     5,       // number of variables randomly selected at node and used to find the best split(s).
                                     _tree_count,	 // max number of trees in the forest
                                     0.001f, // forest accuracy
                                     CV_TERMCRIT_ITER //|	CV_TERMCRIT_EPS // termination cirteria
                                      );
	

     // 3. train classifier
     _rf->train( features, CV_ROW_SAMPLE, labels, 0, 0, var_type, 0, params);
         //CvRTParams(10,10,0,false,15,0,true,4,100,0.01f,CV_TERMCRIT_ITER));

     float correct = 0;
     for(int  i = 0; i < features->rows ; i++ ){
         float r;
         CvMat sample;
         cvGetRow( features, &sample, i );
	
         r = _rf->predict_prob( &sample );
	 r = (r>0.5)? 1 :-1;
         r = fabs((float)r - labels->data.fl[i]) <= FLT_EPSILON ? 1 : 0;


	 correct += r;
      }
      	

    std::time(&end);
    printf("Time required to learn RF: %.2f sec\n", (difftime(end,start))*1.0);
//     printf("Time required to learn RF: %.2f sec\n", ((float)clock() - start) / CLOCKS_PER_SEC);
    printf("with training set accuracy :%.3f\n", correct/features->rows*100.);

    _tree_count = _rf->get_tree_count();	
    for(int i = 0; i < _tree_count; i++){
	CvForestTree* treep = _rf->get_tree(i);
	_trees.push_back(treep); 	
    }
    //int ntrees = _rf->get_tree_count();	
    _tree_weights.resize(_tree_count, 1.0/_tree_count); 		

     cvReleaseMat( &features );
     cvReleaseMat( &labels );	
     cvReleaseMat( &var_type );	
}
コード例 #21
0
static
int build_boost_classifier( char* data_filename,
    char* filename_to_save, char* filename_to_load )
{
    const int class_count = 26;
    CvMat* data = 0;
    CvMat* responses = 0;
    CvMat* var_type = 0;
    CvMat* temp_sample = 0;
    CvMat* weak_responses = 0;

    int ok = read_num_class_data( data_filename, 16, &data, &responses );
    int nsamples_all = 0, ntrain_samples = 0;
    int var_count;
    int i, j, k;
    double train_hr = 0, test_hr = 0;
    CvBoost boost;

    if( !ok )
    {
        printf( "Could not read the database %s\n", data_filename );
        return -1;
    }

    printf( "The database %s is loaded.\n", data_filename );
    nsamples_all = data->rows;
    ntrain_samples = (int)(nsamples_all*0.5);
    var_count = data->cols;

    // Create or load Boosted Tree classifier
    if( filename_to_load )
    {
        // load classifier from the specified file
        boost.load( filename_to_load );
        ntrain_samples = 0;
        if( !boost.get_weak_predictors() )
        {
            printf( "Could not read the classifier %s\n", filename_to_load );
            return -1;
        }
        printf( "The classifier %s is loaded.\n", data_filename );
    }
    else
    {
        // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        //
        // As currently boosted tree classifier in MLL can only be trained
        // for 2-class problems, we transform the training database by
        // "unrolling" each training sample as many times as the number of
        // classes (26) that we have.
        //
        // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

        CvMat* new_data = cvCreateMat( ntrain_samples*class_count, var_count + 1, CV_32F );
        CvMat* new_responses = cvCreateMat( ntrain_samples*class_count, 1, CV_32S );

        // 1. unroll the database type mask
        printf( "Unrolling the database...\n");
        for( i = 0; i < ntrain_samples; i++ )
        {
            float* data_row = (float*)(data->data.ptr + data->step*i);
            for( j = 0; j < class_count; j++ )
            {
                float* new_data_row = (float*)(new_data->data.ptr +
                                new_data->step*(i*class_count+j));
                for( k = 0; k < var_count; k++ )
                    new_data_row[k] = data_row[k];
                new_data_row[var_count] = (float)j;
                new_responses->data.i[i*class_count + j] = responses->data.fl[i] == j+'A';
            }
        }

        // 2. create type mask
        var_type = cvCreateMat( var_count + 2, 1, CV_8U );
        cvSet( var_type, cvScalarAll(CV_VAR_ORDERED) );
        // the last indicator variable, as well
        // as the new (binary) response are categorical
        cvSetReal1D( var_type, var_count, CV_VAR_CATEGORICAL );
        cvSetReal1D( var_type, var_count+1, CV_VAR_CATEGORICAL );

        // 3. train classifier
        printf( "Training the classifier (may take a few minutes)...\n");
        boost.train( new_data, CV_ROW_SAMPLE, new_responses, 0, 0, var_type, 0,
            CvBoostParams(CvBoost::REAL, 100, 0.95, 5, false, 0 ));
        cvReleaseMat( &new_data );
        cvReleaseMat( &new_responses );
        printf("\n");
    }

    temp_sample = cvCreateMat( 1, var_count + 1, CV_32F );
    weak_responses = cvCreateMat( 1, boost.get_weak_predictors()->total, CV_32F ); 

    // compute prediction error on train and test data
    for( i = 0; i < nsamples_all; i++ )
    {
        int best_class = 0;
        double max_sum = -DBL_MAX;
        double r;
        CvMat sample;
        cvGetRow( data, &sample, i );
        for( k = 0; k < var_count; k++ )
            temp_sample->data.fl[k] = sample.data.fl[k];

        for( j = 0; j < class_count; j++ )
        {
            temp_sample->data.fl[var_count] = (float)j;
            boost.predict( temp_sample, 0, weak_responses );
            double sum = cvSum( weak_responses ).val[0];
            if( max_sum < sum )
            {
                max_sum = sum;
                best_class = j + 'A';
            }
        }

        r = fabs(best_class - responses->data.fl[i]) < FLT_EPSILON ? 1 : 0;

        if( i < ntrain_samples )
            train_hr += r;
        else
            test_hr += r;
    }

    test_hr /= (double)(nsamples_all-ntrain_samples);
    train_hr /= (double)ntrain_samples;
    printf( "Recognition rate: train = %.1f%%, test = %.1f%%\n",
            train_hr*100., test_hr*100. );

    printf( "Number of trees: %d\n", boost.get_weak_predictors()->total );

    // Save classifier to file if needed
    if( filename_to_save )
        boost.save( filename_to_save );

    cvReleaseMat( &temp_sample );
    cvReleaseMat( &weak_responses );
    cvReleaseMat( &var_type );
    cvReleaseMat( &data );
    cvReleaseMat( &responses );

    return 0;
}
コード例 #22
0
void CTWithWater::worldToImage(double x, double y, double z,
                               double* u, double* v,
                               bool distort)
{
    double d = m_dWaterDepth - z;

    /* d > 0 => point is below surface of water */
    if(d > 0)
    {
        double phi = atan2(y - cvGetReal1D(m_CameraWorld, 1),
                           x - cvGetReal1D(m_CameraWorld, 0));
        double rP = sqrt((x-cvGetReal1D(m_CameraWorld, 0))
                         *(x-cvGetReal1D(m_CameraWorld, 0)) + 
                         (y-cvGetReal1D(m_CameraWorld, 1))
                         *(y-cvGetReal1D(m_CameraWorld, 1)));
        double rS = solveRsFromRp(rP, d, m_dCameraHeightAboveWater);
        cvSetReal1D(m_S, 0, rS*cos(phi));
        cvSetReal1D(m_S, 1, rS*sin(phi));
        cvSetReal1D(m_S, 2, -m_dCameraHeightAboveWater);

        /* S = CW + S */
        cvAdd(m_S, m_CameraWorld, m_S);
    }
    else
    {
        /* point is above water surface and can be used directly */
        cvSetReal1D(m_S, 0, x);
        cvSetReal1D(m_S, 1, y);
        cvSetReal1D(m_S, 2, z);
    }

    /* S = R*S + T */
    cvGEMM(m_R, m_S, 1.0, m_T, 1.0, m_S);

    /* in camera coordinats */
    x = cvGetReal1D(m_S, 0);
    y = cvGetReal1D(m_S, 1);
    z = cvGetReal1D(m_S, 2);

    if(z == 0)
    {
        z = 1.0;
    }

    x = x/z;
    y = y/z;

    if(distort)
    {
        double xx, yy, r2, k1, k2, k3, p1, p2;
        r2 = (x*x + y*y);
        k1 = cvGetReal1D(m_DistCoeffs, 0);
        k2 = cvGetReal1D(m_DistCoeffs, 1);
        p1 = cvGetReal1D(m_DistCoeffs, 2);
        p2 = cvGetReal1D(m_DistCoeffs, 3);
        k3 = cvGetReal1D(m_DistCoeffs, 4);        
        xx = x*(1 + k1*r2 + k2*r2*r2 + k3*r2*r2*r2) +
            2.0*p1*x*y + p2*(r2 + 2.0*x*x);
        yy = y*(1 + k1*r2 + k2*r2*r2 + k3*r2*r2*r2) +
            p1*(r2 + 2.0*y*y) + 2.0*p2*x*y;
        *u = cvGetReal2D(m_CameraMatrix, 0, 0)*x + cvGetReal2D(m_CameraMatrix, 0, 2);
        *v = cvGetReal2D(m_CameraMatrix, 1, 1)*y + cvGetReal2D(m_CameraMatrix, 1, 2);
    }
    else
    {
        *u = cvGetReal2D(m_CameraMatrixNorm, 0, 0)*x
            + cvGetReal2D(m_CameraMatrixNorm, 0, 2);
        *v = cvGetReal2D(m_CameraMatrixNorm, 1, 1)*y
            + cvGetReal2D(m_CameraMatrixNorm, 1, 2);
    }

}
コード例 #23
0
/*!
    \fn CvGaborFeature::_XM2VTSMulti_F(const char *pathname, const CvMat* picIndex, const CvMat* subIndex) const
 */
CvTrainingData* CvGaborFeature::_XM2VTSMulti_F(const char *pathname, const CvMat* picIndex, const CvMat* subIndex) const
{
  int nosub = 200;
  int nopic = 8;
  
  /*    Generate filename   */
  char *filename = new char[100];
  char *ch_scale = new char[5];
  char *ch_orient = new char[5];
  char *ch_name = new char[10];
  strcpy( filename, pathname );
  sprintf( ch_scale, "%d", iNu );
  strcat(filename, ch_scale);
  strcat(filename, "/");
  
  sprintf( ch_orient, "%d", iMu );
  strcat( filename, ch_orient );
  strcat(filename, "/");
  sprintf(ch_name, "%d_%d.xml", ix, iy);
  strcat(filename, ch_name);
  delete [] ch_scale;
  delete [] ch_orient;
  delete [] ch_name;
  /*  Generate filename   */
  
  CvMat* mat = (CvMat*)cvLoad( filename, NULL, NULL, NULL );
  //printf("Open %s \n", filename);
  //assert( mat );
  if(!CV_IS_MAT( mat )) 
  {
    //retry 10 times
    for(int i = 0; i < 10; i++)
    {
      time_t rawtime;
      struct tm * timeinfo;
      time ( &rawtime );
      timeinfo = localtime ( &rawtime );
      perror( asctime (timeinfo) );
      perror("Can not get a matrix from ");
      perror(filename);
      sleep( 10 );   // sleep for 10 sec
      mat = (CvMat*)cvLoad( filename, NULL, NULL, NULL );
      if (CV_IS_MAT( mat )) break;
    }
  }
  CvSize size = cvGetSize( picIndex );
  CvSize size1 = cvGetSize( mat );
  CvSize size2 = cvGetSize(subIndex);
  
  int num = size1.height;
  int ntpic = size.width;
  int ntsub = size2.width;
  int numsample = ntsub*ntpic;
  
  CvTrainingData *bindata = new CvTrainingData;
  CvMat* tmpmat = cvCreateMat(numsample, 1, CV_32FC1);
  bindata->init(ntsub, numsample, 1);
  
  int n = 0;
  int m = 0;
  double v;
  for(int sub = 1; sub <= nosub; sub++)
  {
    for(int pic = 1; pic <= nopic; pic++)
    {
      for(int j = 0; j < ntsub; j++)
      {
        for(int i = 0; i < ntpic; i++)
        {
          if((pic == cvGetReal1D(picIndex, i))&&(sub == cvGetReal1D(subIndex, j))) 
          {
            v = cvGetReal1D(mat, n);
            cvSetReal1D(tmpmat, m, v);
            bindata->setclsidxofsample(sub, m);
            m++;
          }
        }
      }
      n++;
    }
  }
  bindata->setdata(tmpmat);
  
  cvReleaseMat(&tmpmat);
  cvReleaseMat(&mat);
  delete [] filename;
  bindata->statclsdist();
  return bindata;
}
コード例 #24
0
ファイル: main.cpp プロジェクト: huabh/GenderTester
int main(int argc, char **argv) {
IplImage *inputImg;
trainImage sample;  
cvNamedWindow("With COM", CV_WINDOW_AUTOSIZE);
// CvCapture* capture = 0;
// capture = cvCreateCameraCapture(-1);
// if(!capture){
// return -1;
// }
// inputImg = cvQueryFrame(capture);
#include <opencv2/ml/ml.hpp>
float result;
initializeFaceProcessor();
CvMat* SampleMatrix;
CvMat* PjMatrix=(CvMat*)cvLoad("/home/umut/projects/fastTrainer/build/ProjectionMatrix.xml");
int newDimension=PjMatrix->cols;
// int newDimension;
CvMat* allFeatures;
 CvMat* LDAMatrix=cvCreateMat(newDimension,1,CV_32F);
// CvBoost booster;
// 
// booster.load("/home/umut/projects/fastTrainer/build/Booster.dat");
int trans=CV_GEMM_A_T;

CvSVM SVM;
SVM.load("/home/umut/projects/fastTrainer/build/SVM_CLASS.dat");
// Grab the next frame from the camera.
// while((inputImg = cvQueryFrame(capture))  != NULL ){
for (int i=1;i<argc;i++){
    inputImg=cvLoadImage(argv[i]);


  
      if(processFace(inputImg,  sample.FaceImage, sample.MouthImage, sample.NoseImage, sample.EyeImage, 0))  
      {
	 sample.LBPHF=LBP_HF(sample.FaceImage,sample.nonUniform,sample.complete); //Pass through the LBPHF
// 	  sample.EyeImage=filterGabor(sample.EyeImage);
// 	  sample.NoseImage=filterGabor(sample.NoseImage);
// 	  sample.MouthImage=filterGabor(sample.MouthImage);
	  mat2Col(&sample,0,1,0,SampleMatrix);
	//  newDimension=SampleMatrix->rows;
	  allFeatures=cvCreateMat(1,35+2+newDimension,CV_32F);
	  cvGEMM(PjMatrix,SampleMatrix,1,NULL,0,LDAMatrix,trans);
	   cvSetReal1D(allFeatures,0,sample.complete);
	  cvSetReal1D(allFeatures,1,sample.nonUniform);      
	  for (int j=0;j<35;j++)
	    cvSetReal1D(allFeatures,2+j,sample.LBPHF[j]);
	  for (int j=0;j
	    <newDimension;j++)
	//    cvSetReal1D(allFeatures,37+j,cvGetReal1D(SampleMatrix,j));
	  cvSetReal1D(allFeatures,37+j,cvGetReal1D(LDAMatrix,j));
	//  cout<< "feature Size: "<< allFeatures->cols << "\n";
	//  result=booster.predict(allFeatures,0,booster.get_weak_response());
	  result=SVM.predict(allFeatures);
	  if (result==0)
	  {
	    cvRectangle(sample.FaceImage,cvPoint(2,2),cvPoint(sample.FaceImage->width-2,sample.FaceImage->height-2),cvScalar(255,0,0),3);
	    printf("Result is male\n");
	  }
	  else
	  {
	    cvRectangle(sample.FaceImage,cvPoint(2,2),cvPoint(sample.FaceImage->width-2,sample.FaceImage->height-2),cvScalar(0,0,255),3);
	    printf("Result is female\n");
	  }
	
      cvShowImage("With COM",sample.FaceImage);
     char c=cvWaitKey(0);
//      char c=cvWaitKey(5);
//       if (c==27) break;
 }
}
if (strcmp(argv[1],"1"))
cvReleaseImage( &inputImg);
}
コード例 #25
0
/*!
    \fn CvGaborFeature::_XM2VTSMulti_F(const char *pathname, const CvMat* index) const
 */
CvTrainingData* CvGaborFeature::_XM2VTSMulti_F(const char *pathname, const CvMat* index) const
{
  int nosub = 200;
  int nopic = 8;
  
  /*    Generate filename   */
  char *filename = new char[100];
  char *ch_scale = new char[5];
  char *ch_orient = new char[5];
  char *ch_name = new char[10];
  strcpy( filename, pathname );
  sprintf( ch_scale, "%d", iNu );
  strcat(filename, ch_scale);
  strcat(filename, "/");
  
  sprintf( ch_orient, "%d", iMu );
  strcat( filename, ch_orient );
  strcat(filename, "/");
  sprintf(ch_name, "%d_%d.xml", ix, iy);
  strcat(filename, ch_name);
  delete [] ch_scale;
  delete [] ch_orient;
  delete [] ch_name;
  /*  Generate filename   */
  
  CvMat* mat = (CvMat*)cvLoad( filename, NULL, NULL, NULL );
  
  CvSize size = cvGetSize( index );
  CvSize size1 = cvGetSize( mat );
  int num = size1.height;
  int ntpic = size.width;
  int numsample = nosub*ntpic;
  
  CvTrainingData *bindata = new CvTrainingData;
  CvMat* tmpmat = cvCreateMat(numsample, 1, CV_32FC1);
  bindata->init(nosub, numsample, 1);
  
  int n = 0;
  int m = 0;
  double v;
  for(int sub = 1; sub <= nosub; sub++)
  {
    for(int pic = 1; pic <= nopic; pic++)
    {
      for(int i = 0; i < ntpic; i++)
      {
        if(pic == cvGetReal1D(index, i)) 
        {
          v = cvGetReal1D(mat, n);
          cvSetReal1D(tmpmat, m, v);
          bindata->setclsidxofsample(sub, m);
          m++;
        }
      }
      n++;
    }
  }
  bindata->setdata(tmpmat);
  
  cvReleaseMat(&tmpmat);
  cvReleaseMat(&mat);
  delete [] filename;
  bindata->statclsdist();
  return bindata;
}
コード例 #26
0
void calibrateViews(std::vector<CvPoint2D32f>& corners, int rows, int cols)
{

  int nViews = corners.size()/(rows*cols);
  LINFO("Calibrate: %i views", nViews);

  if (nViews <= 0)
  {
    LINFO("No corners avl");
    return;
  }

  // Set up the object points matrix
  // Squares are size set in defines found in header file.
  CvMat* object_points = cvCreateMat(corners.size(), 3, CV_32FC1);
  for(uint k=0; k < corners.size()/(rows*cols); k++ )
  {
    for(int i=0; i < cols; i++ )
    {
      for(int j=0; j < rows; j++ )
      {
        cvmSet( object_points, k*(rows*cols) + i*rows + j, 0, GRID_SIZE*j );        // x coordinate
        cvmSet( object_points, k*(rows*cols) + i*rows + j, 1, GRID_SIZE*i ); // y coordinate
        cvmSet( object_points, k*(rows*cols) + i*rows + j, 2, 0 ); // z coordinate
      }
    }
  }

  //for (uint j = 0; j < corners.size(); j++){
  //  cvSetReal2D( object_points, j, 0, ( j % rows) * GRID_SIZE );
  //  cvSetReal2D( object_points, j, 1, ( j / rows) * GRID_SIZE );
  //  cvSetReal2D( object_points, j, 2, 0.0 );
        //}

        // Set up the matrix of points per image
        CvMat* point_counts = cvCreateMat(1, nViews, CV_32SC1);
        for(int i=0; i < nViews; i++ )
                cvSetReal1D( point_counts, i, rows*cols );

        // Copy corners found to matrix
        CvMat image_points = cvMat(corners.size(), 2, CV_32FC1, &corners[0]);



  int flags = 0;

        // Initiliazie the intrinsic matrix such that the two focal lengths
        // have a ratio of 1.0
 cvmSet( itsIntrinsicMatrix, 0, 0, 1.0);
 cvmSet( itsIntrinsicMatrix, 1, 1, 1.0);


  //flags = CV_CALIB_FIX_PRINCIPAL_POINT; // | CV_CALIB_USE_INTRINSIC_GUESS;
  //flags =  CV_CALIB_USE_INTRINSIC_GUESS;
  flags =  CV_CALIB_FIX_ASPECT_RATIO;

  cvCalibrateCamera2( object_points, &image_points, point_counts, cvSize(320,240),
      itsIntrinsicMatrix, itsDistortionCoeffs,
      NULL, NULL,
      flags);


  //display results
 // Image<byte> in = itsPCameraCellsInput[0];
 // Image<byte> out(in.getDims(), ZEROS);

 // cvUndistort2( img2ipl(in), img2ipl(out), itsIntrinsicMatrix, itsDistortionCoeffs);

 // //itsDebugImg = out;


  cvReleaseMat( &object_points);
  cvReleaseMat( &point_counts);

}
コード例 #27
0
ファイル: adaboost.cpp プロジェクト: EduFill/hbrs-ros-pkg
int AdaBoost::train(const char* samples_filename, const char* model_filename, const double ratio, double &train_error, double &test_error)
{
    CvMat* data = 0;
    CvMat* responses = 0;
    CvMat* var_type = 0;
    CvMat* temp_sample = 0;
    CvMat* weak_responses = 0;

	int ok = read_num_class_data( samples_filename, this->number_of_features_, &data, &responses );
	int nsamples_all = 0, ntrain_samples = 0;
	int var_count = 0;
	int i=0, j=0, k=0;
	double train_hr = 0, test_hr = 0;
	CvBoost boost;


	if( !ok )
	{
		cout << "Could not read the sample in" << samples_filename << endl;;
		return -1;
	}

	cout << "The sample file " << samples_filename << " is loaded." << endl;
	nsamples_all = data->rows;
	ntrain_samples = (int)(nsamples_all * ratio);
	var_count = data->cols;

	// create classifier by using <data> and <responses>
	cout << "Training the classifier ..." << endl;

   // create classifiers
	CvMat* new_data = cvCreateMat(ntrain_samples * this->number_of_classes_, var_count + 1 , CV_32F );//+1
	CvMat* new_responses = cvCreateMat( ntrain_samples * this->number_of_classes_, 1, CV_32S );

	// unroll the database type mask
	printf( "Unrolling the samples ...\n");

	for( i = 0; i < ntrain_samples; i++ )
	{
		float* data_row = (float*)(data->data.ptr + data->step*i);

		for( j = 0; j < this->number_of_classes_; j++ )
		{
			float* new_data_row = (float*)(new_data->data.ptr + new_data->step*(i * this->number_of_classes_ + j));

			for( k = 0; k < var_count; k++ )
				new_data_row[k] = data_row[k];

			new_data_row[var_count] = (float)j;
			new_responses->data.i[i * this->number_of_classes_ + j] = responses->data.fl[i] == j + FIRST_LABEL;
		}
	}

	// create type mask
	var_type = cvCreateMat( var_count + 2, 1, CV_8U );
	cvSet( var_type, cvScalarAll(CV_VAR_ORDERED));

	// the last indicator variable, as well
	// as the new (binary) response are categorical
	cvSetReal1D( var_type, var_count, CV_VAR_CATEGORICAL );//CV_VAR_CATEGORICAL CV_VAR_NUMERICAL
	cvSetReal1D( var_type, var_count+1, CV_VAR_CATEGORICAL ); //CV_VAR_CATEGORICAL

	// train classifier
	//printf( "training the classifier (may take a few minutes)...");
	boost.train( new_data, CV_ROW_SAMPLE, new_responses, 0, 0, var_type, 0, this->boost_parameters_);

	cvReleaseMat( &new_data );
	cvReleaseMat( &new_responses );
	//printf("\n");

	temp_sample = cvCreateMat( 1, var_count + 1, CV_32F );
	weak_responses = cvCreateMat( 1, boost.get_weak_predictors()->total, CV_32F );

	// compute prediction error on train and test data
	for( i = 0; i < nsamples_all; i++ )
	{
		int best_class = 0;
		double max_sum = -DBL_MAX;
		double r;
		CvMat sample;
		cvGetRow( data, &sample, i );

		for( k = 0; k < var_count; k++ )
			temp_sample->data.fl[k] = sample.data.fl[k];

		for( j = 0; j < this->number_of_classes_; j++ )
		{
			temp_sample->data.fl[var_count] = (float)j;

			boost.predict( temp_sample, 0, weak_responses );
			double sum = cvSum( weak_responses ).val[0];

			if( max_sum < sum )
			{
				max_sum = sum;
				best_class = j + FIRST_LABEL;
			}
		}

		r = fabs(best_class - responses->data.fl[i]) < FLT_EPSILON ? 1 : 0;

		if( i < ntrain_samples )
			train_hr += r;
		else
			test_hr += r;
	}

	train_hr /= (double)ntrain_samples;
	test_hr /= ((double)nsamples_all - (double)ntrain_samples);

	cout << "Recognition rate: train = " << train_hr * 100 << ", test = " << test_hr * 100 << endl;

	// fill result-parameters
	train_error = 1 - train_hr;
	test_error = 1 - test_hr;

	// Save classifier to file if needed
	if( model_filename )
		boost.save( model_filename );

	boost.clear();
	cvReleaseMat( &temp_sample );
	cvReleaseMat( &weak_responses );
	cvReleaseMat( &var_type );
	cvReleaseMat( &data );
	cvReleaseMat( &responses );

	return 0;
}
コード例 #28
0
static
int build_rtrees_classifier( char* data_filename,
    char* filename_to_save, char* filename_to_load )
{
    CvMat* data = 0;
    CvMat* responses = 0;
    CvMat* var_type = 0;
    CvMat* sample_idx = 0;

    int ok = read_num_class_data( data_filename, 16, &data, &responses );
    int nsamples_all = 0, ntrain_samples = 0;
    int i = 0;
    double train_hr = 0, test_hr = 0;
    CvRTrees forest;
    CvMat* var_importance = 0;

    if( !ok )
    {
        printf( "Could not read the database %s\n", data_filename );
        return -1;
    }

    printf( "The database %s is loaded.\n", data_filename );
    nsamples_all = data->rows;
    ntrain_samples = (int)(nsamples_all*0.8);

    // Create or load Random Trees classifier
    if( filename_to_load )
    {
        // load classifier from the specified file
        forest.load( filename_to_load );
        ntrain_samples = 0;
        if( forest.get_tree_count() == 0 )
        {
            printf( "Could not read the classifier %s\n", filename_to_load );
            return -1;
        }
        printf( "The classifier %s is loaded.\n", data_filename );
    }
    else
    {
        // create classifier by using <data> and <responses>
        printf( "Training the classifier ...\n");

        // 1. create type mask
        var_type = cvCreateMat( data->cols + 1, 1, CV_8U );
        cvSet( var_type, cvScalarAll(CV_VAR_ORDERED) );
        cvSetReal1D( var_type, data->cols, CV_VAR_CATEGORICAL );

        // 2. create sample_idx
        sample_idx = cvCreateMat( 1, nsamples_all, CV_8UC1 );
        {
            CvMat mat;
            cvGetCols( sample_idx, &mat, 0, ntrain_samples );
            cvSet( &mat, cvRealScalar(1) );

            cvGetCols( sample_idx, &mat, ntrain_samples, nsamples_all );
            cvSetZero( &mat );
        }

        // 3. train classifier
        forest.train( data, CV_ROW_SAMPLE, responses, 0, sample_idx, var_type, 0,
            CvRTParams(10,10,0,false,15,0,true,4,100,0.01f,CV_TERMCRIT_ITER));
        printf( "\n");
    }

    // compute prediction error on train and test data
    for( i = 0; i < nsamples_all; i++ )
    {
        double r;
        CvMat sample;
        cvGetRow( data, &sample, i );

        r = forest.predict( &sample );
        r = fabs((double)r - responses->data.fl[i]) <= FLT_EPSILON ? 1 : 0;

        if( i < ntrain_samples )
            train_hr += r;
        else
            test_hr += r;
    }

    test_hr /= (double)(nsamples_all-ntrain_samples);
    train_hr /= (double)ntrain_samples;
    printf( "Recognition rate: train = %.1f%%, test = %.1f%%\n",
            train_hr*100., test_hr*100. );

    printf( "Number of trees: %d\n", forest.get_tree_count() );

    // Print variable importance
    var_importance = (CvMat*)forest.get_var_importance();
    if( var_importance )
    {
        double rt_imp_sum = cvSum( var_importance ).val[0];
        printf("var#\timportance (in %%):\n");
        for( i = 0; i < var_importance->cols; i++ )
            printf( "%-2d\t%-4.1f\n", i,
            100.f*var_importance->data.fl[i]/rt_imp_sum);
    }

    //Print some proximitites
    printf( "Proximities between some samples corresponding to the letter 'T':\n" );
    {
        CvMat sample1, sample2;
        const int pairs[][2] = {{0,103}, {0,106}, {106,103}, {-1,-1}};

        for( i = 0; pairs[i][0] >= 0; i++ )
        {
            cvGetRow( data, &sample1, pairs[i][0] );
            cvGetRow( data, &sample2, pairs[i][1] );
            printf( "proximity(%d,%d) = %.1f%%\n", pairs[i][0], pairs[i][1],
                forest.get_proximity( &sample1, &sample2 )*100. );
        }
    }

    // Save Random Trees classifier to file if needed
    if( filename_to_save )
        forest.save( filename_to_save );

    cvReleaseMat( &sample_idx );
    cvReleaseMat( &var_type );
    cvReleaseMat( &data );
    cvReleaseMat( &responses );

    return 0;
}
コード例 #29
0
ファイル: ahistograms.cpp プロジェクト: SCS-B3C/OpenCV2-2
void CV_QueryHistTest::run_func(void)
{
    int i, iters = values->cols;
    CvArr* h = hist[0]->bins;
    const int* idx = indices->data.i;
    float* val = values->data.fl;
    float default_value = 0.f;

    // stage 1: write bins
    if( cdims == 1 )
        for( i = 0; i < iters; i++ )
        {
            float v0 = values0->data.fl[i];
            if( fabs(v0 - default_value) < FLT_EPSILON )
                continue;
            if( !(i % 2) )
            {
                if( !(i % 4) )
                    cvSetReal1D( h, idx[i], v0 );
                else
                    *(float*)cvPtr1D( h, idx[i] ) = v0;
            }
            else
                cvSetRealND( h, idx+i, v0 );
        }
    else if( cdims == 2 )
        for( i = 0; i < iters; i++ )
        {
            float v0 = values0->data.fl[i];
            if( fabs(v0 - default_value) < FLT_EPSILON )
                continue;
            if( !(i % 2) )
            {
                if( !(i % 4) )
                    cvSetReal2D( h, idx[i*2], idx[i*2+1], v0 );
                else
                    *(float*)cvPtr2D( h, idx[i*2], idx[i*2+1] ) = v0;
            }
            else
                cvSetRealND( h, idx+i*2, v0 );
        }
    else if( cdims == 3 )
        for( i = 0; i < iters; i++ )
        {
            float v0 = values0->data.fl[i];
            if( fabs(v0 - default_value) < FLT_EPSILON )
                continue;
            if( !(i % 2) )
            {
                if( !(i % 4) )
                    cvSetReal3D( h, idx[i*3], idx[i*3+1], idx[i*3+2], v0 );
                else
                    *(float*)cvPtr3D( h, idx[i*3], idx[i*3+1], idx[i*3+2] ) = v0;
            }
            else
                cvSetRealND( h, idx+i*3, v0 );
        }
    else
        for( i = 0; i < iters; i++ )
        {
            float v0 = values0->data.fl[i];
            if( fabs(v0 - default_value) < FLT_EPSILON )
                continue;
            if( !(i % 2) )
                cvSetRealND( h, idx+i*cdims, v0 );
            else
                *(float*)cvPtrND( h, idx+i*cdims ) = v0;
        }

    // stage 2: read bins
    if( cdims == 1 )
        for( i = 0; i < iters; i++ )
        {
            if( !(i % 2) )
                val[i] = *(float*)cvPtr1D( h, idx[i] );
            else
                val[i] = (float)cvGetReal1D( h, idx[i] );
        }
    else if( cdims == 2 )
        for( i = 0; i < iters; i++ )
        {
            if( !(i % 2) )
                val[i] = *(float*)cvPtr2D( h, idx[i*2], idx[i*2+1] );
            else
                val[i] = (float)cvGetReal2D( h, idx[i*2], idx[i*2+1] );
        }
    else if( cdims == 3 )
        for( i = 0; i < iters; i++ )
        {
            if( !(i % 2) )
                val[i] = *(float*)cvPtr3D( h, idx[i*3], idx[i*3+1], idx[i*3+2] );
            else
                val[i] = (float)cvGetReal3D( h, idx[i*3], idx[i*3+1], idx[i*3+2] );
        }
    else
        for( i = 0; i < iters; i++ )
        {
            if( !(i % 2) )
                val[i] = *(float*)cvPtrND( h, idx+i*cdims );
            else
                val[i] = (float)cvGetRealND( h, idx+i*cdims );
        }
}