Esempio n. 1
0
int
main (int argc, char **argv)
{
  char filename[] = "save_cv.xml";	// file name
  int i,j,k;
  CvFileStorage *cvfs;
  CvFileNode *node, *fn;
  CvSeq *s;
  int total;

  // (1)memory space for loading data
  int a;
  float b;
  CvMat** mat = (CvMat**)cvAlloc(3*sizeof(CvMat*));

  // (2)open file storage
  cvfs = cvOpenFileStorage(filename, NULL, CV_STORAGE_READ);

  // (3)read data from file storage
  node = cvGetFileNodeByName(cvfs, NULL, "");	// Get Top Node

  a = cvReadIntByName(cvfs, node, "a", 0);
  b = cvReadRealByName(cvfs, node, "b", 0);

  fn = cvGetFileNodeByName(cvfs,node,"mat_array");

  s = fn->data.seq;
  total = s->total;
  for(i=0;i<total;i++){
    mat[i] = (CvMat*)cvRead(cvfs,(CvFileNode*)cvGetSeqElem(s,i), NULL);
  }

  // (4)close file storage
  cvReleaseFileStorage(&cvfs);

  // (5)print loaded data
  printf("a:%d\n", a);
  printf("b:%f\n", b);
  for(i=0; i<3; i++){
    printf("mat%d:\n",i);
    for(j=0;j<mat[i]->rows;j++){
      for(k=0;k<mat[i]->cols;k++){
	printf("%f,",cvmGet(mat[i],j,k));
      }
      printf("\n");
    }
  }

  // release mat
  for(i=0; i<3; i++){
    cvReleaseMat(mat+i);
  }
  cvFree(mat);

  return 0;
}
Esempio n. 2
0
void CvANN_MLP::read( CvFileStorage* fs, CvFileNode* node )
{
    CvMat* _layer_sizes = 0;
    
    CV_FUNCNAME( "CvANN_MLP::read" );

    __BEGIN__;

    CvFileNode* w;
    CvSeqReader reader;
    int i, l_count;

    _layer_sizes = (CvMat*)cvReadByName( fs, node, "layer_sizes" );
    CV_CALL( create( _layer_sizes, SIGMOID_SYM, 0, 0 ));
    l_count = layer_sizes->cols;

    CV_CALL( read_params( fs, node ));

    w = cvGetFileNodeByName( fs, node, "input_scale" );
    if( !w || CV_NODE_TYPE(w->tag) != CV_NODE_SEQ ||
        w->data.seq->total != layer_sizes->data.i[0]*2 )
        CV_ERROR( CV_StsParseError, "input_scale tag is not found or is invalid" );

    CV_CALL( cvReadRawData( fs, w, weights[0], "d" ));

    w = cvGetFileNodeByName( fs, node, "output_scale" );
    if( !w || CV_NODE_TYPE(w->tag) != CV_NODE_SEQ ||
        w->data.seq->total != layer_sizes->data.i[l_count-1]*2 )
        CV_ERROR( CV_StsParseError, "output_scale tag is not found or is invalid" );

    CV_CALL( cvReadRawData( fs, w, weights[l_count], "d" ));

    w = cvGetFileNodeByName( fs, node, "inv_output_scale" );
    if( !w || CV_NODE_TYPE(w->tag) != CV_NODE_SEQ ||
        w->data.seq->total != layer_sizes->data.i[l_count-1]*2 )
        CV_ERROR( CV_StsParseError, "inv_output_scale tag is not found or is invalid" );

    CV_CALL( cvReadRawData( fs, w, weights[l_count+1], "d" ));

    w = cvGetFileNodeByName( fs, node, "weights" );
    if( !w || CV_NODE_TYPE(w->tag) != CV_NODE_SEQ ||
        w->data.seq->total != l_count - 1 )
        CV_ERROR( CV_StsParseError, "weights tag is not found or is invalid" );

    cvStartReadSeq( w->data.seq, &reader );

    for( i = 1; i < l_count; i++ )
    {
        w = (CvFileNode*)reader.ptr;
        CV_CALL( cvReadRawData( fs, w, weights[i], "d" ));
        CV_NEXT_SEQ_ELEM( reader.seq->elem_size, reader );
    }

    __END__;
}
// --------------------------------------------------------------------------
// main(Number of arguments, Argument values)
// Description  : This is the entry point of the program.
// Return value : SUCCESS:0  ERROR:-1
// --------------------------------------------------------------------------
int main(int argc, char **argv)
{
    // AR.Drone class
    ARDrone ardrone;

    // Initialize
    if (!ardrone.open()) {
        printf("Failed to initialize.\n");
        return -1;
    }

    // Image of AR.Drone's camera
    IplImage *image = ardrone.getImage();

    // Read intrincis camera parameters
    CvFileStorage *fs = cvOpenFileStorage("camera.xml", 0, CV_STORAGE_READ);
    CvMat *intrinsic = (CvMat*)cvRead(fs, cvGetFileNodeByName(fs, NULL, "intrinsic"));
    CvMat *distortion = (CvMat*)cvRead(fs, cvGetFileNodeByName(fs, NULL, "distortion"));

    // Initialize undistortion maps
    CvMat *mapx = cvCreateMat(image->height, image->width, CV_32FC1);
    CvMat *mapy = cvCreateMat(image->height, image->width, CV_32FC1);
    cvInitUndistortMap(intrinsic, distortion, mapx, mapy);

    // Main loop
    while (1) {
        // Key input
        int key = cvWaitKey(1);
        if (key == 0x1b) break;

        // Update
        if (!ardrone.update()) break;

        // Get an image
        image = ardrone.getImage();

        // Remap the image
        cvRemap(image, image, mapx, mapy);

        // Display the image
        cvShowImage("camera", image);
    }

    // Release the matrices
    cvReleaseMat(&mapx);
    cvReleaseMat(&mapy);
    cvReleaseFileStorage(&fs);

    // See you
    ardrone.close();

    return 0;
}
Esempio n. 4
0
bool ObjectDefinition::Load(const char* filename)
{
	do{
		CvFileStorage* storage = cvOpenFileStorage(filename, 0, CV_STORAGE_READ);
		m_keypoints = (CvSeq*)cvRead(storage, cvGetFileNodeByName(storage, 0, "keypoints"));
		m_descriptor = (CvSeq*)cvRead(storage, cvGetFileNodeByName(storage, 0, "descriptor"));
		cvReadRawData(storage, cvGetFileNodeByName(storage, 0, "corners"), m_corners, "ii");
		cvReleaseFileStorage(&storage);
		m_filename = filename; 
		return true;
	}while(false);
	return false;
}
Esempio n. 5
0
void GazeTracker::load() {
	CvFileStorage *in = cvOpenFileStorage("calibration.xml", NULL, CV_STORAGE_READ);
	CvFileNode *root = cvGetRootFileNode(in);
	load(in, cvGetFileNodeByName(in, root, "GazeTracker"));
	cvReleaseFileStorage(&in);
	updateGaussianProcesses();
}
Esempio n. 6
0
int main(int argc, const char * argv[]) {
    CvMat *cmatrix = cvCreateMat(5,5,CV_32FC1);
    float element_3_2 = 7.7;
    *((float*)CV_MAT_ELEM_PTR( *cmatrix, 3,2) ) = element_3_2;
    cvmSet(cmatrix,4,4,0.5000);
    cvSetReal2D(cmatrix,3,3,0.5000);
    
    CvFileStorage* fs1 = cvOpenFileStorage("cfg.xml", 0, CV_STORAGE_WRITE);
    cvWriteInt( fs1, "frame_count", 10 );
    cvStartWriteStruct( fs1, "frame_size", CV_NODE_SEQ );
    cvWriteInt( fs1 , 0, 320 );
    cvWriteInt( fs1 , 0, 200 );
    cvEndWriteStruct( fs1 );
    cvWrite( fs1, "color_cvt_matrix", cmatrix );
    cvReleaseFileStorage( &fs1 );
    
    CvFileStorage* fs2 = cvOpenFileStorage("cfg.xml", 0, CV_STORAGE_READ);
    int frame_count = cvReadIntByName( fs2 , 0, "frame_count");
    CvSeq* s = cvGetFileNodeByName( fs2,0,"frame_size" )->data.seq;
    int frame_width = cvReadInt( (CvFileNode*)cvGetSeqElem(s,0) );
    int frame_height = cvReadInt( (CvFileNode*)cvGetSeqElem(s,1) );
    CvMat* color_cvt_matrix = (CvMat*) cvReadByName( fs2, 0 , "color_cvt_matrix");
    
    printf("color_cvt_matrix: width=%d, height=%d\n",color_cvt_matrix->width, color_cvt_matrix->height );
    printf("frame_count=%d, frame_width=%d, frame_height=%d\n",frame_count,frame_width,frame_height);
    
    cvReleaseFileStorage( &fs2 );
    
    return 0;
}
Esempio n. 7
0
void read_pseudocolor(char* file, Pseudocolor *psdata)
{
	CvFileStorage* storage = cvOpenFileStorage( file, 0, CV_STORAGE_READ );
	if(storage==NULL){
		fprintf(stderr, "Error reading file %s\n",file);
		return;
	}	
	CvFileNode* p_node = cvGetFileNodeByName( storage, NULL, "p" );
	CvFileNode* t_node = cvGetFileNodeByName( storage, NULL, "t" );
	CvFileNode* table_node = cvGetFileNodeByName( storage, NULL, "table" );
	
	cvReadRawData(storage, p_node, psdata->p,"f");
	cvReadRawData(storage, t_node, psdata->t,"f");
	cvReadRawData(storage, table_node, psdata->table,"u");
	cvReleaseFileStorage( &storage );
}
/*!
    \fn CvBinGabAdaFeatureSelect::loadweaks(const char* filename)
 */
