Esempio n. 1
0
void CalTarget::save(CvFileStorage *out, const char *name) {
	cvStartWriteStruct(out, name, CV_NODE_MAP);
	point.save(out, "point");
	cvWrite(out, "image", image.get());
	cvWrite(out, "origImage", origImage.get());
	cvEndWriteStruct(out);
}
Esempio n. 2
0
void SaveFeature(
		FEATURE* 	feature,
		char* 		fileName){
	CvFileStorage* fs = cvOpenFileStorage( fileName, 0, CV_STORAGE_WRITE, NULL);
	if (fs==NULL){
		fprintf(stderr, "can't open feature file\n");
		return;
	}
	cvWriteInt(fs, "radius", feature->radius);
	cvWriteInt(fs, "neighbors", feature->neighbors);
	cvWriteInt(fs, "grid_x", feature->grid_x);
	cvWriteInt(fs, "grid_y", feature->grid_y);
	cvWriteInt(fs, "num_faces", feature->num_faces);

	char faceid[1024];
	char id[1024];

	for (int i=0; i<feature->num_faces; i++){
		strcpy(faceid, "face-");
		sprintf(id, "%d", i);
		strcat(faceid, id);
		cvWrite( fs, faceid, feature->histogram[i], cvAttrList(0,0) );
	}
	if (HUELBP_ON){
		for (int i=0; i<feature->num_faces; i++){
			strcpy(faceid, "hue-face-");
			sprintf(id, "%d", i);
			strcat(faceid, id);
			cvWrite( fs, faceid, feature->hue_histogram[i], cvAttrList(0,0) );
		}
	}
	cvReleaseFileStorage( &fs );
}
// Save the training data to the file 'facedata.xml'.
void storeTrainingData()
{
    CvFileStorage * fileStorage;
    int i;
    
    // create a file-storage interface

    fileStorage = cvOpenFileStorage( facedata, 0, CV_STORAGE_WRITE );    
    // Store the person names. Added by Shervin.
    cvWriteInt( fileStorage, "nPersons", nPersons );
    for (i=0; i<nPersons; i++) {
        char varname[200];
        sprintf( varname, "personName_%d", (i+1) );
        cvWriteString(fileStorage, varname, personNames[i].c_str(), 0);
    }
    
    // store all the data
    cvWriteInt( fileStorage, "nEigens", nEigens );
    cvWriteInt( fileStorage, "nTrainFaces", nTrainFaces );
    cvWrite(fileStorage, "trainPersonNumMat", personNumTruthMat, cvAttrList(0,0));
    cvWrite(fileStorage, "eigenValMat", eigenValMat, cvAttrList(0,0));
    cvWrite(fileStorage, "projectedTrainFaceMat", projectedTrainFaceMat, cvAttrList(0,0));
    cvWrite(fileStorage, "avgTrainImg", pAvgTrainImg, cvAttrList(0,0));
    for(i=0; i<nEigens; i++)
    {
        char varname[200];
        sprintf( varname, "eigenVect_%d", i );
        cvWrite(fileStorage, varname, eigenVectArr[i], cvAttrList(0,0));
    }
    
    // release the file-storage interface
    cvReleaseFileStorage( &fileStorage );
}
Esempio n. 4
0
//存储训练结果
void storeTrainingData()
{
	CvFileStorage * fileStorage;
	int i;

	
	fileStorage = cvOpenFileStorage( "facedata.xml", 0, CV_STORAGE_WRITE );

	//存储特征值,投影矩阵,平均矩阵等训练结果
	cvWriteInt( fileStorage, "nEigens", nEigens );
	cvWriteInt( fileStorage, "nTrainFaces", nTrainFaces );
	cvWrite(fileStorage, "trainPersonNumMat", personNumTruthMat, cvAttrList(0,0));
	cvWrite(fileStorage, "eigenValMat", eigenValMat, cvAttrList(0,0));
	cvWrite(fileStorage, "projectedTrainFaceMat", projectedTrainFaceMat, cvAttrList(0,0));
	cvWrite(fileStorage, "avgTrainImg", pAvgTrainImg, cvAttrList(0,0));
	for(i=0; i<nEigens; i++)
	{
		char varname[200];
		sprintf( varname, "eigenVect_%d", i );
		cvWrite(fileStorage, varname, eigenVectArr[i], cvAttrList(0,0));
	}


	cvReleaseFileStorage( &fileStorage );
}
Esempio n. 5
0
bool ObjectDefinition::Save(const char* filename)
{
	do{
		CvFileStorage* storage = cvOpenFileStorage(filename, 0, CV_STORAGE_WRITE);
		cvWrite(storage, "keypoints", m_keypoints);
		cvWrite(storage, "descriptor", m_descriptor);
		cvStartWriteStruct(storage, "corners", CV_NODE_SEQ, NULL, cvAttrList(0,0));
		cvWriteRawData(storage, m_corners, 4, "ii");
		cvEndWriteStruct(storage);
		cvReleaseFileStorage(&storage);
		m_filename = filename; 
		return true;
	}while(false);
	return false;
}
Esempio n. 6
0
void CvGBTrees::write_params( CvFileStorage* fs ) const
{
    const char* loss_function_type_str =
        params.loss_function_type == SQUARED_LOSS ? "SquaredLoss" :
        params.loss_function_type == ABSOLUTE_LOSS ? "AbsoluteLoss" :
        params.loss_function_type == HUBER_LOSS ? "HuberLoss" :
        params.loss_function_type == DEVIANCE_LOSS ? "DevianceLoss" : 0;


    if( loss_function_type_str )
        cvWriteString( fs, "loss_function", loss_function_type_str );
    else
        cvWriteInt( fs, "loss_function", params.loss_function_type );

    cvWriteInt( fs, "ensemble_length", params.weak_count );
    cvWriteReal( fs, "shrinkage", params.shrinkage );
    cvWriteReal( fs, "subsample_portion", params.subsample_portion );
    //cvWriteInt( fs, "max_tree_depth", params.max_depth );
    //cvWriteString( fs, "use_surrogate_splits", params.use_surrogates ? "true" : "false");
    if (class_labels) cvWrite( fs, "class_labels", class_labels);

    data->is_classifier = !problem_type();
    data->write_params( fs );
    data->is_classifier = 0;
}
Esempio n. 7
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. 8
0
bool CameraParameters::saveParameters(const char* filename){

    CvFileStorage* fstorage = 0;
    fstorage = cvOpenFileStorage(filename, NULL, CV_STORAGE_WRITE);

    if(!fstorage)
        return false;

    cvWrite(fstorage, CAMERA_MATRIX_TAG, m_mat_camera_matrix);
    cvWrite(fstorage, DISTORTION_COEF_TAG, m_mat_distortion_coeff);

    cvReleaseFileStorage(&fstorage);

    return true;

}
Esempio n. 9
0
void save_posture_model (CvFileStorage *fs, CvMat *mean, CvMat *cov)
{
	static int i=0;
	static char asd[]="posture-00";
	
	cvStartWriteStruct(fs, asd, CV_NODE_MAP, NULL, cvAttrList(0,0));
	cvWriteInt(fs, "type", i++);
	cvWrite(fs, "mean", (void*)mean, cvAttrList(0,0));
	cvWrite(fs, "cov", (void*)cov, cvAttrList(0,0));
	cvEndWriteStruct(fs);

	if (++asd[9] == ':') {
		asd[9] = '0';
		asd[8]++;
	}
		
}
Esempio n. 10
0
void save_sequence (const char *file, ptseq seq, int N)
{
	CvFileStorage *fs;

	fs = cvOpenFileStorage(file, NULL, CV_STORAGE_WRITE, NULL);
	cvWriteInt(fs, "N", N);
	cvWrite(fs, "seq", seq.ptr, cvAttrList(0,0));
	cvReleaseFileStorage(&fs);
}
Esempio n. 11
0
/**
 * Write out a Protocol to YAML file, given an initialized CvFileStorage
 */