void CvBinGabAdaFeatureSelect::loadweaks(const char* filename)
{
  //clear();
  {
    delete new_pool;
    weaks.clear();
  }
  CvMemStorage* fstorage = cvCreateMemStorage( 0 );
  CvFileStorage *fs;
  fs = cvOpenFileStorage( filename, fstorage, CV_STORAGE_READ );
  CvFileNode *root = cvGetRootFileNode( fs, 0);
  char *weakname = new char[20];
  int i = 0;
  
  CvMemStorage* storage = cvCreateMemStorage(0);
  CvSeq* seq = cvCreateSeq(0, sizeof(CvSeq), sizeof(CvGaborTree), storage );
  while(1)
  {
    sprintf( weakname, "weak_%d", i);
    CvFileNode *weaknode = cvGetFileNodeByName( fs, root, weakname);
    if (!weaknode) break;
    CvGaborTree tree;
    weaknode2tree(weaknode, fs, &tree);
    cvSeqPush( seq, &tree );
    i++;	
  }
  
    /* from squence to vector weaks*/
  new_pool = new CvGaborFeaturePool;
  for (int i = 0; i <seq->total; i++)
  {
    CvGaborTree *atree = (CvGaborTree*)cvGetSeqElem(seq, i);
    CvWeakLearner *weak = new CvWeakLearner;
    weak->setType( weaklearner_type );
    weak->setthreshold(atree->threshold);
    weak->setparity(atree->parity);
    weaks.push_back(*weak);
    CvGaborFeature *feature = new CvGaborFeature(atree->x, atree->y, atree->Mu, atree->Nu);
    new_pool->add(feature);
    alphas.push_back(atree->alpha);
    delete weak;
    delete feature;
  } 
  
  cvReleaseMemStorage( &storage );
  cvReleaseFileStorage(&fs);
  cvReleaseMemStorage( &fstorage );
  delete [] weakname;
  
    /* set member variables */
  current = new_pool->getSize();
  falsepositive = 0.0;
  nexpfeatures = new_pool->getSize();
  nselecfeatures = new_pool->getSize();
  printf(" %d weak classifiers have been loaded!\n", nselecfeatures);
}
 virtual void LoadState(CvFileStorage* fs, CvFileNode* node)
 {
     CvFileNode* BlobListNode = cvGetFileNodeByName(fs,node,"BlobList");
     m_FrameCount = cvReadIntByName(fs,node, "FrameCount", m_FrameCount);
     m_NextBlobID = cvReadIntByName(fs,node, "NextBlobID", m_NextBlobID);
     if(BlobListNode)
     {
         m_BlobList.Load(fs,BlobListNode);
     }
 };