void WriteProtocol(Protocol* myP, CvFileStorage* fs){
	if (fs==0){
		printf("fs is zero! Could you have specified the wrong directory?\n");
		return;
	}
	/** Write out Protocol **/
	cvStartWriteStruct(fs,"Protocol",CV_NODE_MAP,NULL);
		if (myP->Filename!=NULL) cvWriteString(fs,"Filename",myP->Filename);
		if (myP->Description!=NULL)  cvWriteString(fs,"Description",myP->Description);
		cvStartWriteStruct(fs,"GridSize",CV_NODE_MAP,NULL);
			cvWriteInt(fs,"height",myP->GridSize.height);
			cvWriteInt(fs,"width",myP->GridSize.width);
		cvEndWriteStruct(fs);
		//printf("yo\n");
		/** Write Out Steps **/
		cvStartWriteStruct(fs,"Steps",CV_NODE_SEQ,NULL);
		int j;
		int jtot=myP->Steps->total;


		CvSeqReader StepReader;
		cvStartReadSeq(myP->Steps,&StepReader,0);
		for (j = 0; j < jtot; ++j) {
			//printf("About to write step number %d\n",j);
			CvSeq** CurrentMontagePtr = (CvSeq**) StepReader.ptr;
			CvSeq* CurrentMontage=*CurrentMontagePtr;
			assert(CurrentMontage!=NULL);
		//	printf("ping\n");
		//	printf("CurrentMontage->total=%d",CurrentMontage->total);
			cvStartWriteStruct(fs,NULL,CV_NODE_SEQ,NULL);
			int k;
			int ktot=CurrentMontage->total;
		//	printf("ktot=%d\n",ktot);

			CvSeqReader MontageReader;
			cvStartReadSeq(CurrentMontage,&MontageReader);
			for (k = 0; k < ktot; ++k) {
			//	printf("About to write polygon number %d\n",k);
				WormPolygon** CurrentPolygonPtr= (WormPolygon**) MontageReader.ptr;
				WormPolygon* CurrentPolygon=*CurrentPolygonPtr;

				cvWrite(fs,NULL,CurrentPolygon->Points);

				CV_NEXT_SEQ_ELEM(CurrentMontage->elem_size,MontageReader);
			}
			CurrentMontagePtr=NULL;
			CurrentMontage=NULL;
			cvEndWriteStruct(fs);

			/** Loop to Next Step **/
			CV_NEXT_SEQ_ELEM(myP->Steps->elem_size,StepReader);

		}
		cvEndWriteStruct(fs);
	cvEndWriteStruct(fs);
}
void storeTrainingData()
{
    CvFileStorage * fileStorage;
    int i;
    fileStorage = cvOpenFileStorage( "/etc/pam_face_authentication/facedata.xml", 0, CV_STORAGE_WRITE );
    cvWriteInt( fileStorage, "numberOfEigenVectors", numberOfEigenVectors );
    cvWriteInt( fileStorage, "numberOfTrainingFaces", numberOfTrainingFaces );
    cvWrite(fileStorage, "eigenValueMatrix", eigenValueMatrix, cvAttrList(0,0));
    cvWrite(fileStorage, "projectedTrainFaceMat", projectedTrainFaceMat, cvAttrList(0,0));
    cvWrite(fileStorage, "avgTrainImg", averageTrainingImage, cvAttrList(0,0));
    for (i=0; i<numberOfEigenVectors; i++)
    {
        char varname[200];
        sprintf( varname, "eigenVect_%d", i );
        cvWrite(fileStorage, varname, eigenVectorArray[i], cvAttrList(0,0));
    }

    cvReleaseFileStorage( &fileStorage );
}
Esempio n. 13
0
//////////////////////////////////
// storeTrainingData()
//
void faceRecognition::storeTrainingData()
{
	CvFileStorage * fileStorage;
	int i;
	// create a file-storage interface
	fileStorage = cvOpenFileStorage( "./res/facedata.xml", 0, CV_STORAGE_WRITE );
	// store all the data
	cvWriteInt( fileStorage, "nEigens", nEigens );
	cvWriteInt( fileStorage, "nTrainFaces", nTrainFaces );
	cvWrite(fileStorage, "trainPersonNumMat", personNumTruthMat, cvAttrList(0,0));
	cvWrite(fileStorage, "eigenValMat", eigenValMat, cvAttrList(0,0));
	cvWrite(fileStorage, "projectedTrainFaceMat", projectedTrainFaceMat, cvAttrList(0,0));
	cvWrite(fileStorage, "avgTrainImg", pAvgTrainImg, cvAttrList(0,0));
	for(i=0; i<nEigens; i++){
		char varname[200];
		sprintf( varname, "eigenVect_%d", i );
		cvWrite(fileStorage, varname, eigenVectArr[i], cvAttrList(0,0));
	}
	// release the file-storage interface
	cvReleaseFileStorage( &fileStorage);
}
Esempio n. 14
0
int main(int argc, 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);
	printf("Example 3_17, writing cfg.xml\n");
	CvFileStorage* fs = cvOpenFileStorage("cfg.xml", 0, CV_STORAGE_WRITE);
	cvWriteInt(fs, "frame_count", 10);
	cvStartWriteStruct(fs, "frame_size", CV_NODE_SEQ);
	cvWriteInt(fs, 0, 320);
	cvWriteInt(fs, 0, 200);
	cvEndWriteStruct(fs);
	cvWrite(fs, "color_cvt_matrix", cmatrix);
	cvReleaseFileStorage(&fs);
	return 0;
}
Esempio n. 15
0
/* debug functions */
void icvSave( const CvArr* ptr, const char* filename, int line )
{
    CvFileStorage* fs;
    char buf[PATH_MAX];
    const char* name;
    
    name = strrchr( filename, '\\' );
    if( !name ) name = strrchr( filename, '/' );
    if( !name ) name = filename;
    else name++; /* skip '/' or '\\' */

    sprintf( buf, "%s-%d-%d", name, line, time( NULL ) );
    fs = cvOpenFileStorage( buf, NULL, CV_STORAGE_WRITE_TEXT );
    if( !fs ) return;
    cvWrite( fs, "debug", ptr );
    cvReleaseFileStorage( &fs );
}
Esempio n. 16
0
int Eigenfaces::saveConfig(const string& dir)
{
    if (DEBUG)
        cout << "Saving config in "<< dir << endl;

    string configFile          = dir + string("/libface-config.xml");
    CvFileStorage* fileStorage = cvOpenFileStorage(d->configFile.c_str(), 0, CV_STORAGE_WRITE);

    if (!fileStorage)
    {
        if (DEBUG)
            cout << "Cant open for storing :" << d->configFile << endl;

        return 1;
    }

    // Start storing
    unsigned int nIds = d->faceImgArr.size(), i;

    // Write some initial params and matrices
    cvWriteInt( fileStorage, "nIds", nIds );
    cvWriteInt( fileStorage, "FACE_WIDTH", d->FACE_WIDTH);
    cvWriteInt( fileStorage, "FACE_HEIGHT", d->FACE_HEIGHT);
    cvWriteReal( fileStorage, "THRESHOLD", d->THRESHOLD);

    // Write all the training faces
    for ( i = 0; i < nIds; i++ )
    {
        char facename[200];
        sprintf(facename, "person_%d", i);
        cvWrite(fileStorage, facename, d->faceImgArr.at(i), cvAttrList(0,0));
    }

    for ( i = 0; i < nIds; i++ )
    {
        char idname[200];
        sprintf(idname, "id_%d", i);
        cvWriteInt(fileStorage, idname, d->indexMap.at(i));
    }

    // Release the fileStorage
    cvReleaseFileStorage(&fileStorage);
    return 0;
}
Esempio n. 17
0
int
main (int argc, char **argv)
{
  char filename[] = "save_cv.xml";	// file name
  int i;
  int a;
  float b;
  CvMat** mat;
  CvFileStorage *cvfs;

  // (1)create sample data
  a = 10;
  b = 0.1;
  mat = (CvMat**)cvAlloc(3*sizeof(CvMat*));
  for(i=0;i<3;i++){
    mat[i] = cvCreateMat(3,3,CV_32FC1);
    cvSet(mat[i], cvScalarAll(i), NULL);
  }

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

  // (3)write data to file
  cvWriteInt(cvfs, "a", a);
  cvWriteReal(cvfs, "b", b);

  cvStartWriteStruct(cvfs, "mat_array", CV_NODE_SEQ, NULL, cvAttrList(NULL, NULL));	// create node
  for(i=0; i<3; i++){
    cvWrite(cvfs, NULL, mat[i], cvAttrList(NULL, NULL));
  }
  cvEndWriteStruct(cvfs);

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

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

  return 0;
}
Esempio n. 18
0
/* simple API for reading/writing data */
CV_IMPL void
cvSave( const char* filename, const void* struct_ptr,
        const char* _name, const char* comment, CvAttrList attributes )
{
    CvFileStorage* fs = 0;

    if( !struct_ptr )
        CV_Error( CV_StsNullPtr, "NULL object pointer" );

    fs = cvOpenFileStorage( filename, 0, CV_STORAGE_WRITE );
    if( !fs )
        CV_Error( CV_StsError, "Could not open the file storage. Check the path and permissions" );

    cv::String name = _name ? cv::String(_name) : cv::FileStorage::getDefaultObjectName(filename);

    if( comment )
        cvWriteComment( fs, comment, 0 );
    cvWrite( fs, name.c_str(), struct_ptr, attributes );
    cvReleaseFileStorage( &fs );
}
Esempio n. 19
0
void CvANN_MLP::write( CvFileStorage* fs, const char* name )
{
    CV_FUNCNAME( "CvANN_MLP::write" );

    __BEGIN__;

    int i, l_count = layer_sizes->cols;

    if( !layer_sizes )
        CV_ERROR( CV_StsError, "The network has not been initialized" );

    cvStartWriteStruct( fs, name, CV_NODE_MAP, CV_TYPE_NAME_ML_ANN_MLP );

    cvWrite( fs, "layer_sizes", layer_sizes );

    write_params( fs );
    
    cvStartWriteStruct( fs, "input_scale", CV_NODE_SEQ + CV_NODE_FLOW );
    cvWriteRawData( fs, weights[0], layer_sizes->data.i[0]*2, "d" );
    cvEndWriteStruct( fs );

    cvStartWriteStruct( fs, "output_scale", CV_NODE_SEQ + CV_NODE_FLOW );
    cvWriteRawData( fs, weights[l_count], layer_sizes->data.i[l_count-1]*2, "d" );
    cvEndWriteStruct( fs );

    cvStartWriteStruct( fs, "inv_output_scale", CV_NODE_SEQ + CV_NODE_FLOW );
    cvWriteRawData( fs, weights[l_count+1], layer_sizes->data.i[l_count-1]*2, "d" );
    cvEndWriteStruct( fs );

    cvStartWriteStruct( fs, "weights", CV_NODE_SEQ );
    for( i = 1; i < l_count; i++ )
    {
        cvStartWriteStruct( fs, 0, CV_NODE_SEQ + CV_NODE_FLOW );
        cvWriteRawData( fs, weights[i], (layer_sizes->data.i[i-1]+1)*layer_sizes->data.i[i], "d" );
        cvEndWriteStruct( fs );
    }

    cvEndWriteStruct( fs );

    __END__;
}
Esempio n. 20
0
void CvOneWayDescriptor::Write(CvFileStorage* fs, const char* name)
{
	CvMat* mat = cvCreateMat(m_pose_count, m_samples[0]->width*m_samples[0]->height, CV_32FC1);

	// prepare data to write as a single matrix
	for(int i = 0; i < m_pose_count; i++)
	{
		for(int y = 0; y < m_samples[i]->height; y++)
		{
			for(int x = 0; x < m_samples[i]->width; x++)
			{
				float val = *((float*)(m_samples[i]->imageData + m_samples[i]->widthStep*y) + x);
				cvmSet(mat, i, y*m_samples[i]->width + x, val);
			}
		}
	}

	cvWrite(fs, name, mat);

	cvReleaseMat(&mat);
}
Esempio n. 21
0
int
main (int argc, char *argv[])
{
  int i, j, k;
  int corner_count, found;
  int p_count[IMAGE_NUM];
  IplImage *src_img[IMAGE_NUM];
  CvSize pattern_size = cvSize (PAT_COL, PAT_ROW);
  CvPoint3D32f objects[ALL_POINTS];
  CvPoint2D32f *corners = (CvPoint2D32f *) cvAlloc (sizeof (CvPoint2D32f) * ALL_POINTS);
  CvMat object_points;
  CvMat image_points;
  CvMat point_counts;
  CvMat *intrinsic = cvCreateMat (3, 3, CV_32FC1);
  CvMat *rotation = cvCreateMat (1, 3, CV_32FC1);
  CvMat *translation = cvCreateMat (1, 3, CV_32FC1);
  CvMat *distortion = cvCreateMat (1, 4, CV_32FC1);

  // (1)キャリブレーション画像の読み込み
  for (i = 0; i < IMAGE_NUM; i++) {
    char buf[32];
    sprintf (buf, "calib_img/%02d.png", i);
    if ((src_img[i] = cvLoadImage (buf, CV_LOAD_IMAGE_COLOR)) == NULL) {
      fprintf (stderr, "cannot load image file : %s\n", buf);
    }
  }

  // (2)3次元空間座標の設定
  for (i = 0; i < IMAGE_NUM; i++) {
    for (j = 0; j < PAT_ROW; j++) {
      for (k = 0; k < PAT_COL; k++) {
        objects[i * PAT_SIZE + j * PAT_COL + k].x = j * CHESS_SIZE;
        objects[i * PAT_SIZE + j * PAT_COL + k].y = k * CHESS_SIZE;
        objects[i * PAT_SIZE + j * PAT_COL + k].z = 0.0;
      }
    }
  }
  cvInitMatHeader (&object_points, ALL_POINTS, 3, CV_32FC1, objects);

  // (3)チェスボード(キャリブレーションパターン)のコーナー検出
  int found_num = 0;
  cvNamedWindow ("Calibration", CV_WINDOW_AUTOSIZE);
  for (i = 0; i < IMAGE_NUM; i++) {
    found = cvFindChessboardCorners (src_img[i], pattern_size, &corners[i * PAT_SIZE], &corner_count);
    fprintf (stderr, "%02d...", i);
    if (found) {
      fprintf (stderr, "ok\n");
      found_num++;
    }
    else {
      fprintf (stderr, "fail\n");
    }
    // (4)コーナー位置をサブピクセル精度に修正,描画
    IplImage *src_gray = cvCreateImage (cvGetSize (src_img[i]), IPL_DEPTH_8U, 1);
    cvCvtColor (src_img[i], src_gray, CV_BGR2GRAY);
    cvFindCornerSubPix (src_gray, &corners[i * PAT_SIZE], corner_count,
                        cvSize (3, 3), cvSize (-1, -1), cvTermCriteria (CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 20, 0.03));
    cvDrawChessboardCorners (src_img[i], pattern_size, &corners[i * PAT_SIZE], corner_count, found);
    p_count[i] = corner_count;
    cvShowImage ("Calibration", src_img[i]);
    cvWaitKey (0);
  }
  cvDestroyWindow ("Calibration");

  if (found_num != IMAGE_NUM)
    return -1;
  cvInitMatHeader (&image_points, ALL_POINTS, 1, CV_32FC2, corners);
  cvInitMatHeader (&point_counts, IMAGE_NUM, 1, CV_32SC1, p_count);

  // (5)内部パラメータ,歪み係数の推定
  cvCalibrateCamera2 (&object_points, &image_points, &point_counts, cvSize (640, 480), intrinsic, distortion);

  // (6)外部パラメータの推定
  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);

  // (7)XMLファイルへの書き出し
  CvFileStorage *fs;
  fs = cvOpenFileStorage ("camera.xml", 0, CV_STORAGE_WRITE);
  cvWrite (fs, "intrinsic", intrinsic);
  cvWrite (fs, "rotation", rotation);
  cvWrite (fs, "translation", translation);
  cvWrite (fs, "distortion", distortion);
  cvReleaseFileStorage (&fs);

  for (i = 0; i < IMAGE_NUM; i++) {
    cvReleaseImage (&src_img[i]);
  }

  return 0;
}
Esempio n. 22
0
void CvMatrix::write( CvFileStorage* fs, const char* matname )
{
    if( matrix )
        cvWrite( fs, matname, matrix );
}
Esempio n. 23
0
void CvImage::write( CvFileStorage* fs, const char* imgname )
{
    if( image )
        cvWrite( fs, imgname, image );
}
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. 25
0
void save_camera_params( const char* out_filename, int image_count, CvSize img_size,
                         CvSize board_size, float square_size,
                         float aspect_ratio, int flags,
                         const CvMat* camera_matrix, CvMat* dist_coeffs,
                         const CvMat* extr_params, const CvSeq* image_points_seq,
                         const CvMat* reproj_errs, double avg_reproj_err )
{
    CvFileStorage* fs = cvOpenFileStorage( out_filename, 0, CV_STORAGE_WRITE );
    
    time_t t;
    time( &t );
    struct tm *t2 = localtime( &t );
    char buf[1024];
    strftime( buf, sizeof(buf)-1, "%c", t2 );

    cvWriteString( fs, "calibration_time", buf );
    
    cvWriteInt( fs, "image_count", image_count );
    cvWriteInt( fs, "image_width", img_size.width );
    cvWriteInt( fs, "image_height", img_size.height );
    cvWriteInt( fs, "board_width", board_size.width );
    cvWriteInt( fs, "board_height", board_size.height );
    cvWriteReal( fs, "square_size", square_size );
    
    if( flags & CV_CALIB_FIX_ASPECT_RATIO )
        cvWriteReal( fs, "aspect_ratio", aspect_ratio );

    if( flags != 0 )
    {
        sprintf( buf, "flags: %s%s%s%s",
            flags & CV_CALIB_USE_INTRINSIC_GUESS ? "+use_intrinsic_guess" : "",
            flags & CV_CALIB_FIX_ASPECT_RATIO ? "+fix_aspect_ratio" : "",
            flags & CV_CALIB_FIX_PRINCIPAL_POINT ? "+fix_principal_point" : "",
            flags & CV_CALIB_ZERO_TANGENT_DIST ? "+zero_tangent_dist" : "" );
        cvWriteComment( fs, buf, 0 );
    }
    
    cvWriteInt( fs, "flags", flags );

    cvWrite( fs, "camera_matrix", camera_matrix );
    cvWrite( fs, "distortion_coefficients", dist_coeffs );

    cvWriteReal( fs, "avg_reprojection_error", avg_reproj_err );
    if( reproj_errs )
        cvWrite( fs, "per_view_reprojection_errors", reproj_errs );

    if( extr_params )
    {
        cvWriteComment( fs, "a set of 6-tuples (rotation vector + translation vector) for each view", 0 );
        cvWrite( fs, "extrinsic_parameters", extr_params );
    }

    if( image_points_seq )
    {
        cvWriteComment( fs, "the array of board corners projections used for calibration", 0 );
        assert( image_points_seq->total == image_count );
        CvMat* image_points = cvCreateMat( 1, image_count*board_size.width*board_size.height, CV_32FC2 );
        cvCvtSeqToArray( image_points_seq, image_points->data.fl );

        cvWrite( fs, "image_points", image_points );
        cvReleaseMat( &image_points );
    }

    cvReleaseFileStorage( &fs );
}
// --------------------------------------------------------------------------
// 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;
    }

    // Images
    std::vector<IplImage*> images;
    printf("Press space key to take a sample picture !\n");

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

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

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

        // Convert the camera image to grayscale
        IplImage *gray = cvCreateImage(cvGetSize(image), IPL_DEPTH_8U, 1);
        cvCvtColor(image, gray, CV_BGR2GRAY);

        // Detect the chessboard
        int corner_count = 0;
        CvSize size = cvSize(PAT_COL, PAT_ROW);
        CvPoint2D32f corners[PAT_SIZE];
        int found = cvFindChessboardCorners(gray, size, corners, &corner_count, CV_CALIB_CB_ADAPTIVE_THRESH+CV_CALIB_CB_NORMALIZE_IMAGE|CV_CALIB_CB_FAST_CHECK);

        // Chessboard detected
        if (found) {
            // Draw corners
            cvDrawChessboardCorners(image, size, corners, corner_count, found);

            // If you push Space key
            if (key == ' ') {
                // Add to buffer
                images.push_back(gray);
            }
            else {
                // Release the image
                cvReleaseImage(&gray);
            }
        }
        // Failed to detect
        else {
            // Release the image
            cvReleaseImage(&gray);
        }

        // Display the image
        cvDrawText(image, cvPoint(15, 20), "NUM = %d", (int)images.size());
        cvShowImage("camera", image);
    }

    // Destroy the window
    cvDestroyWindow("camera");

    // At least one image was taken
    if (!images.empty()) {
        // Total number of images
        const int num = (int)images.size();

        //// For debug
        //for (int i = 0; i < num; i++) {
        //    char name[256];
        //    sprintf(name, "images[%d/%d]", i+1, num);
        //    cvShowImage(name, images[i]);
        //    cvWaitKey(0);
        //    cvDestroyWindow(name);
        //}

        // Ask save parameters or not
        if (cvAsk("Do you save the camera parameters ? (y/n)\n")) {
            // Detect coners
            int *p_count = (int*)malloc(sizeof(int) * num);
            CvPoint2D32f *corners = (CvPoint2D32f*)cvAlloc(sizeof(CvPoint2D32f) * num * PAT_SIZE);
            for (int i = 0; i < num; i++) {
                // Detect chessboard
                int corner_count = 0;
                CvSize size = cvSize(PAT_COL, PAT_ROW);
                int found = cvFindChessboardCorners(images[i], size, &corners[i * PAT_SIZE], &corner_count);

                // Convert the corners to sub-pixel
                cvFindCornerSubPix(images[i], &corners[i * PAT_SIZE], corner_count, cvSize(3, 3), cvSize(-1, -1), cvTermCriteria(CV_TERMCRIT_ITER|CV_TERMCRIT_EPS, 20, 0.03));
                p_count[i] = corner_count;
            }

            // Set the 3D position of patterns
            CvPoint3D32f *objects = (CvPoint3D32f*)cvAlloc(sizeof(CvPoint3D32f) * num * PAT_SIZE);
            for (int i = 0; i < num; i++) {
                for (int j = 0; j < PAT_ROW; j++) {
                    for (int k = 0; k < PAT_COL; k++) {
                        objects[i * PAT_SIZE + j * PAT_COL + k].x = j * CHESS_SIZE;
                        objects[i * PAT_SIZE + j * PAT_COL + k].y = k * CHESS_SIZE;
                        objects[i * PAT_SIZE + j * PAT_COL + k].z = 0.0;
                    }
                }
            }

            // Create matrices
            CvMat object_points, image_points, point_counts;
            cvInitMatHeader(&object_points, num * PAT_SIZE, 3, CV_32FC1, objects);
            cvInitMatHeader(&image_points,  num * PAT_SIZE, 1, CV_32FC2, corners);
            cvInitMatHeader(&point_counts,  num,            1, CV_32SC1, p_count);

            // Estimate intrinsic parameters and distortion coefficients
            printf("Calicurating parameters...");
            CvMat *intrinsic   = cvCreateMat(3, 3, CV_32FC1);
            CvMat *distortion  = cvCreateMat(1, 4, CV_32FC1);
            cvCalibrateCamera2(&object_points, &image_points, &point_counts, cvGetSize(images[0]), intrinsic, distortion);
            printf("Finished !\n");

            // Output a file
            printf("Generating a XML file...");
            CvFileStorage *fs = cvOpenFileStorage("camera.xml", 0, CV_STORAGE_WRITE);
            cvWrite(fs, "intrinsic", intrinsic);
            cvWrite(fs, "distortion", distortion);
            cvReleaseFileStorage(&fs);    
            printf("Finished !\n");

            // Release the matrices
            free(p_count);
            cvFree(&corners);
            cvFree(&objects);
            cvReleaseMat(&intrinsic);
            cvReleaseMat(&distortion);
        }

        // Release the images
        for (int i = 0; i < num; i++) cvReleaseImage(&images[i]);
    }

    // See you
    ardrone.close();

    return 0;
}
Esempio n. 27
0
/*
 * Writes Out information of one frame of the worm to a disk
 * in YAML format.
 *
 * Note the Worm object must have the following fields
 * Worm->frameNum
 * Worm->Segmented->Head
 * Worm->Segmented->Tail
 * Worm->Segmented->LeftBound
 * Worm->Segmented->RightBound
 * Worm->Segmented->Centerline
 *
 * and Params object must have
 * Params->DLPOn
 * Params->IllumSegCenter
 * Params->IllumSegRadius
 * Params->IllumLRC
 *
 * And more now!
 */