Esempio n. 10
0
void CvGBTrees::read_params( CvFileStorage* fs, CvFileNode* fnode )
{
    CV_FUNCNAME( "CvGBTrees::read_params" );
    __BEGIN__;


    CvFileNode* temp;

    if( !fnode || !CV_NODE_IS_MAP(fnode->tag) )
        return;

    data = new CvDTreeTrainData();
    CV_CALL( data->read_params(fs, fnode));
    data->shared = true;

    params.max_depth = data->params.max_depth;
    params.min_sample_count = data->params.min_sample_count;
    params.max_categories = data->params.max_categories;
    params.priors = data->params.priors;
    params.regression_accuracy = data->params.regression_accuracy;
    params.use_surrogates = data->params.use_surrogates;

    temp = cvGetFileNodeByName( fs, fnode, "loss_function" );
    if( !temp )
        EXIT;

    if( temp && CV_NODE_IS_STRING(temp->tag) )
    {
        const char* loss_function_type_str = cvReadString( temp, "" );
        params.loss_function_type = strcmp( loss_function_type_str, "SquaredLoss" ) == 0 ? SQUARED_LOSS :
                            strcmp( loss_function_type_str, "AbsoluteLoss" ) == 0 ? ABSOLUTE_LOSS :
                            strcmp( loss_function_type_str, "HuberLoss" ) == 0 ? HUBER_LOSS :
                            strcmp( loss_function_type_str, "DevianceLoss" ) == 0 ? DEVIANCE_LOSS : -1;
    }
    else
        params.loss_function_type = cvReadInt( temp, -1 );


    if( params.loss_function_type < SQUARED_LOSS || params.loss_function_type > DEVIANCE_LOSS ||  params.loss_function_type == 2)
        CV_ERROR( CV_StsBadArg, "Unknown loss function" );

    params.weak_count = cvReadIntByName( fs, fnode, "ensemble_length" );
    params.shrinkage = (float)cvReadRealByName( fs, fnode, "shrinkage", 0.1 );
    params.subsample_portion = (float)cvReadRealByName( fs, fnode, "subsample_portion", 1.0 );

    if (data->is_classifier)
    {
        class_labels = (CvMat*)cvReadByName( fs, fnode, "class_labels" );
        if( class_labels && !CV_IS_MAT(class_labels))
            CV_ERROR( CV_StsParseError, "class_labels must stored as a matrix");
    }
    data->is_classifier = 0;

    __END__;
}
Esempio n. 11
0
void CvGBTrees::read( CvFileStorage* fs, CvFileNode* node )
{

    CV_FUNCNAME( "CvGBTrees::read" );

    __BEGIN__;

    CvSeqReader reader;
    CvFileNode* trees_fnode;
    CvMemStorage* storage;
    int i, ntrees;
    cv::String s;

    clear();
    read_params( fs, node );

    if( !data )
        EXIT;

    base_value = (float)cvReadRealByName( fs, node, "base_value", 0.0 );
    class_count = cvReadIntByName( fs, node, "class_count", 1 );

    weak = new pCvSeq[class_count];


    for (int j=0; j<class_count; ++j)
    {
        s = cv::format("trees_%d", j);

        trees_fnode = cvGetFileNodeByName( fs, node, s.c_str() );
        if( !trees_fnode || !CV_NODE_IS_SEQ(trees_fnode->tag) )
            CV_ERROR( CV_StsParseError, "<trees_x> tag is missing" );

        cvStartReadSeq( trees_fnode->data.seq, &reader );
        ntrees = trees_fnode->data.seq->total;

        if( ntrees != params.weak_count )
            CV_ERROR( CV_StsUnmatchedSizes,
            "The number of trees stored does not match <ntrees> tag value" );

        CV_CALL( storage = cvCreateMemStorage() );
        weak[j] = cvCreateSeq( 0, sizeof(CvSeq), sizeof(CvDTree*), storage );

        for( i = 0; i < ntrees; i++ )
        {
            CvDTree* tree = new CvDTree();
            CV_CALL(tree->read( fs, (CvFileNode*)reader.ptr, data ));
            CV_NEXT_SEQ_ELEM( reader.seq->elem_size, reader );
            cvSeqPush( weak[j], &tree );
        }
    }

    __END__;
}
Esempio n. 12
0
int CV_MLBaseTest::read_params( CvFileStorage* _fs )
{
    if( !_fs )
        test_case_count = -1;
    else
    {
        CvFileNode* fn = cvGetRootFileNode( _fs, 0 );
        fn = (CvFileNode*)cvGetSeqElem( fn->data.seq, 0 );
        fn = cvGetFileNodeByName( _fs, fn, "run_params" );
        CvSeq* dataSetNamesSeq = cvGetFileNodeByName( _fs, fn, modelName.c_str() )->data.seq;
        test_case_count = dataSetNamesSeq ? dataSetNamesSeq->total : -1;
        if( test_case_count > 0 )
        {
            dataSetNames.resize( test_case_count );
            vector<string>::iterator it = dataSetNames.begin();
            for( int i = 0; i < test_case_count; i++, it++ )
                *it = ((CvFileNode*)cvGetSeqElem( dataSetNamesSeq, i ))->data.str.ptr;
        }
    }
    return CvTS::OK;;
}
Esempio n. 13
0
bool CvImage::read( CvFileStorage* fs, const char* seqname, int idx )
{
    void* obj = 0;
    IplImage* img = 0;
    CvFileNode* seqnode = seqname ?
        cvGetFileNodeByName( fs, 0, seqname ) : cvGetRootFileNode(fs,0);

    if( seqnode && CV_NODE_IS_SEQ(seqnode->tag) )
        obj = cvRead( fs, (CvFileNode*)cvGetSeqElem( seqnode->data.seq, idx ));
    img = icvRetrieveImage(obj);
    attach( img );
    return img != 0;
}
Esempio n. 14
0
bool CvMatrix::read( CvFileStorage* fs, const char* seqname, int idx )
{
    void* obj = 0;
    CvMat* m = 0;
    CvFileNode* seqnode = seqname ?
        cvGetFileNodeByName( fs, 0, seqname ) : cvGetRootFileNode(fs,0);

    if( seqnode && CV_NODE_IS_SEQ(seqnode->tag) )
        obj = cvRead( fs, (CvFileNode*)cvGetSeqElem( seqnode->data.seq, idx ));
    m = icvRetrieveMatrix(obj);
    set( m, false );
    return m != 0;
}
Esempio n. 15
0
void read_my_struct( CvFileStorage* fs, CvFileNode* ms_node, my_struct* ms) {

    ms->i = cvReadIntByName(
      fs,
      NULL,       // search a top-level node
      "integer",  // node name
      456         // default value
    );

    CvSeq *s;

    s = cvGetFileNodeByName(fs, 0, "point")->data.seq;
    ms->point.x = cvReadInt( (CvFileNode *)cvGetSeqElem(s, 0) );
    ms->point.y = cvReadInt( (CvFileNode *)cvGetSeqElem(s, 1) );
    
    s = cvGetFileNodeByName(fs, 0, "rectangle")->data.seq;
    ms->rect.x = cvReadInt( (CvFileNode *)cvGetSeqElem(s, 0) );
    ms->rect.y = cvReadInt( (CvFileNode *)cvGetSeqElem(s, 1) );
    ms->rect.width = cvReadInt( (CvFileNode *)cvGetSeqElem(s, 2) );
    ms->rect.height = cvReadInt( (CvFileNode *)cvGetSeqElem(s, 3) );

}
Esempio n. 16
0
/*!
    \fn CvGaborFeature::val(const char *filename) const
 */
double CvGaborFeature::val(const char *filename) const
{
    double ve;
    CvFileStorage *fs;
    fs = cvOpenFileStorage( filename, NULL, CV_STORAGE_READ );
    if (!fs)
    {
       printf("Error: Can not open %s \n", filename);
       exit(-1);
    }
    char *name;
    name = new char[20];
    extractname(name, filename);
    CvFileNode *node;
    node = cvGetFileNodeByName( fs, 0, name );
    CvFileNode *nodew;
    nodew = cvGetFileNodeByName( fs, node, "width" );
    int width = cvReadInt(nodew);
    CvFileNode *nodeh;
    nodeh = cvGetFileNodeByName( fs, node, "height" );
    int height = cvReadInt(nodeh);

    CvFileNode *nodedata;
    nodedata = cvGetFileNodeByName( fs, node, "data" );
    CvSeq* seq = nodedata->data.seq;
    
    CvSeqReader reader;
    cvStartReadSeq( seq, &reader, 0 );

    int num = (iy-1)*width + ix - 1;
 
    CvFileNode* pt = (CvFileNode*)reader.ptr + num;
    
    ve = pt->data.f;
    delete [] name;
    cvReleaseFileStorage(&fs);
    return ve;
}
Esempio n. 17
0
bool CvMatrix::read( CvFileStorage* fs, const char* mapname, const char* matname )
{
    void* obj = 0;
    CvMat* m = 0;

    if( mapname )
    {
        CvFileNode* mapnode = cvGetFileNodeByName( fs, 0, mapname );
        if( !mapnode )
            obj = cvReadByName( fs, mapnode, matname );
    }
    else
        obj = cvReadByName( fs, 0, matname );

    m = icvRetrieveMatrix(obj);
    set( m, false );
    return m != 0;
}
Esempio n. 18
0
bool CvImage::read( CvFileStorage* fs, const char* mapname, const char* imgname )
{
    void* obj = 0;
    IplImage* img = 0;

    if( mapname )
    {
        CvFileNode* mapnode = cvGetFileNodeByName( fs, 0, mapname );
        if( !mapnode )
            obj = cvReadByName( fs, mapnode, imgname );
    }
    else
        obj = cvReadByName( fs, 0, imgname );

    img = icvRetrieveImage(obj);
    attach( img );
    return img != 0;
}
    virtual void LoadState(CvFileStorage* fs, CvFileNode* node)
    {
        int         b,bN = cvReadIntByName(fs,node,"BlobNum",0);
        CvFileNode* pBlobListNode = cvGetFileNodeByName(fs,node,"BlobList");
        if(!CV_NODE_IS_SEQ(pBlobListNode->tag)) return;
        bN = pBlobListNode->data.seq->total;

        for(b=0; b<bN; ++b)
        {
            DefBlobTrackerCR*   pF = NULL;
            CvBlob              Blob;
            CvFileNode*         pSeqNode = NULL;
            CvFileNode*         pBlobNode = (CvFileNode*)cvGetSeqElem(pBlobListNode->data.seq,b);
            assert(pBlobNode);

            Blob.ID = cvReadIntByName(fs,pBlobNode,"ID",0);

            pSeqNode = cvGetFileNodeByName(fs, pBlobNode, "Blob");
            if(CV_NODE_IS_SEQ(pSeqNode->tag))
                cvReadRawData( fs, pSeqNode, &Blob, "ffffi" );

            AddBlob(&Blob,NULL,NULL);
            pF = (DefBlobTrackerCR*)m_BlobList.GetBlobByID(Blob.ID);

            pSeqNode = cvGetFileNodeByName(fs, pBlobNode, "BlobPredict");
            if(CV_NODE_IS_SEQ(pSeqNode->tag))
                cvReadRawData( fs, pSeqNode, &pF->BlobPredict, "ffffi" );

            pSeqNode = cvGetFileNodeByName(fs, pBlobNode, "BlobPrev");
            if(CV_NODE_IS_SEQ(pSeqNode->tag))
                cvReadRawData( fs, pSeqNode, &pF->BlobPrev, "ffffi" );

            pSeqNode = cvGetFileNodeByName(fs, pBlobNode, "BlobHyp");
            if(pSeqNode)
                pF->pBlobHyp->Load(fs,pSeqNode);
            pF->Collision = cvReadIntByName(fs, pBlobNode,"Collision",pF->Collision);

            pSeqNode = cvGetFileNodeByName(fs, pBlobNode, "Predictor");
            if(pSeqNode)
                pF->pPredictor->LoadState(fs,pSeqNode);

            pSeqNode = cvGetFileNodeByName(fs, pBlobNode, "Resolver");
            if(pSeqNode)
                pF->pResolver->LoadState(fs,pSeqNode);
        }   /* Read next blob. */
    }   /*  CCwithCR LoadState */
Esempio n. 20
0
void cvReadStructByName(CvFileStorage* fs, CvFileNode* node, const char* name, void* addr, const char* desc)
{
    CvFileNode* pSeqNode = cvGetFileNodeByName(fs, node, name);
    if(pSeqNode==NULL)
    {
        printf("WARNING!!! Can't read structure %s\n",name);
    }
    else
    {
        if(CV_NODE_IS_SEQ(pSeqNode->tag))
        {
            cvReadRawData( fs, pSeqNode, addr, desc );
        }
        else
        {
            printf("WARNING!!! Structure %s is not sequence and can not be read\n",name);
        }
    }
}
void KITECH_HSVColorRecognitionComp::GetDataFromDB(const char* database)
{
	char str[256];
	CvFileStorage *fs = cvOpenFileStorage(database, 0, CV_STORAGE_READ);
	int colorCount = cvReadIntByName(fs, 0, "color_count");
	ColorRange colorRange;
	for( int i = 0  ;  i < colorCount  ;  i++ ) {
		sprintf(str, "color%d", i);
		CvSeq *s = cvGetFileNodeByName(fs, 0, str)->data.seq;
		colorRange.name = cvReadString( (CvFileNode*)cvGetSeqElem(s, 0) );
		colorRange.min1 = cvReadInt( (CvFileNode*)cvGetSeqElem(s, 1) );
		colorRange.max1 = cvReadInt( (CvFileNode*)cvGetSeqElem(s, 2) );
		colorRange.min2 = cvReadInt( (CvFileNode*)cvGetSeqElem(s, 3) );
		colorRange.max2 = cvReadInt( (CvFileNode*)cvGetSeqElem(s, 4) );
		colorRange.min3 = cvReadInt( (CvFileNode*)cvGetSeqElem(s, 5) );
		colorRange.max3 = cvReadInt( (CvFileNode*)cvGetSeqElem(s, 6) );
		_colorRange.push_back(colorRange);
//		PrintMessage("INFO:KITECH_HSVColorRecognitionComp::Add color data : %s\n", colorRange.name.c_str());
	}
}
/*!
    \fn CvBinGabAdaFeatureSelect::weaknode2tree(CvFileNode *node, CvFileStorage *fs, CvGaborTree *tree)
 */
void CvBinGabAdaFeatureSelect::weaknode2tree(CvFileNode *node, CvFileStorage *fs, CvGaborTree *tree)
{
  CvFileNode *xnode = cvGetFileNodeByName( fs, node, "x");
  CvFileNode *ynode = cvGetFileNodeByName( fs, node, "y");
  CvFileNode *Munode = cvGetFileNodeByName( fs, node, "Mu");
  CvFileNode *Nunode = cvGetFileNodeByName( fs, node, "Nu");
  CvFileNode *anode = cvGetFileNodeByName( fs, node, "alpha");
  CvFileNode *tnode = cvGetFileNodeByName( fs, node, "threshold");
  CvFileNode *pnode = cvGetFileNodeByName( fs, node, "parity");
  int x = cvReadInt( xnode, 0);
  int y = cvReadInt( ynode, 0);
  int Mu = cvReadInt( Munode, 0);
  int Nu = cvReadInt( Nunode, 0);
  double alpha = cvReadReal( anode, 0);
  double threshold = cvReadReal( tnode, 0);
  double parity = cvReadReal( pnode, 0);
  tree->x = x;
  tree->y = y;
  tree->Mu = Mu;
  tree->Nu = Nu;
  tree->alpha = alpha;
  tree->threshold = threshold;
  tree->parity = parity;
}
Esempio n. 23
0
void CalTarget::load(CvFileStorage *in, CvFileNode *node) {
	point.load(in, cvGetFileNodeByName(in, node, "point"));
	image.reset((cv::Mat*) cvReadByName(in, node, "image"));
	origImage.reset((cv::Mat*) cvReadByName(in, node, "origImage"));
}
Esempio n. 24
0
int CV_DTreeTest :: train( int test_case_idx )
{
    int MAX_DEPTH, MIN_SAMPLE_COUNT, MAX_CATEGORIES, CV_FOLDS;
    float REG_ACCURACY = 0;
    bool USE_SURROGATE, IS_PRUNED;
    
    const char* data_name = ((CvFileNode*)cvGetSeqElem( data_sets_names, test_case_idx ))->data.str.ptr;      

    // read validation params
    CvFileStorage* fs = ts->get_file_storage();
    CvFileNode* fnode = cvGetFileNodeByName( fs, 0, "validation" ), *fnode1 = 0;
    fnode = cvGetFileNodeByName( fs, fnode, name );
    fnode = cvGetFileNodeByName( fs, fnode, data_name );
    fnode = cvGetFileNodeByName( fs, fnode, "model_params" );
    fnode1 = cvGetFileNodeByName( fs, fnode, "max_depth" );
    if ( !fnode1 )
    {
        ts->printf( CvTS::LOG, "MAX_DEPTH can not be read from config file" );
        return CvTS::FAIL_INVALID_TEST_DATA;
    }
    MAX_DEPTH = fnode1->data.i;
    fnode1 = cvGetFileNodeByName( fs, fnode, "min_sample_count" );
    if ( !fnode1 )
    {
        ts->printf( CvTS::LOG, "MAX_DEPTH can not be read from config file" );
        return CvTS::FAIL_INVALID_TEST_DATA;
    }
    MIN_SAMPLE_COUNT = fnode1->data.i;
    fnode1 = cvGetFileNodeByName( fs, fnode, "use_surrogate" );
    if ( !fnode1 )
    {
        ts->printf( CvTS::LOG, "USE_SURROGATE can not be read from config file" );
        return CvTS::FAIL_INVALID_TEST_DATA;
    }
    USE_SURROGATE = ( fnode1->data.i!= 0);
    fnode1 = cvGetFileNodeByName( fs, fnode, "max_categories" );
    if ( !fnode1 )
    {
        ts->printf( CvTS::LOG, "MAX_CATEGORIES can not be read from config file" );
        return CvTS::FAIL_INVALID_TEST_DATA;
    }
    MAX_CATEGORIES = fnode1->data.i;
    fnode1 = cvGetFileNodeByName( fs, fnode, "cv_folds" );
    if ( !fnode1 )
    {
        ts->printf( CvTS::LOG, "CV_FOLDS can not be read from config file" );
        return CvTS::FAIL_INVALID_TEST_DATA;
    }
    CV_FOLDS = fnode1->data.i;
    fnode1 = cvGetFileNodeByName( fs, fnode, "is_pruned" );
    if ( !fnode1 )
    {
        ts->printf( CvTS::LOG, "IS_PRUNED can not be read from config file" );
        return CvTS::FAIL_INVALID_TEST_DATA;
    }
    IS_PRUNED = (fnode1->data.i != 0);

    
    if ( !tree->train( &data, 
       CvDTreeParams(MAX_DEPTH, MIN_SAMPLE_COUNT, REG_ACCURACY, USE_SURROGATE,
       MAX_CATEGORIES, CV_FOLDS, false, IS_PRUNED, 0 )) )
    {
        ts->printf( CvTS::LOG, "in test case %d model training  was failed", test_case_idx );
        return CvTS::FAIL_INVALID_OUTPUT;
    }
    return CvTS::OK;
}
Esempio n. 25
0
/*
 * Load a  Protocol From yaml File
 *
 */