int AppendWormFrameToDisk(WormAnalysisData* Worm, WormAnalysisParam* Params, WriteOut* DataWriter){

	CvFileStorage* fs=DataWriter->fs;

	cvStartWriteStruct(fs,NULL,CV_NODE_MAP,NULL);
		/** Frame Number Info **/
		cvWriteInt(fs,"FrameNumber",Worm->frameNum);

		/** TimeStamp **/
		cvWriteInt(fs,"sElapsed",GetSeconds(Worm->timestamp));
		cvWriteInt(fs,"msRemElapsed",GetMilliSeconds(Worm->timestamp));


		/** Segmentation Info **/
		if(cvPointExists(Worm->Segmented->Head)){
		cvStartWriteStruct(fs,"Head",CV_NODE_MAP,NULL);
			cvWriteInt(fs,"x",Worm->Segmented->Head->x);
			cvWriteInt(fs,"y",Worm->Segmented->Head->y);
		cvEndWriteStruct(fs);
		}

		if(cvPointExists(Worm->Segmented->Tail)){
		cvStartWriteStruct(fs,"Tail",CV_NODE_MAP,NULL);
			cvWriteInt(fs,"x",Worm->Segmented->Tail->x);
			cvWriteInt(fs,"y",Worm->Segmented->Tail->y);
		cvEndWriteStruct(fs);
		}


		if(cvSeqExists(Worm->Segmented->LeftBound)) cvWrite(fs,"BoundaryA",Worm->Segmented->LeftBound);
		if(cvSeqExists(Worm->Segmented->RightBound)) cvWrite(fs,"BoundaryB",Worm->Segmented->RightBound);
		if(cvSeqExists(Worm->Segmented->Centerline)) cvWrite(fs,"SegmentedCenterline",Worm->Segmented->Centerline);

		/** Illumination Information **/
		cvWriteInt(fs,"DLPIsOn",Params->DLPOn);
		cvWriteInt(fs,"FloodLightIsOn",Params->IllumFloodEverything);
		cvWriteInt(fs,"IllumInvert",Params->IllumInvert);
		cvWriteInt(fs,"IllumFlipLR",Params->IllumFlipLR);

		CvPoint origin=ConvertSlidlerToWormSpace(Params->IllumSquareOrig,Params->DefaultGridSize);
		cvStartWriteStruct(fs,"IllumRectOrigin",CV_NODE_MAP,NULL);
			cvWriteInt(fs,"x",origin.x);
			cvWriteInt(fs,"y",origin.y);
		cvEndWriteStruct(fs);

		cvStartWriteStruct(fs,"IllumRectRadius",CV_NODE_MAP,NULL);
			cvWriteInt(fs,"x",Params->IllumSquareRad.width);
			cvWriteInt(fs,"y",Params->IllumSquareRad.height);
		cvEndWriteStruct(fs);

		if (Params->stageTrackingOn){
			cvStartWriteStruct(fs,"StageVelocity",CV_NODE_MAP,NULL);
				cvWriteInt(fs,"i",Worm->stageVelocity.x);
				cvWriteInt(fs,"j",Worm->stageVelocity.y);
			cvEndWriteStruct(fs);
		}

		/** Protocol Information **/

		cvWriteInt(fs,"ProtocolIsOn",Params->ProtocolUse);
		cvWriteInt(fs,"ProtocolStep",Params->ProtocolStep);
	cvEndWriteStruct(fs);

	return 0;
}