Protocol* LoadProtocolFromFile(const char* filename){
		Protocol* myP=CreateProtocolObject();
		LoadProtocolWithFilename(filename,myP);
		CvFileStorage* fs=cvOpenFileStorage(myP->Filename,0,CV_STORAGE_READ);
		printf("Opened File: %s for reading\n", myP->Filename);
		/** Point to Protocol Object **/
		CvFileNode* protonode=cvGetFileNodeByName(fs,NULL,"Protocol");

		/** Load in Description **/
		CvFileNode* node=cvGetFileNodeByName(fs,protonode,"Description");
		myP->Description=copyString(cvReadString(node,NULL));
		printf("Loading in Protocol, Description:\n %s\n",myP->Description);

		/** Load in Grid Size **/
		node=cvGetFileNodeByName(fs,protonode,"GridSize");
		int height=cvReadIntByName(fs,node,"height",-1);
		int width=cvReadIntByName(fs,node,"width",-1);
				printf(" width =%d\n",width );
								printf(" height=%d\n",height);
		if (height>0 && width>0){
			myP->GridSize=cvSize(width,height);
		}

		/** Create the Steps Object and Load it into the Protocol **/
		myP->Steps=CreateStepsObject(myP->memory);

		/** Point to the Steps node  in the YAML file **/
		node=cvGetFileNodeByName(fs,protonode,"Steps");



		/** Create a local object that contains the information of the steps **/
		CvSeq* stepSeq=node->data.seq;
		int numsteps=stepSeq->total;
		printf("numsteps=%d\n",numsteps);

		CvSeqReader StepReader;
		cvStartReadSeq( stepSeq, &StepReader, 0 );

		/** Let's loop through all of the steps **/
		for (int i= 0; i< numsteps; ++i) {

			/**Create Illumination Montage Object **/
			CvSeq* montage=CreateIlluminationMontage(myP->memory);

			/** Find the node of the current image montage (step) **/
			CvFileNode* montageNode = (CvFileNode*)StepReader.ptr;

			CvSeq* montageSeq=montageNode->data.seq;
			int numPolygonsInMontage=montageSeq->total;
//			printf("Step %d: %d polygon(s) found\n",i,numPolygonsInMontage);

			CvSeqReader MontageReader;
			cvStartReadSeq( montageSeq, &MontageReader, 0 );

			/** Loop through all of the polygons **/
			for (int k = 0; k < numPolygonsInMontage; ++k) {
				/** Load the CvSeq Polygon Objects and push them onto the montage **/
				CvFileNode* polygonNode = (CvFileNode*)MontageReader.ptr;
				CvSeq* polygonPts =(CvSeq*) cvRead(fs,polygonNode); // <---- Andy come back here.
				printf("\tStep %d, Polygon %d: %d points found.\n",i,k,polygonPts->total);

				/**
				 * Now we have the points for our polygon so we need to load
				 * those points into a polygon object
				 */
				WormPolygon* polygon= CreateWormPolygonFromSeq(myP->memory,myP->GridSize,polygonPts);
				//printf("\t\t %d points copied\n",polygon->Points->total);

				/** Add the polygon to the montage **/
				cvSeqPush(montage,&polygon);
				//printf("\t\t Current montage now has %d polygons\n",montage->total);

				/** Move to the next polygon **/
				CV_NEXT_SEQ_ELEM( montageSeq->elem_size, MontageReader );
			}
			cvClearSeq(montageSeq);
			numPolygonsInMontage=0;

			//printf("Loading a montage with %d polygons on the protocol\n.",montage->total);
			/** Load the montage onto the step object**/
			cvSeqPush(myP->Steps,&montage);

			/** Progress to the next step **/
			CV_NEXT_SEQ_ELEM( stepSeq->elem_size, StepReader );

		}

		return myP;

}
Esempio n. 26
0
const CvFileNode* BaseTest::find_param( CvFileStorage* fs, const char* param_name )
{
    CvFileNode* node = cvGetFileNodeByName(fs, 0, get_name().c_str());
    return node ? cvGetFileNodeByName( fs, node, param_name ) : 0;
}
Esempio n. 27
0
void GazeTracker::load(CvFileStorage *in, CvFileNode *node) {
	_calTargets = Utils::loadVector<CalTarget>(in, cvGetFileNodeByName(in, node, "calTargets"));
}
Esempio n. 28
0
static CvTestSeqElem* icvTestSeqReadElemAll(CvTestSeq_* pTS, CvFileStorage* fs, const char* name)
{
    CvTestSeqElem*  pElem = NULL;
    CvFileNode*     node;

    if(name == NULL) return NULL;

    node = cvGetFileNodeByName( fs, NULL, name );

    if(node == NULL)
    {
        printf("WARNING!!! - Video %s does not exist!\n", name);
        return NULL;
    }

    printf("Read node %s\n",name);

    if(CV_NODE_IS_SEQ(node->tag))
    {   /* Read all element in sequence: */
        int             i;
        CvSeq*          seq = node->data.seq;
        CvTestSeqElem*  pElemLast = NULL;

        for(i=0; i<seq->total; ++i)
        {
            CvFileNode*     next_node = (CvFileNode*)cvGetSeqElem( seq, i );
            CvTestSeqElem*  pElemNew = icvTestSeqReadElemOne(pTS, fs, next_node );
            CvFileNode*     pDurNode = cvGetFileNodeByName( fs, next_node,"Dur");

            if(pElemNew == NULL )
            {
                printf("WARNING in parsing %s record!!! Cannot read array element\n", name);
                continue;
            }

            if(pElem && pElemLast)
            {
                pElemLast->next = pElemNew;
                if(pDurNode)
                {
                    pElemNew->FrameBegin = pElemLast->FrameBegin + pElemLast->FrameNum;
                }
            }
            else
            {
                pElem = pElemNew;
            }

            /* Find last element: */
            for(pElemLast=pElemNew;pElemLast && pElemLast->next;pElemLast= pElemLast->next);

        }   /* Next element. */
    }   /*  Read all element in sequence. */
    else
    {   /* Read one element: */
        pElem = icvTestSeqReadElemOne(pTS, fs, node );
    }

    return pElem;

}   /* icvTestSeqReadElemAll */
int
main (int argc, char *argv[])
{
	// IMAGE_NUM, PAT_ROW, PAT_COL,PAT_SIZE, ALL_POINTS, CHESS_SIZE

	/*
	if (argc < 6)
	{
		std::cout<< "ERROR : augment is incorrect" << std::endl;
		return -1;
	}
	*/

	//int PAT_ROW   	= atoi(argv[3]);
	//int PAT_COL   	= atoi(argv[4]);
	//int CHESS_SIZE	= atoi(argv[5]);
	//int PAT_SIZE = PAT_ROW*PAT_COL;
	char* NAME_IMG_IN		= argv[1];
	//char* NAME_XML_OUT	= argv[2];

	int i,j;
	int corner_count, found;
	IplImage *src_img;
	CvSize pattern_size = cvSize(PAT_COL, PAT_ROW);
	CvMat image_points;
	CvMat object_points;
	CvMat *intrinsic, *distortion;
	CvMat *rotation = cvCreateMat(1, 3, CV_32FC1);
	CvMat *rotationConv = cvCreateMat(3, 3, CV_32FC1);
	CvMat *translation = cvCreateMat(1, 3, CV_32FC1);
	CvPoint3D32f objects[PAT_SIZE];
	CvFileStorage *fs;
	CvFileNode *param;
	CvPoint2D32f *corners = (CvPoint2D32f *) cvAlloc (sizeof (CvPoint2D32f) * PAT_SIZE);

	// (1)�����оݤȤʤ������ɤ߹���
	if ( ( src_img = cvLoadImage(NAME_IMG_IN, CV_LOAD_IMAGE_COLOR) ) == 0)
	//if (argc < 2 || (src_img = cvLoadImage (argv[1], CV_LOAD_IMAGE_COLOR)) == 0)
	{
		std::cout<< "ERROR : input image is not exist  or  augment is incorrect" << std::endl;
		return -1;
	}

	// 3�������ֺ�ɸ������
	for (i = 0; i < PAT_ROW; i++) {
		for (j = 0; j < PAT_COL; j++) {
			objects[i * PAT_COL + j].x = i * CHESS_SIZE;
			objects[i * PAT_COL + j].y = j * CHESS_SIZE;
			objects[i * PAT_COL + j].z = 0.0;
		}
	}
	cvInitMatHeader(&object_points, PAT_SIZE, 3, CV_32FC1, objects);

	// �������ܡ��ɡʥ����֥졼�����ѥ�����ˤΥ����ʡ�����
	int found_num = 0;
//	cvNamedWindow("Calibration", CV_WINDOW_AUTOSIZE);
	found = cvFindChessboardCorners(src_img, pattern_size, &corners[0], &corner_count);
	fprintf(stderr, "corner:%02d...\n", corner_count);
	if (found) {
		fprintf(stderr, "ok\n");
	} else {
		fprintf(stderr, "fail\n");
	}

	// (4)�����ʡ����֤򥵥֥ԥ��������٤˽���������
	IplImage *src_gray = cvCreateImage (cvGetSize (src_img), IPL_DEPTH_8U, 1);
	cvCvtColor (src_img, src_gray, CV_BGR2GRAY);
	cvFindCornerSubPix (src_gray, &corners[0], corner_count,
			cvSize (3, 3), cvSize (-1, -1), cvTermCriteria (CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 20, 0.03));
	cvDrawChessboardCorners (src_img, pattern_size, &corners[0], corner_count, found);

//	cvShowImage ("Calibration", src_img);
//	cvWaitKey (0);
//	cvDestroyWindow("Calibration");
	cvShowImage ("Calibration", src_img);

	cvInitMatHeader(&image_points, PAT_SIZE, 1, CV_32FC2, corners);


	// (2)�ѥ�᡼���ե�������ɤ߹���
	fs = cvOpenFileStorage ("xml/rgb.xml", 0, CV_STORAGE_READ);
	param = cvGetFileNodeByName (fs, NULL, "intrinsic");
	intrinsic = (CvMat *) cvRead (fs, param);
	param = cvGetFileNodeByName (fs, NULL, "distortion");
	distortion = (CvMat *) cvRead (fs, param);
	cvReleaseFileStorage (&fs);

	// (3) �����ѥ�᡼���ο���
	CvMat sub_image_points, sub_object_points;
	int base = 0;
	cvGetRows(&image_points, &sub_image_points, base * PAT_SIZE, (base + 1) * PAT_SIZE);
	cvGetRows(&object_points, &sub_object_points, base * PAT_SIZE, (base + 1)* PAT_SIZE);
	cvFindExtrinsicCameraParams2(&sub_object_points, &sub_image_points, intrinsic, distortion, rotation, translation);
	int ret = cvRodrigues2(rotation, rotationConv);

//	int cols = sub_object_points.rows;
//	printf("cols = %d\n", cols);
//	printf("%f\n",sub_object_points.data.fl[0]);

	// mm -> m
	for (i = 0; i < translation->cols; i++) { translation->data.fl[i] = translation->data.fl[i] / 1000;}

	// (4)XML�ե�����ؤν񤭽Ф�
	//fs = cvOpenFileStorage(argv[2], 0, CV_STORAGE_WRITE);
	fs = cvOpenFileStorage(NAME_XML_OUT, 0, CV_STORAGE_WRITE);
	cvWrite(fs, "rotation", rotationConv);
	cvWrite(fs, "translation", translation);
	cvReleaseFileStorage(&fs);

	/////////////////////////////////////////////////
	// write out py
	if(1)
	{
		cv::Mat ttt(translation);
		cv::Mat rrr(rotationConv);


		char data2Write[1024];
		char textFileName[256];
		sprintf( textFileName , "cbCoord/cbOneShot.py");
		std::ofstream outPy(textFileName);

		outPy << "import sys"						<<std::endl;
		outPy << "sys.path.append('../')"			<<std::endl;
		outPy << "from numpy import *"				<<std::endl;
		outPy << "from numpy.linalg import svd"	<<std::endl;
		outPy << "from numpy.linalg import inv"	<<std::endl;
		outPy << "from chessboard_points import *"<<std::endl;
		outPy << "sys.path.append('../geo')"		<<std::endl;
		outPy << "from geo import *"				<<std::endl;

		/*
		///////////////////////////////////////////////////////////////////////////////////
		// out translation and rotation as xyzabc list
		outPy << "xyzabc = []"	<<std::endl;

		sprintf( data2Write, "xyzabc.append(%f)", ttt.at<float>(0) );
		outPy << data2Write << std::endl;
		std::cout << data2Write << std::endl;

		sprintf( data2Write, "xyzabc.append(%f)", ttt.at<float>(1) );
		outPy << data2Write << std::endl;
		std::cout << data2Write << std::endl;

		sprintf( data2Write, "xyzabc.append(%f)", ttt.at<float>(2) );
		outPy << data2Write << std::endl;
		std::cout << data2Write << std::endl;

		sprintf( data2Write, "xyzabc.append(%f)", rrr.at<float>(0) );
		outPy << data2Write << std::endl;
		std::cout << data2Write << std::endl;

		sprintf( data2Write, "xyzabc.append(%f)", rrr.at<float>(1) );
		outPy << data2Write << std::endl;
		std::cout << data2Write << std::endl;

		sprintf( data2Write, "xyzabc.append(%f)", rrr.at<float>(2) );
		outPy << data2Write << std::endl;
		std::cout << data2Write << std::endl;
		// out translation and rotation as xyzabc list
		///////////////////////////////////////////////////////////////////////////////////
		 */

		///////////////////////////////////////////////////////////////////////////////////
		// out translation
		outPy << "ttt = []"	<<std::endl;

		sprintf( data2Write, "ttt.append(%f)", ttt.at<float>(0) );
		outPy << data2Write << std::endl;
		std::cout << data2Write << std::endl;

		sprintf( data2Write, "ttt.append(%f)", ttt.at<float>(1) );
		outPy << data2Write << std::endl;
		std::cout << data2Write << std::endl;

		sprintf( data2Write, "ttt.append(%f)", ttt.at<float>(2) );
		outPy << data2Write << std::endl;
		std::cout << data2Write << std::endl;
		// out translation
		//////////////////////////////////////////////////////////////////////////////////////

		///////////////////////////////////////////////////////////////////////////////////
		// out rotation
		outPy << "rrr = []"	<<std::endl;

		sprintf( data2Write, "rrr.append([%f,%f,%f])", rrr.at<float>(0), rrr.at<float>(1), rrr.at<float>(2) );
		outPy << data2Write << std::endl;
		std::cout << data2Write << std::endl;

		sprintf( data2Write, "rrr.append([%f,%f,%f])", rrr.at<float>(3), rrr.at<float>(4), rrr.at<float>(5) );
		outPy << data2Write << std::endl;
		std::cout << data2Write << std::endl;

		sprintf( data2Write, "rrr.append([%f,%f,%f])", rrr.at<float>(6), rrr.at<float>(7), rrr.at<float>(8) );
		outPy << data2Write << std::endl;
		std::cout << data2Write << std::endl;
		// out rotation
		//////////////////////////////////////////////////////////////////////////////////////

	
		/////////////////////////////////////////////////////////////////
		outPy<< "_T = FRAME( vec=ttt, mat=rrr )" << std::endl;
		/////////////////////////////////////////////////////////////////

	}
	// write out py
	/////////////////////////////////////////////////
	
	std::cout<< "press any key..."<< std::endl;
	cvWaitKey (0);
	cvDestroyWindow("Calibration");


	cvReleaseImage(&src_img);
	cvReleaseMat(&intrinsic);
	cvReleaseMat(&distortion);

	return 0;
}
Esempio n. 30
0
static CvTestSeqElem* icvTestSeqReadElemOne(CvTestSeq_* pTS, CvFileStorage* fs, CvFileNode* node)
{
    int             noise_type = CV_NOISE_NONE;;
    CvTestSeqElem*  pElem = NULL;
    const char*     pVideoName = cvReadStringByName( fs, node,"Video", NULL);
    const char*     pVideoObjName = cvReadStringByName( fs, node,"VideoObj", NULL);

    if(pVideoName)
    {   /* Check to noise flag: */
        if( cv_stricmp(pVideoName,"noise_gaussian") == 0 ||
            cv_stricmp(pVideoName,"noise_normal") == 0) noise_type = CV_NOISE_GAUSSIAN;
        if( cv_stricmp(pVideoName,"noise_uniform") == 0) noise_type = CV_NOISE_UNIFORM;
        if( cv_stricmp(pVideoName,"noise_speckle") == 0) noise_type = CV_NOISE_SPECKLE;
        if( cv_stricmp(pVideoName,"noise_salt_and_pepper") == 0) noise_type = CV_NOISE_SALT_AND_PEPPER;
    }

    if((pVideoName || pVideoObjName ) && noise_type == CV_NOISE_NONE)
    {   /* Read other elements: */
        if(pVideoName) pElem = icvTestSeqReadElemAll(pTS, fs, pVideoName);
        if(pVideoObjName)
        {
            CvTestSeqElem* pE;
            pElem = icvTestSeqReadElemAll(pTS, fs, pVideoObjName);
            for(pE=pElem;pE;pE=pE->next)
            {
                pE->ObjID = pTS->ObjNum;
                pE->pObjName = pVideoObjName;
            }
            pTS->ObjNum++;
        }
    }   /* Read other elements. */
    else
    {   /* Create new element: */
        CvFileNode* pPosNode = cvGetFileNodeByName( fs, node,"Pos");
        CvFileNode* pSizeNode = cvGetFileNodeByName( fs, node,"Size");
        int AutoSize = (pSizeNode && CV_NODE_IS_STRING(pSizeNode->tag) && cv_stricmp("auto",cvReadString(pSizeNode,""))==0);
        int AutoPos = (pPosNode && CV_NODE_IS_STRING(pPosNode->tag) && cv_stricmp("auto",cvReadString(pPosNode,""))==0);
        const char* pFileName = cvReadStringByName( fs, node,"File", NULL);
        pElem = (CvTestSeqElem*)cvAlloc(sizeof(CvTestSeqElem));
        memset(pElem,0,sizeof(CvTestSeqElem));

        pElem->ObjID = -1;
        pElem->noise_type = noise_type;
        cvRandInit( &pElem->rnd_state, 1, 0, 0,CV_RAND_NORMAL);

        if(pFileName && pElem->noise_type == CV_NOISE_NONE)
        {   /* If AVI or BMP: */
            size_t  l = strlen(pFileName);
            pElem->pFileName = pFileName;

            pElem->type = SRC_TYPE_IMAGE;
            if(cv_stricmp(".avi",pFileName+l-4) == 0)pElem->type = SRC_TYPE_AVI;

            if(pElem->type == SRC_TYPE_IMAGE)
            {
                //pElem->pImg = cvLoadImage(pFileName);
                if(pElem->pImg)
                {
                    pElem->FrameNum = 1;
                    if(pElem->pImgMask)cvReleaseImage(&(pElem->pImgMask));

                    pElem->pImgMask = cvCreateImage(
                        cvSize(pElem->pImg->width,pElem->pImg->height),
                        IPL_DEPTH_8U,1);
                    icvTestSeqCreateMask(pElem->pImg,pElem->pImgMask,FG_BG_THRESHOLD);
                }
            }

            if(pElem->type == SRC_TYPE_AVI && pFileName)
            {
                //pElem->pAVI = cvCaptureFromFile(pFileName);

                if(pElem->pAVI)
                {
                    IplImage* pImg = 0;//cvQueryFrame(pElem->pAVI);
                    pElem->pImg = cvCloneImage(pImg);
                    pElem->pImg->origin = 0;
                    //cvSetCaptureProperty(pElem->pAVI,CV_CAP_PROP_POS_FRAMES,0);
                    pElem->FrameBegin = 0;
                    pElem->AVILen = pElem->FrameNum = 0;//(int)cvGetCaptureProperty(pElem->pAVI, CV_CAP_PROP_FRAME_COUNT);
                    //cvReleaseCapture(&pElem->pAVI);
                    pElem->pAVI = NULL;
                }
                else
                {
                    printf("WARNING!!! Cannot open avi file %s\n",pFileName);
                }
            }

        }   /* If AVI or BMP. */

        if(pPosNode)
        {   /* Read positions: */
            if(CV_NODE_IS_SEQ(pPosNode->tag))
            {
                int num = pPosNode->data.seq->total;
                pElem->pPos = (CvPoint2D32f*)cvAlloc(sizeof(float)*num);
                cvReadRawData( fs, pPosNode, pElem->pPos, "f" );
                pElem->PosNum = num/2;
                if(pElem->FrameNum == 0) pElem->FrameNum = pElem->PosNum;
            }
        }

        if(pSizeNode)
        {   /* Read sizes: */
            if(CV_NODE_IS_SEQ(pSizeNode->tag))
            {
                int num = pSizeNode->data.seq->total;
                pElem->pSize = (CvPoint2D32f*)cvAlloc(sizeof(float)*num);
                cvReadRawData( fs, pSizeNode, pElem->pSize, "f" );
                pElem->SizeNum = num/2;
            }
        }

        if(AutoPos || AutoSize)
        {   /* Auto size and pos: */
            int     i;
            int     num = (pElem->type == SRC_TYPE_AVI)?pElem->AVILen:1;
            if(AutoSize)
            {
                pElem->pSize = (CvPoint2D32f*)cvAlloc(sizeof(CvPoint2D32f)*num);
                pElem->SizeNum = num;
            }
            if(AutoPos)
            {
                pElem->pPos = (CvPoint2D32f*)cvAlloc(sizeof(CvPoint2D32f)*num);
                pElem->PosNum = num;
            }

            for(i=0; i<num; ++i)
            {
                IplImage* pFG = NULL;
                CvPoint2D32f* pPos = AutoPos?(pElem->pPos + i):NULL;
                CvPoint2D32f* pSize = AutoSize?(pElem->pSize + i):NULL;

                icvTestSeqQureyFrameElem(pElem,i);
                pFG = pElem->pImgMask;

                if(pPos)
                {
                    pPos->x = 0.5f;
                    pPos->y = 0.5f;
                }
                if(pSize)
                {
                    pSize->x = 0;
                    pSize->y = 0;
                }

                if(pFG)
                {
                    double      M00;
                    CvMoments   m;
                    cvMoments( pElem->pImgMask, &m, 0 );
                    M00 = cvGetSpatialMoment( &m, 0, 0 );

                    if(M00 > 0 && pSize )
                    {
                        double X = cvGetSpatialMoment( &m, 1, 0 )/M00;
                        double Y = cvGetSpatialMoment( &m, 0, 1 )/M00;
                        double XX = (cvGetSpatialMoment( &m, 2, 0 )/M00) - X*X;
                        double YY = (cvGetSpatialMoment( &m, 0, 2 )/M00) - Y*Y;
                        pSize->x = (float)(4*sqrt(XX))/(pElem->pImgMask->width-1);
                        pSize->y = (float)(4*sqrt(YY))/(pElem->pImgMask->height-1);
                    }

                    if(M00 > 0 && pPos)
                    {
                        pPos->x = (float)(cvGetSpatialMoment( &m, 1, 0 )/(M00*(pElem->pImgMask->width-1)));
                        pPos->y = (float)(cvGetSpatialMoment( &m, 0, 1 )/(M00*(pElem->pImgMask->height-1)));
                    }

                    if(pPos)
                    {   /* Another way to calculate y pos
                         * using object median:
                         */
                        int y0=0, y1=pFG->height-1;
                        for(y0=0; y0<pFG->height; ++y0)
                        {
                            CvMat       m;
                            CvScalar    s = cvSum(cvGetRow(pFG, &m, y0));
                            if(s.val[0] > 255*7) break;
                        }

                        for(y1=pFG->height-1; y1>0; --y1)
                        {
                            CvMat m;
                            CvScalar s = cvSum(cvGetRow(pFG, &m, y1));
                            if(s.val[0] > 255*7) break;
                        }

                        pPos->y = (y0+y1)*0.5f/(pFG->height-1);
                    }
                }   /* pFG */
            }   /* Next frame. */

            //if(pElem->pAVI) cvReleaseCapture(&pElem->pAVI);

            pElem->pAVI = NULL;

        }   /* End auto position creation. */
    }   /*  Create new element. */

    if(pElem)
    {   /* Read transforms and: */
        int             FirstFrame, LastFrame;
        CvTestSeqElem*  p=pElem;
        CvFileNode*     pTransNode = NULL;
        CvFileNode*     pS = NULL;
        int             ShiftByPos = 0;
        int             KeyFrames[1024];
        CvSeq*          pTransSeq = NULL;
        int             KeyFrameNum = 0;

        pTransNode = cvGetFileNodeByName( fs, node,"Trans");

        while( pTransNode &&
               CV_NODE_IS_STRING(pTransNode->tag) &&
               cv_stricmp("auto",cvReadString(pTransNode,""))!=0)
        {   /* Trans is reference: */
            pTransNode = cvGetFileNodeByName( fs, NULL,cvReadString(pTransNode,""));
        }

        pS = cvGetFileNodeByName( fs, node,"Shift");
        ShiftByPos = 0;
        pTransSeq = pTransNode?(CV_NODE_IS_SEQ(pTransNode->tag)?pTransNode->data.seq:NULL):NULL;
        KeyFrameNum = pTransSeq?pTransSeq->total:1;

        if(   (pS && CV_NODE_IS_STRING(pS->tag) && cv_stricmp("auto",cvReadString(pS,""))==0)
            ||(pTransNode && CV_NODE_IS_STRING(pTransNode->tag) && cv_stricmp("auto",cvReadString(pTransNode,""))==0))
        {
            ShiftByPos = 1;
        }

        FirstFrame = pElem->FrameBegin;
        LastFrame = pElem->FrameBegin+pElem->FrameNum-1;

        /* Calculate length of video and reallocate
         * transformation array:
         */
        for(p=pElem; p; p=p->next)
        {
            int v;
            v = cvReadIntByName( fs, node, "BG", -1 );
            if(v!=-1)p->BG = v;
            v = cvReadIntByName( fs, node, "Mask", -1 );
            if(v!=-1)p->Mask = v;

            p->FrameBegin += cvReadIntByName( fs, node, "FrameBegin", 0 );
            p->FrameNum = cvReadIntByName( fs, node, "FrameNum", p->FrameNum );
            p->FrameNum = cvReadIntByName( fs, node, "Dur", p->FrameNum );
            {
                int LastFrame = cvReadIntByName( fs, node, "LastFrame", p->FrameBegin+p->FrameNum-1 );
                p->FrameNum = MIN(p->FrameNum,LastFrame - p->FrameBegin+1);
            }

            icvTestSeqAllocTrans(p);

            {   /* New range estimation: */
                int LF = p->FrameBegin+p->FrameNum-1;
                if(p==pElem || FirstFrame > p->FrameBegin)FirstFrame = p->FrameBegin;
                if(p==pElem || LastFrame < LF)LastFrame = LF;
            }   /* New range estimation. */
        }   /*  End allocate new transfrom array. */

        if(ShiftByPos)
        {
            for(p=pElem;p;p=p->next)
            {   /* Modify transformation to make autoshift: */
                int         i;
                int         num = p->FrameNum;
                assert(num <= p->TransNum);
                p->TransNum = MAX(1,num);

                for(i=0; i<num; ++i)
                {
                    CvTSTrans*  pT = p->pTrans+i;
                    //float   t = (num>1)?((float)i/(num-1)):0.0f;
                    float newx = p->pPos[i%p->PosNum].x;
                    float newy = p->pPos[i%p->PosNum].y;
                    pT->Shift.x = -newx*pT->Scale.x;
                    pT->Shift.y = -newy*pT->Scale.y;

                    if(p->pImg)
                    {
                        newx *= p->pImg->width-1;
                        newy *= p->pImg->height-1;
                    }

                    pT->T[2] = -(pT->T[0]*newx+pT->T[1]*newy);
                    pT->T[5] = -(pT->T[3]*newx+pT->T[4]*newy);
                }
            }   /* Modify transformation old. */
        }   /*  Next record. */

        /* Initialize frame number array: */
        KeyFrames[0] = FirstFrame;

        if(pTransSeq&&KeyFrameNum>1)
        {
            int i0,i1,i;
            for(i=0; i<KeyFrameNum; ++i)
            {
                CvFileNode* pTN = (CvFileNode*)cvGetSeqElem(pTransSeq,i);
                KeyFrames[i] = cvReadIntByName(fs,pTN,"frame",-1);
            }

            if(KeyFrames[0]<0)KeyFrames[0]=FirstFrame;
            if(KeyFrames[KeyFrameNum-1]<0)KeyFrames[KeyFrameNum-1]=LastFrame;

            for(i0=0, i1=1; i1<KeyFrameNum;)
            {
                int i;

                for(i1=i0+1; i1<KeyFrameNum && KeyFrames[i1]<0; i1++);

                assert(i1<KeyFrameNum);
                assert(i1>i0);

                for(i=i0+1; i<i1; ++i)
                {
                    KeyFrames[i] = cvRound(KeyFrames[i0] + (float)(i-i0)*(float)(KeyFrames[i1] - KeyFrames[i0])/(float)(i1-i0));
                }
                i0 = i1;
                i1++;
            }   /* Next key run. */
        }   /*  Initialize frame number array. */

        if(pTransNode || pTransSeq)
        {   /* More complex transform. */
            int     param;
            CvFileNode* pTN = pTransSeq?(CvFileNode*)cvGetSeqElem(pTransSeq,0):pTransNode;

            for(p=pElem; p; p=p->next)
            {
                //int trans_num = p->TransNum;
                for(param=0; param_name[param]; ++param)
                {
                    const char*   name = param_name[param];
                    float   defv = param_defval[param];
                    if(KeyFrameNum==1)
                    {   /* Only one transform record: */
                        int     i;
                        double  val;
                        CvFileNode* node = cvGetFileNodeByName( fs, pTN,name);
                        if(node == NULL) continue;
                        val = cvReadReal(node,defv);

                        for(i=0; i<p->TransNum; ++i)
                        {
                            icvUpdateTrans(
                                p->pTrans+i, param, val,
                                p->pImg?(float)(p->pImg->width-1):1.0f,
                                p->pImg?(float)(p->pImg->height-1):1.0f);
                        }
                    }   /* Next record. */
                    else
                    {   /* Several transforms: */
                        int         i0,i1;
                        double      v0;
                        double      v1;

                        CvFileNode* pTN = (CvFileNode*)cvGetSeqElem(pTransSeq,0);
                        v0 = cvReadRealByName(fs, pTN,name,defv);

                        for(i1=1,i0=0; i1<KeyFrameNum; ++i1)
                        {
                            int         f0,f1;
                            int         i;
                            CvFileNode* pTN = (CvFileNode*)cvGetSeqElem(pTransSeq,i1);
                            CvFileNode* pVN = cvGetFileNodeByName(fs,pTN,name);

                            if(pVN)v1 = cvReadReal(pVN,defv);
                            else if(pVN == NULL && i1 == KeyFrameNum-1) v1 = defv;
                            else continue;

                            f0 = KeyFrames[i0];
                            f1 = KeyFrames[i1];

                            if(i1==(KeyFrameNum-1)) f1++;

                            for(i=f0; i<f1; ++i)
                            {
                                double   val;
                                double   t = (float)(i-f0);
                                int      li = i - p->FrameBegin;
                                if(li<0) continue;
                                if(li>= p->TransNum) break;
                                if(KeyFrames[i1]>KeyFrames[i0]) t /=(float)(KeyFrames[i1]-KeyFrames[i0]);
                                val = t*(v1-v0)+v0;

                                icvUpdateTrans(
                                    p->pTrans+li, param, val,
                                    p->pImg?(float)(p->pImg->width-1):1.0f,
                                    p->pImg?(float)(p->pImg->height-1):1.0f);

                            }   /* Next transform. */
                            i0 = i1;
                            v0 = v1;

                        }   /* Next value run. */
                    }   /*  Several transforms. */
                }   /*  Next parameter. */
            }   /*  Next record. */
        }   /*  More complex transform. */
    }   /*  Read transfroms. */

    return pElem;

}   /* icvTestSeqReadElemOne */