template<class Storage, class SrcType, class ThreshType, class DstType> static int foaCvBackProject(Storage, SrcType, ThreshType, DstType) { const S1 = 4; const S2 = 4; const S3 = 4; CvSize roi = {100, 100}; int step = roi.width * sizeof( SrcType ); SrcType* src[3]; src[0] = new SrcType[roi.width * roi.height]; src[1] = new SrcType[roi.width * roi.height]; src[2] = new SrcType[roi.width * roi.height]; DstType* measure = new DstType[roi.width * roi.height]; ThreshType _thresh[3][5] = {{1, 2, 3, 4, 5}, {2, 3, 4, 5, 6}, {5, 6, 7, 9, 10}}; ThreshType* thresh[3] = { _thresh[0], _thresh[1], _thresh[2] }; int Errors = 0; for( int i = 0; i < roi.width * roi.height; i++ ) src[0][i] = src[1][i] = src[2][i] = 0; for( i = 0; i < roi.width; i++ ) for( int j = 0; j < 3; j++ ) src[j][roi.width + i] = (SrcType)thresh[j][i%5]; CVHistogram<Storage> hist( S1, S2, S3 ); CvCalculateC1( hist, src, roi, step, thresh ); CvBackProject<CVHistogram<Storage>, SrcType, ThreshType, DstType> ( hist, src, roi, step, thresh, measure, roi.width * sizeof(DstType), 0 ); for( i = 0; i < roi.width; i++ ) if( measure[roi.width + i] != roi.width / 5 * (1 + (i%5 == 0) + (i%5 == 1))) { trsWrite( ATS_CON | ATS_LST, "Wrong destination value\n" ); Errors++; break; } for( int y = 0; y < roi.height; y++ ) for( int x = 0; x < roi.width; x++ ) if( y != 1 && measure[roi.width * y + x] != 0 ) { trsWrite( ATS_CON | ATS_LST, "Wrong destination value (non zero)\n" ); Errors++; goto _exit; } _exit:; delete src[0]; delete src[1]; delete src[2]; delete measure; return Errors == 0 ? TRS_OK : trsResult( TRS_FAIL, "Fixed %d errors", Errors ); }
static int CheckImage(IplImage* image, char* file, char* /*funcname*/) { //printf("loading %s\n", file ); IplImage* read = cvLoadImage( file, 1 ); if( !read ) { trsWrite( ATS_CON | ATS_LST, "can't read image\n" ); return 1; } int err = 0; #if 0 { IplImage* temp = cvCloneImage( read ); cvAbsDiff( image, read, temp ); cvThreshold( temp, temp, 0, 255, CV_THRESH_BINARY ); cvvNamedWindow( "Original", 0 ); cvvNamedWindow( "Diff", 0 ); cvvShowImage( "Original", read ); cvvShowImage( "Diff", temp ); cvvWaitKey(0); cvvDestroyWindow( "Original" ); cvvDestroyWindow( "Diff" ); } #endif cvAbsDiff( image, read, read ); cvThreshold( read, read, 0, 1, CV_THRESH_BINARY ); err = cvRound( cvNorm( read, 0, CV_L1 ))/3; cvReleaseImage( &read ); return err; }
static int ProcessImage( IplImage* image, char* funcname, int read ) { char name[1000]; char lowername[1000]; int i = 0, err; do { lowername[i] = (char)my_tolower(funcname[i]); } while( funcname[i++] != '\0' ); if( read ) { err = CheckImage( image, atsGetTestDataPath(name, filedir_, lowername, "bmp"), funcname ); if( err ) { trsWrite( ATS_CON | ATS_LST, "Error in %s: %d\n", funcname, err ); } return 0; //err; } else { cvvSaveImage( atsGetTestDataPath(name, filedir_, lowername, "bmp"), image ); return 0; } }
template <class Val, class Idx> static int check_balance( _CvTreeNode<Val,Idx>* root ) { if( root == 0 ) return 0; int left = check_balance( root->link[0] ); int right = check_balance( root->link[1] ); if( left < 0 || right < 0 ) return -1; switch( left - right ) { case 0: if( root->balance != _CvTreeNode<Val,Idx>::center ) { trsWrite( ATS_CON | ATS_LST, "Wrong balance: act: %d exp:2\n", root->balance ); return -1; } break; case 1: if( root->balance != _CvTreeNode<Val,Idx>::left ) { trsWrite( ATS_CON | ATS_LST, "Wrong balance: act: %d exp:0\n", root->balance ); return -1; } break; case -1: if( root->balance != _CvTreeNode<Val,Idx>::right ) { trsWrite( ATS_CON | ATS_LST, "Wrong balance: act: %d exp:1\n", root->balance ); return -1; } break; default: trsWrite( ATS_CON | ATS_LST, "Wrong balance\n" ); return -1; } return 1 + (left > right ? left : right); }
template<class Storage1, class Storage2> static int foaOperations(Storage1, Storage2) { const int SIZE = 720; typedef Storage1::value_type Val; typedef Storage1::idx_type Idx; CVHistogram<Storage1> hist1( SIZE ); CVHistogram<Storage2> hist2( SIZE ); int Errors = 0; for( Idx i = 0; i < SIZE; i++ ) { hist1[i] = (Val)(i % 10); hist2[i] = (Val)(9 - hist1[i]); } if( calc_histogram_intersection( hist1, hist2 ) != SIZE * 2 ) { Errors++; trsWrite( ATS_CON | ATS_LST, "Error Intersection function\n" ); } double res; if( (res = fabs(calc_histogram_chi_square( hist1, hist2 ) - SIZE * 330 / 90)) > 0.0001 ) { Errors++; trsWrite( ATS_CON | ATS_LST, "Error ChiSqr function\n" ); } for( i = 0; i < SIZE; i++ ) { hist1[i] = (Val)(i % 9); hist2[i] = (Val)(8 - hist1[i]); } if( fabs(calc_histogram_correlation( hist1, hist2 ) + 1 ) >= 0.0001 ) { Errors++; trsWrite( ATS_CON | ATS_LST, "Error Correl function\n" ); } return Errors == 0 ? TRS_OK : trsResult( TRS_FAIL, "Fixed %d errors", Errors ); }
/*F/////////////////////////////////////////////////////////////////////////////////////// // Name: atsCompare2Db // Purpose: // Comparing two array and writing results to SUM & LST files // Context: // Parameters: // Returns: // Number of differents elements // Notes: //F*/ long atsCompare2Dc( char* ArrayAct, char* ArrayExp, CvSize size, int stride, int Tol ) { int x, y; long lErrors = 0; for( y = 0; y < size.height; y++, ArrayAct += stride, ArrayExp += stride ) for( x = 0; x < size.width; x++ ) if( abs( ArrayAct[x] - ArrayExp[x] ) > Tol ) { lErrors++; trsWrite( ATS_LST, "Error: x=%d y=%d act %d exp %d\n", x, y, (int)ArrayAct[x], (int)ArrayExp[x] ); } /* if */ if( lErrors ) trsWrite( ATS_SUM | ATS_LST, "Total fixed %d errors :(\n", lErrors ); return lErrors; }
template <class Val, class Idx> static int foaCvTreeIterator() { int Errors = 0; typedef CvTree<Val, Idx>::node_type node_type; CvTree<Val, Idx> tree; for( Idx i = 0; i < SIZE; i++ ) tree[i] = (Val)(i + 1); CvTreeIterator<node_type> iterator; iterator = tree.begin(); if( *iterator != 1 ) { Errors++; trsWrite( ATS_CON | ATS_LST, "Wrong CvTree::begin() function\n" ); } if( *(iterator++) != 1 ) { Errors++; trsWrite( ATS_CON | ATS_LST, "Wrong postfix operator++ (not postfix)\n" ); } if( *iterator != 2 ) { Errors++; trsWrite( ATS_CON | ATS_LST, "Wrong postfix operator++ (not increment)\n" ); } for( i = 2; i < SIZE; i++ ) if( *(++iterator) != (i + 1) ) { Errors++; trsWrite( ATS_CON | ATS_LST, "Wrong prefix operator++ (not increment)\n" ); break; } if( *(++iterator) != SIZE ) { Errors++; trsWrite( ATS_CON | ATS_LST, "Wrong operator++ (increment out of date)\n" ); } if( !(iterator == iterator) ) { Errors++; trsWrite( ATS_CON | ATS_LST, "Bad operator==" ); } if( iterator != iterator ) { Errors++; trsWrite( ATS_CON | ATS_LST, "Bad operator!=" ); } return Errors == 0 ? TRS_OK : trsResult( TRS_FAIL, "Fixed %d errors", Errors ); }
/*F/////////////////////////////////////////////////////////////////////////////////////// // Name: atsCompare1Dc // Purpose: // Comparing two 1D array and writing results to SUM & LST files // Context: // Parameters: // ArrayAct - actual array // ArrayExp - expected array // lLen - lenght of this arrays // Tol - tolerable limit // Returns: // Number of differents elements // Notes: //F*/ long atsCompare1Dc( char* ArrayAct, char* ArrayExp, long lLen, int Tol ) { int i; long lErrors = 0; for( i = 0; i < lLen; i++ ) { if( abs( ArrayAct[i] - ArrayExp[i] ) > Tol ) { lErrors++; trsWrite( ATS_LST, "Error: x = %d act %d exp %d\n", i, (int)ArrayAct[i], (int)ArrayExp[i] ); } /* if */ } /* for */ if( lErrors ) trsWrite( ATS_SUM | ATS_LST, "Total fixed %d errors :(\n", lErrors ); return lErrors; } /* atsCompare1Dc */
/*F/////////////////////////////////////////////////////////////////////////////////////// // Name: atsCompare1Db // Purpose: // Comparing two 1D array and writing results to SUM & LST files // Context: // Parameters: // ArrayAct - actual array // ArrayExp - expected array // lLen - lenght of this arrays // Tol - tolerable limit // Returns: // Number of differents elements // Notes: //F*/ long atsCompare1Db( uchar* ArrayAct, uchar* ArrayExp, long lLen, int Tol ) { int i; long lErrors = 0; for( i = 0; i < lLen; i++ ) { if( abs( ArrayAct[i] - ArrayExp[i] ) > Tol ) { lErrors++; trsWrite( ATS_LST, "Error: x = %d act %d exp %d\n", i, (int)ArrayAct[i], (int)ArrayExp[i] ); } /* if */ } /* for */ if( lErrors == NULL ) trsWrite( ATS_LST, "No errors detected for this test\n" ); else trsWrite( ATS_SUM | ATS_LST, "Total fixed %d errors :(\n", lErrors ); return lErrors; } /* atsCompare1Db */
/*F/////////////////////////////////////////////////////////////////////////////////////// // Name: atsCompare2Dfl // Purpose: // Comparing two array and writing results to SUM & LST files // Context: // Parameters: // Returns: // Number of differents elements // Notes: //F*/ long atsCompare2Dfl( float* ArrayAct, float* ArrayExp, CvSize size, int stride, double Tol ) { int x, y; long lErrors = 0; for( y = 0; y < size.height; y++, ArrayAct = (float*)((long)ArrayAct + stride), ArrayExp = (float*)((long)ArrayExp + stride) ) for( x = 0; x < size.width; x++ ) if( fabs( ArrayAct[x] - ArrayExp[x] ) > Tol ) { lErrors++; trsWrite( ATS_LST, "Error: x=%d y=%d act %f exp %f\n", x, y, (float)ArrayAct[x], (float)ArrayExp[x] ); } /* if */ if( lErrors == NULL ) trsWrite( ATS_LST, "No errors detected for this test\n" ); else trsWrite( ATS_SUM | ATS_LST, "Total fixed %d errors :(\n", lErrors ); return lErrors; } /* atsCompare1Db */
long atsCompare1Dfl( float* flArrayAct, float* flArrayExp, long lLen, double dbTol ) { int i; long lErrors = 0; for( i = 0; i < lLen; i++ ) { if( fabs( flArrayAct[i] - flArrayExp[i] ) > dbTol ) { lErrors++; trsWrite( ATS_LST, "Error: x = %d act %f exp %f\n", i, flArrayAct[i], flArrayExp[i] ); } /* if */ } /* for */ if( lErrors == NULL ) trsWrite( ATS_LST, "No errors detected for this test\n" ); else trsWrite( ATS_SUM | ATS_LST, "Total fixed %d errors :(\n", lErrors ); return lErrors; } /* atsCompare1Dfl */
static int fmaKMeans(void) { CvTermCriteria crit; float** vectors; int* output; int* etalon_output; int lErrors = 0; int lNumVect = 0; int lVectSize = 0; int lNumClust = 0; int lMaxNumIter = 0; float flEpsilon = 0; int i,j; static int read_param = 0; /* Initialization global parameters */ if( !read_param ) { read_param = 1; /* Read test-parameters */ trsiRead( &lNumVect, "1000", "Number of vectors" ); trsiRead( &lVectSize, "10", "Number of vectors" ); trsiRead( &lNumClust, "20", "Number of clusters" ); trsiRead( &lMaxNumIter,"100","Maximal number of iterations"); trssRead( &flEpsilon, "0.5", "Accuracy" ); } crit = cvTermCriteria( CV_TERMCRIT_EPS|CV_TERMCRIT_ITER, lMaxNumIter, flEpsilon ); //allocate vectors vectors = (float**)cvAlloc( lNumVect * sizeof(float*) ); for( i = 0; i < lNumVect; i++ ) { vectors[i] = (float*)cvAlloc( lVectSize * sizeof( float ) ); } output = (int*)cvAlloc( lNumVect * sizeof(int) ); etalon_output = (int*)cvAlloc( lNumVect * sizeof(int) ); //fill input vectors for( i = 0; i < lNumVect; i++ ) { ats1flInitRandom( -2000, 2000, vectors[i], lVectSize ); } /* run etalon kmeans */ /* actually it is the simpliest realization of kmeans */ int ni = _real_kmeans( lNumClust, vectors, lNumVect, lVectSize, etalon_output, crit.epsilon, crit.max_iter ); trsWrite( ATS_CON, "%d iterations done\n", ni ); /* Run OpenCV function */ #define _KMEANS_TIME 0 #if _KMEANS_TIME //timing section trsTimerStart(0); __int64 tics = atsGetTickCount(); #endif cvKMeans( lNumClust, vectors, lNumVect, lVectSize, crit, output ); #if _KMEANS_TIME tics = atsGetTickCount() - tics; trsTimerStop(0); //output result //double dbUsecs =ATS_TICS_TO_USECS((double)tics); trsWrite( ATS_CON, "Tics per iteration %d\n", tics/ni ); #endif //compare results for( j = 0; j < lNumVect; j++ ) { if ( output[j] != etalon_output[j] ) { lErrors++; } } //free memory for( i = 0; i < lNumVect; i++ ) { cvFree( &(vectors[i]) ); } cvFree(&vectors); cvFree(&output); cvFree(&etalon_output); if( lErrors == 0 ) return trsResult( TRS_OK, "No errors fixed for this text" ); else return trsResult( TRS_FAIL, "Detected %d errors", lErrors ); }
//--------------------------------------------------- Test body -------------------------- static int fmaUnDistort( void ) { int i, itest, io=0, num_test, err1=0, err2=0, err3=0, err4=0, err10=0, err20=0, err30=0, err40=0, err=0, err5, pass=1; int n, n3, step, step3; int* data; IplImage* undistMap = 0; uchar *srcImg, *dstImg, *tstImg, *srcImg3, *dstImg3, *tstImg3; IplImage *src, *dst, *tst, *src3, *dst3, *tst3; float *a, *k, p = 0.f; AtsRandState state; CvSize size; double norm, norm1; /* Reading test parameters */ trsiRead( &img_width, "320", "width of image" ); trsiRead( &img_height, "240", "height of image" ); trsiRead( &roi_step, "0", "ROI step" ); n = img_width * img_height; size.height = img_height; size.width = img_width; a = (float*)cvAlloc( sizeof(float) * 9 ); k = (float*)cvAlloc( sizeof(float) * 4 ); //data = (int*) icvAlloc( 3*n*sizeof(int) ); src = cvCreateImage( size, IPL_DEPTH_8U, 1 ); cvSetImageROI( src, cvRect(0, 0, src->width, src->height) ); dst = cvCreateImage( size, IPL_DEPTH_8U, 1 ); cvSetImageROI( dst, cvRect(0, 0, dst->width, dst->height) ); tst = cvCreateImage( size, IPL_DEPTH_8U, 1 ); cvSetImageROI( tst, cvRect(0, 0, tst->width, tst->height) ); src3 = cvCreateImage( size, IPL_DEPTH_8U, 3 ); cvSetImageROI( src3, cvRect(0, 0, src3->width, src3->height) ); dst3 = cvCreateImage( size, IPL_DEPTH_8U, 3 ); cvSetImageROI( dst3, cvRect(0, 0, dst3->width, dst3->height) ); tst3 = cvCreateImage( size, IPL_DEPTH_8U, 3 ); cvSetImageROI( tst3, cvRect(0, 0, tst3->width, tst3->height) ); undistMap = cvCreateImage( size, IPL_DEPTH_32S, 3 ); srcImg = (uchar*)src->imageData; dstImg = (uchar*)dst->imageData; tstImg = (uchar*)tst->imageData; srcImg3 = (uchar*)src3->imageData; dstImg3 = (uchar*)dst3->imageData; tstImg3 = (uchar*)tst3->imageData; data = (int*)undistMap->imageData; step = src->widthStep; step3 = src3->widthStep; n = step*img_height; n3 = step3*img_height; atsRandInit( &state, 0, 255, 13 ); atsbRand8u ( &state, srcImg, n ); atsbRand8u ( &state, srcImg3, n3 ); a[0] = img_width/3.f; a[4] = img_height/2.f; a[2] = img_width/2.f; a[5] = img_height/2.f; k[0] = -0.04f; k[1] = 0.004f; k[2] = 0.f; k[3] = 0.f; if(roi_step) { num_test = (img_width/2 - 3)/roi_step; if( num_test > (img_height/2)/roi_step ) num_test = (img_height/2)/roi_step; } else num_test = 1; if( num_test < 1 ) num_test = 1; begin: trsWrite(TW_RUN|TW_CON, "\n %d pass of 4 :\n", pass); for(itest=0; itest<num_test; itest++) { int ii = (itest*10)/num_test; int roi_offset = roi_step*itest; int img_offset = roi_offset*(step + 1); int img_offset3 = roi_offset*(step3 + 3); size.width = img_width - 2*roi_offset; size.height = img_height - 2*roi_offset; src->roi->xOffset = src->roi->yOffset = roi_offset; src->roi->height = size.height; src->roi->width = size.width; dst->roi->xOffset = dst->roi->yOffset = roi_offset; dst->roi->height = size.height; dst->roi->width = size.width; tst->roi->xOffset = tst->roi->yOffset = roi_offset; tst->roi->height = size.height; tst->roi->width = size.width; src3->roi->xOffset = src3->roi->yOffset = roi_offset; src3->roi->height = size.height; src3->roi->width = size.width; dst3->roi->xOffset = dst3->roi->yOffset = roi_offset; dst3->roi->height = size.height; dst3->roi->width = size.width; tst3->roi->xOffset = tst3->roi->yOffset = roi_offset; tst3->roi->height = size.height; tst3->roi->width = size.width; /* 8uC1 flavor test without interpolation */ for(i=0; i<n; i++) dstImg[i] = tstImg[i] = 0; cvUnDistortInit ( src, undistMap, a, k, 0 ); cvUnDistort ( src, dst, undistMap, 0 ); UnDistortTest_C1( srcImg + img_offset, tstImg + img_offset, step, size, a, k, 0 ); if( !img_offset ) { norm = norm1 = 0.0; for(i=0; i<n; i++) { norm += fabs( dstImg[i] - tstImg[i] ); norm1 += fabs( tstImg[i] ); } norm /= norm1; printf( " 8u C1 without interpolation: %g\n", norm ); } for(i=0; i<n; i++) { int d = dstImg[i] - tstImg[i]; if( d > MAXDIFF || d < -MAXDIFF ) err1++; } for(i=0; i<n; i++) dstImg[i] = 0; cvUnDistortOnce ( src, dst, a, k, 0 ); //for(i=0; i<n; i++)printf(" %d", dstImg[i]); getchar(); if( !img_offset ) { norm = norm1 = 0.0; for(i=0; i<n; i++) { norm += fabs( dstImg[i] - tstImg[i] ); norm1 += fabs( tstImg[i] ); } norm /= norm1; printf( " %g\n", norm ); } for(i=0; i<n; i++) { int d = dstImg[i] - tstImg[i]; if( d > MAXDIFF || d < -MAXDIFF ) err10++; } /* 8uC1 flavor test with interpolation */ for(i=0; i<n; i++) dstImg[i] = tstImg[i] = 0; cvUnDistortInit ( src, undistMap, a, k, 1 ); cvUnDistort ( src, dst, undistMap, 1 ); UnDistortTest_C1( srcImg + img_offset, tstImg + img_offset, step, size, a, k, 1 ); if( !img_offset ) { norm = norm1 = 0.0; for(i=0; i<n; i++) { norm += fabs( dstImg[i] - tstImg[i] ); norm1 += fabs( tstImg[i] ); } norm /= norm1; printf( " 8u C1 with interpolation: %g\n", norm ); } for(i=0; i<n; i++) { int d = dstImg[i] - tstImg[i]; if( d > MAXDIFF || d < -MAXDIFF ) err2++; } for(i=0; i<n; i++) dstImg[i] = 0; cvUnDistortOnce ( src, dst, a, k, 1 ); if( !img_offset ) { norm = norm1 = 0.0; for(i=0; i<n; i++) { norm += fabs( dstImg[i] - tstImg[i] ); norm1 += fabs( tstImg[i] ); } norm /= norm1; printf( " %g\n", norm ); } for(i=0; i<n; i++) { int d = dstImg[i] - tstImg[i]; if( d > MAXDIFF || d < -MAXDIFF ) err20++; } /* 8uC3 flavor test without interpolation */ for(i=0; i<n3; i++) dstImg3[i] = tstImg3[i] = 0; cvUnDistortInit ( src3, undistMap, a, k, 0 ); cvUnDistort ( src3, dst3, undistMap, 0 ); UnDistortTest_C3( srcImg3+img_offset3, tstImg3+img_offset3, step3, size, a, k, 0 ); for(i=0; i<n3; i++) { int d = dstImg3[i] - tstImg3[i]; if( d > MAXDIFF || d < -MAXDIFF ) err3++; } if( !img_offset ) { norm = norm1 = 0.0; for(i=0; i<n3; i++) { norm += fabs( dstImg3[i] - tstImg3[i] ); norm1 += fabs( tstImg3[i] ); } norm /= norm1; printf( " 8u C3 without interpolation: %g\n", norm ); } for(i=0; i<n3; i++) dstImg3[i] = 0; cvUnDistortOnce ( src3, dst3, a, k, 0 ); if( !img_offset ) { norm = norm1 = 0.0; for(i=0; i<n3; i++) { norm += fabs( dstImg3[i] - tstImg3[i] ); norm1 += fabs( tstImg3[i] ); } norm /= norm1; printf( " %g\n", norm ); } for(i=0; i<n3; i++) { int d = dstImg3[i] - tstImg3[i]; if( d > MAXDIFF || d < -MAXDIFF ) err30++; } /* 8uC3 flavor test with interpolation */ for(i=0; i<n3; i++) dstImg3[i] = tstImg3[i] = 0; cvUnDistortInit ( src3, undistMap, a, k, 1 ); cvUnDistort ( src3, dst3, undistMap, 1 ); UnDistortTest_C3( srcImg3+img_offset3, tstImg3+img_offset3, step3, size, a, k, 1 ); for(i=0; i<n3; i++) { int d = dstImg3[i] - tstImg3[i]; if( d > MAXDIFF || d < -MAXDIFF ) err4++; } if( !img_offset ) { norm = norm1 = 0.0; for(i=0; i<n3; i++) { norm += fabs( dstImg3[i] - tstImg3[i] ); norm1 += fabs( tstImg3[i] ); } norm /= norm1; printf( " 8u C3 with interpolation: %g\n", norm ); } for(i=0; i<n3; i++) dstImg3[i] = 0; cvUnDistortOnce ( src3, dst3, a, k, 1 ); if( !img_offset ) { norm = norm1 = 0.0; for(i=0; i<n3; i++) { norm += fabs( dstImg3[i] - tstImg3[i] ); norm1 += fabs( tstImg3[i] ); } norm /= norm1; printf( " %g\n", norm ); } for(i=0; i<n3; i++) { int d = dstImg3[i] - tstImg3[i]; if( d > MAXDIFF || d < -MAXDIFF ) err40++; } if(ii>io) { trsWrite(TW_RUN|TW_CON, " %d%% ", 10*ii); io=ii; } } err5 = err1 + err2 + err3 + err4 + err10 + err20 + err30 + err40; err += err5; if( p < err1*100.f / (float)(n*num_test) ) p = err1*100.f / (float)(n*num_test); if( p < err2*100.f / (float)(n*num_test) ) p = err2*100.f / (float)(n*num_test); if( p < err3*100.f / (float)(3*n*num_test) ) p = err3*100.f / (float)(3*n*num_test); if( p < err4*100.f / (float)(3*n*num_test) ) p = err4*100.f / (float)(3*n*num_test); if( p < err10*100.f / (float)(n*num_test) ) p = err10*100.f / (float)(n*num_test); if( p < err20*100.f / (float)(n*num_test) ) p = err20*100.f / (float)(n*num_test); if( p < err30*100.f / (float)(3*n*num_test) ) p = err30*100.f / (float)(3*n*num_test); if( p < err40*100.f / (float)(3*n*num_test) ) p = err40*100.f / (float)(3*n*num_test); //printf("\n %d %d %d %d\n %d %d %d %d %7.3f%% errors\n", // err1, err2, err3, err4, err10, err20, err30, err40, p); switch( pass ) { case 1: k[0] = -k[0]; io = 0; err1 = err2 = err3 = err4 = err10 = err20 = err30 = err40 = 0; pass++; goto begin; break; case 2: k[0] = -k[0]; k[2] = k[3] = 0.02f; io = 0; err1 = err2 = err3 = err4 = err10 = err20 = err30 = err40 = 0; pass++; goto begin; break; case 3: k[0] = -k[0]; io = 0; err1 = err2 = err3 = err4 = err10 = err20 = err30 = err40 = 0; pass++; goto begin; break; } if( p < MAXPERCENT ) err = 0; cvReleaseImage( &src ); cvReleaseImage( &dst ); cvReleaseImage( &tst ); cvReleaseImage( &src3 ); cvReleaseImage( &dst3 ); cvReleaseImage( &tst3 ); cvReleaseImage( &undistMap ); cvFree( (void**)&a ); cvFree( (void**)&k ); if( err == 0 ) return trsResult( TRS_OK, "No errors fixed by this test" ); else return trsResult( TRS_FAIL, "Total fixed %d errors", err ); } /*fma*/
int testRandomFactors() { int ret = TRS_OK; int nnodes = 0; int i; while(nnodes <= 0) { trsiRead( &nnodes, "5", "Number of nodes in Model" ); } //create node types int seed1 = pnlTestRandSeed(); //create string to display the value char *value = new char[20]; #if 0 value = _itoa(seed1, value, 10); #else sprintf( value, "%d", seed1 ); #endif trsiRead(&seed1, value, "Seed for srand to define NodeTypes etc."); delete []value; trsWrite(TW_CON|TW_RUN|TW_DEBUG|TW_LST, "seed for rand = %d\n", seed1); //create 2 node types and model domain for them nodeTypeVector modelNodeType; modelNodeType.resize(2); modelNodeType[0] = CNodeType( 1, 4 ); modelNodeType[1] = CNodeType( 1, 3 ); intVector NodeAssociat; NodeAssociat.assign(nnodes, 0); for( i = 0; i < nnodes; i++ ) { float rand = pnlRand( 0.0f, 1.0f ); if( rand < 0.5f ) { NodeAssociat[i] = 1; } } CModelDomain* pMDDiscr = CModelDomain::Create( modelNodeType, NodeAssociat ); //create random graph - number of nodes for every node is rand too int lowBorder = nnodes - 1; int upperBorder = int((nnodes * (nnodes - 1))/2); int numEdges = pnlRand( lowBorder, upperBorder ); mark: CGraph* pGraph = tCreateRandomDAG( nnodes, numEdges, 1 ); if ( pGraph->NumberOfConnectivityComponents() != 1 ) { delete pGraph; goto mark; } CBNet* pDiscrBNet = CBNet::CreateWithRandomMatrices( pGraph, pMDDiscr ); //start jtree inference just for checking //the model is valid for inference and all operations can be made CEvidence* pDiscrEmptyEvid = CEvidence::Create( pMDDiscr, 0, NULL, valueVector() ); CJtreeInfEngine* pDiscrInf = CJtreeInfEngine::Create( pDiscrBNet ); pDiscrInf->EnterEvidence( pDiscrEmptyEvid ); const CPotential* pot = NULL; for( i = 0; i < nnodes; i++ ) { intVector domain; pDiscrBNet->GetFactor(i)->GetDomain( &domain ); pDiscrInf->MarginalNodes( &domain.front(), domain.size() ); pot = pDiscrInf->GetQueryJPD(); } //make copy of Graph for using with other models pGraph = CGraph::Copy( pDiscrBNet->GetGraph() ); delete pDiscrInf; delete pDiscrBNet; delete pDiscrEmptyEvid; delete pMDDiscr; //create gaussian model domain modelNodeType[0] = CNodeType( 0, 4 ); modelNodeType[1] = CNodeType( 0, 2 ); CModelDomain* pMDCont = CModelDomain::Create( modelNodeType, NodeAssociat ); CBNet* pContBNet = CBNet::CreateWithRandomMatrices( pGraph, pMDCont ); CEvidence* pContEmptyEvid = CEvidence::Create( pMDCont, 0, NULL, valueVector() ); CNaiveInfEngine* pContInf = CNaiveInfEngine::Create( pContBNet ); pContInf->EnterEvidence( pContEmptyEvid ); for( i = 0; i < nnodes; i++ ) { intVector domain; pContBNet->GetFactor(i)->GetDomain( &domain ); pContInf->MarginalNodes( &domain.front(), domain.size() ); pot = pContInf->GetQueryJPD(); } pGraph = CGraph::Copy(pContBNet->GetGraph()); delete pContInf; delete pContBNet; delete pContEmptyEvid; delete pMDCont; //find the node that haven't any parents //and change its node type for it to create Conditional Gaussian CPD int numOfNodeWithoutParents = -1; intVector parents; parents.reserve(nnodes); for( i = 0; i < nnodes; i++ ) { pGraph->GetParents( i, &parents ); if( parents.size() == 0 ) { numOfNodeWithoutParents = i; break; } } //change node type of this node, make it discrete CNodeType ntTab = CNodeType( 1,4 ); modelNodeType.push_back( ntTab ); NodeAssociat[numOfNodeWithoutParents] = 2; //need to change this model domain CModelDomain* pMDCondGau = CModelDomain::Create( modelNodeType, NodeAssociat ); CBNet* pCondGauBNet = CBNet::CreateWithRandomMatrices( pGraph, pMDCondGau ); //need to create evidence for all gaussian nodes intVector obsNodes; obsNodes.reserve(nnodes); int numGauVals = 0; for( i = 0; i < numOfNodeWithoutParents; i++ ) { int GauSize = pMDCondGau->GetVariableType(i)->GetNodeSize(); numGauVals += GauSize; obsNodes.push_back( i ); } for( i = numOfNodeWithoutParents + 1; i < nnodes; i++ ) { int GauSize = pMDCondGau->GetVariableType(i)->GetNodeSize(); numGauVals += GauSize; obsNodes.push_back( i ); } valueVector obsGauVals; obsGauVals.resize( numGauVals ); floatVector obsGauValsFl; obsGauValsFl.resize( numGauVals); pnlRand( numGauVals, &obsGauValsFl.front(), -3.0f, 3.0f); //fill the valueVector for( i = 0; i < numGauVals; i++ ) { obsGauVals[i].SetFlt(obsGauValsFl[i]); } CEvidence* pCondGauEvid = CEvidence::Create( pMDCondGau, obsNodes, obsGauVals ); CJtreeInfEngine* pCondGauInf = CJtreeInfEngine::Create( pCondGauBNet ); pCondGauInf->EnterEvidence( pCondGauEvid ); pCondGauInf->MarginalNodes( &numOfNodeWithoutParents, 1 ); pot = pCondGauInf->GetQueryJPD(); pot->Dump(); delete pCondGauInf; delete pCondGauBNet; delete pCondGauEvid; delete pMDCondGau; return trsResult( ret, ret == TRS_OK ? "No errors" : "Bad test on RandomFactors"); }
static int arithm_test( void* arg ) { double success_error_level = 0; int param = (int)arg; int func = param / 256; int depth = (param % 256) % 8; int channels = (param % 256) / 8; int mattype; int seed = -1;//atsGetSeed(); int btpix, max_img_bytes; int merr_i = 0, i; double max_err = 0.; uchar *src1data, *src2data, *dstdata, *dstdbdata, *maskdata; CvRandState rng_state; AtsBinArithmMaskFunc bin_func = 0; AtsUnArithmMaskFunc un_func = 0; AtsBinArithmFunc mul_func = 0; CvScalar alpha, beta, gamma; CvMat gammaarr; alpha = beta = gamma = cvScalarAll(0); read_arithm_params(); if( !(ATS_RANGE( depth, dt_l, dt_h+1 ) && ATS_RANGE( channels, ch_l, ch_h+1 ))) return TRS_UNDEF; cvInitMatHeader( &gammaarr, 1, 1, CV_64FC4, gamma.val ); switch( func ) { case 0: bin_func = cvAdd; alpha = beta = cvScalarAll(1); break; case 1: bin_func = cvSub; alpha = cvScalarAll(1); beta = cvScalarAll(-1); break; case 2: mul_func = cvMul; break; case 3: un_func = cvAddS; alpha = cvScalarAll(1); break; case 4: un_func = cvSubRS; alpha = cvScalarAll(-1); break; default: assert(0); return TRS_FAIL; } mattype = depth + channels*8; depth = depth == 0 ? IPL_DEPTH_8U : depth == 1 ? IPL_DEPTH_8S : depth == 2 ? IPL_DEPTH_16S : depth == 3 ? IPL_DEPTH_32S : depth == 4 ? IPL_DEPTH_32F : IPL_DEPTH_64F; channels = channels + 1; cvRandInit( &rng_state, 0, 1, seed ); max_img_bytes = (max_img_size + 32) * (max_img_size + 2) * cvPixSize(mattype); src1data = (uchar*)cvAlloc( max_img_bytes ); src2data = (uchar*)cvAlloc( max_img_bytes ); dstdata = (uchar*)cvAlloc( max_img_bytes ); dstdbdata = (uchar*)cvAlloc( max_img_bytes ); maskdata = (uchar*)cvAlloc( max_img_bytes / cvPixSize(mattype)); btpix = ((depth & 255)/8)*channels; if( depth == IPL_DEPTH_32F ) success_error_level = FLT_EPSILON * img32f_range * (mul_func ? img32f_range : 2.f); else if( depth == IPL_DEPTH_64F ) success_error_level = DBL_EPSILON * img32f_range * (mul_func ? img32f_range : 2.f); for( i = 0; i < base_iters; i++ ) { int continuous = (cvRandNext( &rng_state ) % 3) == 0; int is_mask_op = mul_func ? 0 : ((cvRandNext( &rng_state ) % 3) == 0); int step1, step2, step, mstep; CvMat src1, src2, dst1, dst2, mask, dst; double err; int w, h; w = cvRandNext( &rng_state ) % (max_img_size - min_img_size) + min_img_size; h = cvRandNext( &rng_state ) % (max_img_size - min_img_size) + min_img_size; step1 = step2 = step = w*btpix; mstep = w; if( !continuous ) { step1 += (cvRandNext( &rng_state ) % 4)*(btpix/channels); step2 += (cvRandNext( &rng_state ) % 4)*(btpix/channels); step += (cvRandNext( &rng_state ) % 4)*(btpix/channels); mstep += (cvRandNext( &rng_state ) % 4); } switch( depth ) { case IPL_DEPTH_8U: cvRandSetRange( &rng_state, 0, img8u_range ); break; case IPL_DEPTH_8S: cvRandSetRange( &rng_state, -img8s_range, img8s_range ); break; case IPL_DEPTH_16S: cvRandSetRange( &rng_state, -img16s_range, img16s_range ); break; case IPL_DEPTH_32S: cvRandSetRange( &rng_state, -img32s_range, img32s_range ); break; case IPL_DEPTH_32F: case IPL_DEPTH_64F: cvRandSetRange( &rng_state, -img32f_range, img32f_range ); break; } cvInitMatHeader( &src1, h, w, mattype, src1data, step1 ); cvInitMatHeader( &src2, h, w, mattype, src2data, step2 ); cvInitMatHeader( &dst1, h, w, mattype, dstdata, step ); cvInitMatHeader( &dst2, h, w, mattype, dstdbdata, step ); cvInitMatHeader( &mask, h, w, CV_8UC1, maskdata, mstep ); cvRand( &rng_state, &src1 ); switch( cvRandNext(&rng_state) % 3 ) { case 0: memcpy( &dst, &src1, sizeof(dst)); break; case 1: if( un_func ) memcpy( &dst, &src1, sizeof(dst)); else memcpy( &dst, &src2, sizeof(dst)); break; default: memcpy( &dst, &dst1, sizeof(dst)); break; } if( un_func ) { if( depth == IPL_DEPTH_8U ) cvRandSetRange( &rng_state, -img8u_range, img8u_range ); cvRand( &rng_state, &gammaarr ); } else { cvRand( &rng_state, &src2 ); } if( is_mask_op ) { const int upper = 4; if( dst.data.ptr == dst1.data.ptr ) cvRand( &rng_state, &dst ); cvRandSetRange( &rng_state, 0, upper ); cvRand( &rng_state, &mask ); atsLinearFunc( &mask, cvScalarAll(1), 0, cvScalarAll(0), cvScalarAll(2-upper), &mask ); } if( !mul_func ) { atsLinearFunc( &src1, alpha, un_func ? 0 : &src2, beta, gamma, &dst2 ); if( is_mask_op ) { cvXorS( &mask, cvScalarAll(1), &mask ); cvCopy( &dst, &dst2, &mask ); cvXorS( &mask, cvScalarAll(1), &mask ); } if( un_func ) un_func( &src1, gamma, &dst, is_mask_op ? &mask : 0 ); else bin_func( &src1, &src2, &dst, is_mask_op ? &mask : 0 ); } else { atsMul( &src1, &src2, &dst2 ); mul_func( &src1, &src2, &dst ); } /*if( i == 9 ) { putchar('.'); }*/ //cvXor( &dst2, &dst, &dst2 ); err = cvNorm( &dst2, &dst, CV_C ); if( err > max_err ) { max_err = err; merr_i = i; if( max_err > success_error_level ) goto test_exit; } } test_exit: cvFree( (void**)&src1data ); cvFree( (void**)&src2data ); cvFree( (void**)&dstdata ); cvFree( (void**)&dstdbdata ); cvFree( (void**)&maskdata ); trsWrite( ATS_LST, "Max err is %g at iter = %d, seed = %08x", max_err, merr_i, seed ); return max_err <= success_error_level ? trsResult( TRS_OK, "No errors" ) : trsResult( TRS_FAIL, "Bad accuracy" ); }
template <class Val, class Idx> static int check_direct( _CvTreeNode<Val,Idx>* root ) { if( root == 0 ) return TRS_OK; int res = TRS_OK; if( root->link[_CvTreeNode<Val,Idx>::left] != 0 ) { if( root->link[_CvTreeNode<Val,Idx>::left]->idx > root->idx ) { trsWrite( ATS_CON | ATS_LST, "Wrong direct: act: left, exp: right, %d\n", (int)root->idx ); res = TRS_FAIL; } if( root->link[_CvTreeNode<Val,Idx>::left]->idx == root->idx ) { trsWrite( ATS_CON | ATS_LST, "Wrong direct: act: left, exp: no_branch, %d\n", (int)root->idx ); res = TRS_FAIL; } if( root->link[_CvTreeNode<Val,Idx>::left]->link[_CvTreeNode<Val,Idx>::up] != root ) { trsWrite( ATS_CON | ATS_LST, "Wrong link (left branch), %d\n", (int)root->idx ); res = TRS_FAIL; } } if( root->link[_CvTreeNode<Val,Idx>::right] != 0 ) { if( root->link[_CvTreeNode<Val,Idx>::right]->idx < root->idx ) { trsWrite( ATS_CON | ATS_LST, "Wrong direct: act: right, exp: left, %d\n", (int)root->idx ); res = TRS_FAIL; } if( root->link[_CvTreeNode<Val,Idx>::right]->idx == root->idx ) { trsWrite( ATS_CON | ATS_LST, "Wrong direct: act: right, exp: no_branch, %d\n", (int)root->idx ); res = TRS_FAIL; } if( root->link[_CvTreeNode<Val,Idx>::right]->link[_CvTreeNode<Val,Idx>::up] != root) { trsWrite( ATS_CON | ATS_LST, "Wrong link (right branch), %d\n", (int)root->idx ); res = TRS_FAIL; } } if( res != TRS_OK ) return res; if( check_direct( root->link[_CvTreeNode<Val,Idx>::left] ) != TRS_OK || check_direct( root->link[_CvTreeNode<Val,Idx>::right] ) != TRS_OK ) return TRS_FAIL; else return TRS_OK; }
template <class Val, class Idx> static int foaCvTree( Val, Idx ) { CvTree<Val, Idx> tree; int res = TRS_OK; /* Check adding new node (operator[]) */ for( Idx i = 0; i < hsize; i++ ) { Idx num = (Idx)atsInitRandom( 0, hsize ); tree[num] = (Val)i; if( check_direct( tree.get_root() ) != TRS_OK || check_balance( tree.get_root() ) < 0 ) { return trsResult( TRS_FAIL, "Error adding new node" ); } } /* Check getting node */ for( i = 0; i < hsize; i++ ) tree[i] = (Val)i; for( i = 0; i < hsize; i++ ) if( tree[i] != (Val)i ) { trsWrite( ATS_CON | ATS_LST, "error operator[] (get node)\n" ); res = TRS_FAIL; break; } for( i = 0; i < hsize; i++ ) if( tree.query(i) != (Val)i ) { trsWrite( ATS_CON | ATS_LST, "error query() function\n" ); res = TRS_FAIL; break; } tree.clear(); for( i = 0; i < hsize; i++ ) tree[i] = (Val)i; for( i = 0; i < hsize; i++ ) { Idx num = (Idx)atsInitRandom( 0, hsize ); tree.remove( num ); if( check_direct( tree.get_root() ) != TRS_OK || check_balance( tree.get_root() ) < 0 ) { return trsResult( TRS_FAIL, "Error removing node" ); } if( tree.query( num ) != 0 ) { trsWrite( ATS_CON | ATS_LST, "Error remove() function (not null) \n" ); res = TRS_FAIL; } } for( i = 0; i < hsize / 2; i++ ) { tree.remove( i ); if( check_direct( tree.get_root() ) != TRS_OK || check_balance( tree.get_root() ) < 0 ) { return trsResult( TRS_FAIL, "Error removing node" ); } if( tree.query( i ) != 0 ) { trsWrite( ATS_CON | ATS_LST, "Error remove() function (not null) \n" ); res = TRS_FAIL; } } for( i = hsize; i > hsize / 2 - 1; i-- ) { tree.remove( i ); if( check_direct( tree.get_root() ) != TRS_OK || check_balance( tree.get_root() ) < 0 ) { return trsResult( TRS_FAIL, "Error removing node" ); } if( tree.query( i ) != 0 ) { trsWrite( ATS_CON | ATS_LST, "Error remove() function (not null) \n" ); res = TRS_FAIL; } } tree.clear(); for( i = 0; i < hsize; i++ ) tree[i] = (Val)(i + 1); CvTree<Val, Idx>::iterator iterator = tree.begin(); if( *iterator != 1 ) { trsWrite( ATS_CON | ATS_LST, "Wrong begin() function (bad val)\n"); res = TRS_FAIL; } if( iterator.get_idx() != 0 ) { trsWrite( ATS_CON | ATS_LST, "Wrong begin() function (bad idx)\n"); res = TRS_FAIL; } iterator = tree.end(); if( *iterator != hsize ) { trsWrite( ATS_CON | ATS_LST, "Wrong end() function (bad val)\n"); res = TRS_FAIL; } if( iterator.get_idx() != hsize - 1 ) { trsWrite( ATS_CON | ATS_LST, "Wrong end() function (bad idx)\n"); res = TRS_FAIL; } CvTree<Val, Idx> empty; empty = tree; CvTree<Val, Idx>::iterator beg1 = empty.begin(); CvTree<Val, Idx>::iterator beg2 = tree.begin(); CvTree<Val, Idx>::iterator end = tree.begin(); while( beg2 != end ) { if( *beg2 != *beg1 ) { res = TRS_FAIL; trsWrite( ATS_CON | ATS_LST, "Wrong operator= (bad value)\n" ); break; } if( beg2.get_idx() != beg1.get_idx() ) { res = TRS_FAIL; trsWrite( ATS_CON | ATS_LST, "Wrong operator= (bad idx)\n" ); break; } beg1++; beg2++; } if( *beg2 != *beg1 ) { res = TRS_FAIL; trsWrite( ATS_CON | ATS_LST, "Wrong operator= (bad value)\n" ); } if( beg2.get_idx() != beg1.get_idx() ) { res = TRS_FAIL; trsWrite( ATS_CON | ATS_LST, "Wrong operator= (bad idx)\n" ); } return res; }
int testMultiplyMatrix() { int ret = TRS_OK; int i; #if 0 int range_max=5; int seed1 = pnlTestRandSeed(); /*create string to display the value*/ char *value = new char[20]; value = _itoa(seed1, value, 10); trsiRead(&seed1, value, "Seed for srand to define NodeTypes etc."); delete []value; trsWrite(TW_CON|TW_RUN|TW_DEBUG|TW_LST, "seed for rand = %d\n", seed1); srand ((unsigned int)seed1); int Nrow1 = 1+rand()%((int) range_max); int Ncol1 = 1+rand()%((int) range_max); int Nrow2=Ncol1; int Ncol2=1+rand()%((int) range_max); #endif int Nrow1 = 4; int Ncol1 = 6; int Nrow2=Ncol1; int Ncol2=5; int* ranges1 = (int*)trsGuardcAlloc( 2, sizeof(int) ); int* ranges2 = (int*)trsGuardcAlloc( 2, sizeof(int) ); ranges1[0]=Nrow1; ranges1[1]=Ncol1; ranges2[0]=Nrow2; ranges2[1]=Ncol2; int data_length1=ranges1[0]*ranges1[1]; int data_length2=ranges2[0]*ranges2[1]; float* data1 = (float*)trsGuardcAlloc( data_length1, sizeof(float) ); float* data2 = (float*)trsGuardcAlloc( data_length2, sizeof(float) ); for (i = 0; i < data_length1; data1[i] = (div(i,Ncol1).quot+1)*1.0f, i++); for (i = 0; i < data_length2; data2[i] = (div(i,Ncol2).rem+1)*0.1f, i++); C2DNumericDenseMatrix<float>* m1 = C2DNumericDenseMatrix<float>::Create( ranges1, data1); C2DNumericDenseMatrix<float>* m2 = C2DNumericDenseMatrix<float>::Create( ranges2, data2); C2DNumericDenseMatrix<float>* m3 = pnlMultiply(m1,m2,0); int data_length3; const float *m3data; m3->GetRawData(&data_length3, &m3data); float *testdata0=new float[data_length3]; int currow;int curcol; for (i = 0; i < data_length3; i++) { currow=div(i,Ncol2).quot+1; curcol=div(i,Ncol2).rem+1; testdata0[i] =currow*curcol*Ncol1*0.1f; } for(i = 0; i < data_length3; i++) { // Test the values... //printf("%3d %4.2f %4.2f\n",i, testdata0[i], m3data[i]); if(m3data[i] - testdata0[i]>eps) { return trsResult(TRS_FAIL, "data doesn't agree at max=0, preorder"); } } delete m3; m3 = pnlMultiply(m2,m1,0); m3->GetRawData(&data_length3, &m3data); for(i = 0; i < data_length3; i++) { // Test the values... //printf("%3d %4.2f %4.2f\n",i, testdata0[i], m3data[i]); if(m3data[i] - testdata0[i]>eps) { return trsResult(TRS_FAIL, "data doesn't agree at max=0, postorder"); } } #if 0 float *data4 = new float[data_length2]; for (i=0;i<data_length2;i++) { currow=div(i,Ncol2).quot+1; curcol=div(i,Ncol2).rem+1; data4[i]=currow*(1e+curcol-3f); } CNumericDenseMatrix<float> * m4=CNumericDenseMatrix<float>::Create(2,ranges2, data4); #endif delete m3; m3 = pnlMultiply(m1,m2,1); m3->GetRawData(&data_length3, &m3data); float *testdata1=new float[data_length3]; for (i = 0; i < data_length3; i++) { int currow=div(i,Ncol2).quot+1; int curcol=div(i,Ncol2).rem+1; testdata1[i] =currow*curcol*0.1f; } for(i = 0; i < data_length3; i++) { // Test the values... //printf("%3d %4.2f %4.2f\n",i, testdata1[i], m3data[i]); if(m3data[i] - testdata1[i] > eps) { return trsResult(TRS_FAIL, "data doesn't agree at max=1, preorder"); } } delete m3; m3 = pnlMultiply(m2,m1,1); m3->GetRawData(&data_length3, &m3data); for(i = 0; i < data_length3; i++) { // Test the values... //printf("%3d %4.2f %4.2f\n",i, testdata1[i], m3data[i]); if(m3data[i] - testdata1[i]>eps) { return trsResult(TRS_FAIL, "data doesn't agree at max=1, postorder"); } } int ranges1_memory_flag = trsGuardCheck( ranges1 ); int ranges2_memory_flag = trsGuardCheck( ranges2 ); int data1_memory_flag = trsGuardCheck( data1 ); int data2_memory_flag = trsGuardCheck( data2 ); trsGuardFree( ranges1 ); trsGuardFree( ranges2 ); trsGuardFree( data1 ); trsGuardFree( data2 ); if(ranges1_memory_flag || ranges2_memory_flag || data1_memory_flag|| data2_memory_flag) { return trsResult( TRS_FAIL, "Dirty memory"); } delete m1; delete m2; delete m3; delete []testdata1; delete []testdata0; return trsResult( ret, ret == TRS_OK ? "No errors" : "Bad matrix data"); }
static int foaCamShiftC1R( void* prm ) { /* Some variables */ long lParam = (long)prm; int Flvr = (lParam >> 4) & 0xf; int depth = (Flvr == ATS_8U ? IPL_DEPTH_8U : Flvr == ATS_8S ? IPL_DEPTH_8S : IPL_DEPTH_32F); int Type = lParam & 0xf; int Errors = 0; CvTermCriteria criteria; CvRect Window; CvSize roi; IplImage* src; float alpha = 0; int i; int x, y; float destOrientation = 0; float destLen = 0; float destWidth = 0; float destArea = 0; int destIters = 0; static int read_param = 0; /* Initialization global parameters */ if( !read_param ) { read_param = 1; trsiRead( &height, "512", "source array length" ); trsiRead( &width, "512", "source array width" ); trsiRead( &Length, "68", "oval length" ); trsiRead( &Width, "15", "oval width" ); trsiRead( &iter, "10", "iterations" ); trsiRead( &steps, "10", "steps" ); trssRead( &epsilon, "1", "epsilon" ); } /* Initilization */ Window.x = width / 4; Window.y = height / 4; Window.width = width / 2; Window.height = height / 2; roi.width = width; roi.height = height; criteria.type = Type; criteria.epsilon = epsilon; criteria.maxIter = iter; /* Allocating source arrays; */ src = cvCreateImage(roi, depth, 1); assert(src); for( alpha = -Pi / 2; alpha < Pi / 2; alpha += Pi / steps ) { x = (int)(width / 2 + width / 8 * cos(alpha)); y = (int)(height / 2 + height / 8 * sin(alpha)); switch( Flvr ) { case ATS_8U: atsbInitEllipse( (uchar*)src->imageData, roi.width, roi.height, src->widthStep, x, y, Length, Width, alpha, 10 ); break; case ATS_8S: atsbInitEllipse( (uchar*)src->imageData, roi.width, roi.height, src->widthStep, x, y, Length, Width, alpha, 10 ); break; case ATS_32F: atsfInitEllipse( (float*)src->imageData, roi.width, roi.height, src->widthStep, x, y, Length, Width, alpha, 10 ); break; } /* switch( Flvr ) */ putchar('.'); for( i = 0; i < steps; i++ ) { CvConnectedComp comp; CvBox2D box; destIters = cvCamShift( src, Window, criteria, &comp, &box ); Window = comp.rect; destArea = (float) comp.area; destOrientation = box.angle; destLen = box.size.height; destWidth = box.size.width; } /* Checking results */ /* Checking orientation */ if( fabs( alpha - destOrientation ) > 0.01 && fabs( alpha + Pi - destOrientation ) > 0.01 ) { Errors++; trsWrite( ATS_LST, "orientation: act: %f, exp: %f\n", destOrientation, alpha ); } /* Checking length */ if( fabs( destLen - Length * 2 ) > epsilon ) { Errors++; trsWrite( ATS_LST, "length: act: %f, exp: %d\n", destLen, Length ); } /* Checking width */ if( fabs( destWidth - Width * 2 ) > epsilon ) { Errors++; trsWrite( ATS_LST, "width: act: %f, exp: %d\n", destWidth, Width ); } } cvReleaseImage(&src); return Errors == 0 ? TRS_OK : trsResult( TRS_FAIL, "Fixed %d errors", Errors ); } /* foaCamShiftC1R */
static int aAdaptThreshold() { CvPoint *cp; int parameter1 = 3; double parameter2 = 10; int width = 128; int height = 128; int kp = 5; int nPoints2 = 20; int fi = 0; int a2 = 20; int b2 = 25,xc,yc; double pi = 3.1415926; double lower, upper; unsigned seed; char rand; AtsRandState state; long diff_binary, diff_binary_inv; int l,i,j; IplImage *imBinary, *imBinary_inv, *imTo_zero, *imTo_zero_inv, *imInput, *imOutput; CvSize size; int code = TRS_OK; // read tests params if(!trsiRead( &width, "128", "image width" )) return TRS_UNDEF; if(!trsiRead( &height, "128", "image height" )) return TRS_UNDEF; // initialized image l = width*height*sizeof(uchar); cp = (CvPoint*) trsmAlloc(nPoints2*sizeof(CvPoint)); xc = (int)( width/2.); yc = (int)( height/2.); kp = nPoints2; size.width = width; size.height = height; int xmin = width; int ymin = height; int xmax = 0; int ymax = 0; for(i=0;i<nPoints2;i++) { cp[i].x = (int)(a2*cos(2*pi*i/nPoints2)*cos(2*pi*fi/360.))- (int)(b2*sin(2*pi*i/nPoints2)*sin(2*pi*fi/360.))+xc; if(xmin> cp[i].x) xmin = cp[i].x; if(xmax< cp[i].x) xmax = cp[i].x; cp[i].y = (int)(a2*cos(2*pi*i/nPoints2)*sin(2*pi*fi/360.))+ (int)(b2*sin(2*pi*i/nPoints2)*cos(2*pi*fi/360.))+yc; if(ymin> cp[i].y) ymin = cp[i].y; if(ymax< cp[i].y) ymax = cp[i].y; } if(xmax>width||xmin<0||ymax>height||ymin<0) return TRS_FAIL; // IPL image moment calculation // create image imBinary = cvCreateImage( size, 8, 1 ); imBinary_inv = cvCreateImage( size, 8, 1 ); imTo_zero = cvCreateImage( size, 8, 1 ); imTo_zero_inv = cvCreateImage( size, 8, 1 ); imOutput = cvCreateImage( size, 8, 1 ); imInput = cvCreateImage( size, 8, 1 ); int bgrn = 50; int signal = 150; memset(imInput->imageData,bgrn,l); cvFillPoly(imInput, &cp, &kp, 1, cvScalarAll(signal)); // do noise upper = 22; lower = -upper; seed = 345753; atsRandInit( &state, lower, upper, seed ); uchar *input = (uchar*)imInput->imageData; uchar *binary = (uchar*)imBinary->imageData; uchar *binary_inv = (uchar*)imBinary_inv->imageData; uchar *to_zero = (uchar*)imTo_zero->imageData; uchar *to_zero_inv = (uchar*)imTo_zero_inv->imageData; double *parameter = (double*)trsmAlloc(2*sizeof(double)); int step = imInput->widthStep; for(i = 0; i<size.height; i++, input+=step, binary+=step, binary_inv+=step, to_zero+=step,to_zero_inv+=step) { for(j = 0; j<size.width; j++) { atsbRand8s( &state, &rand, 1); if(input[j] == bgrn) { binary[j] = to_zero[j] = (uchar)0; binary_inv[j] = (uchar)255; to_zero_inv[j] = input [j] = (uchar)(bgrn + rand); } else { binary[j] = (uchar)255; binary_inv[j] = to_zero_inv[j] = (uchar)0; to_zero[j] = input[j] = (uchar)(signal + rand); } } } cvAdaptiveThreshold( imInput, imOutput, (double)255, CV_ADAPTIVE_THRESH_MEAN_C, CV_THRESH_BINARY, parameter1, parameter2 ); diff_binary = atsCompare1Db( (uchar*)imOutput->imageData, (uchar*)imBinary->imageData, l, 5); cvAdaptiveThreshold( imInput, imOutput, (double)255, CV_ADAPTIVE_THRESH_MEAN_C, CV_THRESH_BINARY_INV, parameter1, parameter2 ); diff_binary_inv = atsCompare1Db( (uchar*)imOutput->imageData, (uchar*)imBinary_inv->imageData, l, 5); if( diff_binary > 5 || diff_binary_inv > 5 ) code = TRS_FAIL; cvReleaseImage(&imInput); cvReleaseImage(&imOutput); cvReleaseImage(&imBinary); cvReleaseImage(&imBinary_inv); cvReleaseImage(&imTo_zero); cvReleaseImage(&imTo_zero_inv); trsWrite( ATS_CON | ATS_LST | ATS_SUM, "diff_binary =%ld \n", diff_binary); trsWrite( ATS_CON | ATS_LST | ATS_SUM, "diff_binary_inv =%ld \n", diff_binary_inv); trsFree(parameter); trsFree(cp); return code; }
static int aMatchContourTrees(void) { CvSeqBlock contour_blk1, contour_blk2; CvContour contour_h1, contour_h2; CvContourTree *tree1, *tree2; CvMemStorage *storage; /* storage for contour and tree writing */ int block_size = 10000; CvRandState state; double lower, upper; int seed; float fr; int type_seq; int method; int nPoints1 = 12, nPoints2 = 12; int xc,yc,a1 = 10, b1 = 20, a2 = 10, b2 =20, fi = 0; int xmin,ymin,xmax,ymax; double error_test,rezult, eps_rez = 0.8; double pi = 3.1415926; double threshold = 1.e-7; double threshold2 = 5.; int i; int code = TRS_OK; int width=256,height=256; CvPoint *cp1,*cp2; /* read tests params */ if (!trsiRead(&nPoints1,"20","Number of points first contour")) return TRS_UNDEF; if (!trsiRead(&nPoints2,"20","Number of points second contour")) return TRS_UNDEF; if(nPoints1>0&&nPoints2>0) { if (!trsiRead(&a1,"10","first radius of the first elipse")) return TRS_UNDEF; if (!trsiRead(&b1,"20","second radius of the first elipse")) return TRS_UNDEF; if (!trsiRead(&a2,"15","first radius of the second elipse")) return TRS_UNDEF; if (!trsiRead(&b2,"30","second radius of the second elipse")) return TRS_UNDEF; if (!trsiRead(&fi,"0","second radius of the second elipse")) return TRS_UNDEF; if (!trsdRead(&upper,"3","noise amplidude")) return TRS_UNDEF; xc = (int)(width/2.); yc = (int)(height/2.); xmin = width; ymin = height; xmax = 0; ymax = 0; cp1 = (CvPoint*) trsmAlloc(nPoints1*sizeof(CvPoint)); cp2 = (CvPoint*) trsmAlloc(nPoints2*sizeof(CvPoint)); for(i=0; i<nPoints1; i++) { cp1[i].x = (int)(a1*cos(2*pi*i/nPoints1))+xc; cp1[i].y = (int)(b1*sin(2*pi*i/nPoints1))+yc; if(xmin> cp1[i].x) xmin = cp1[i].x; if(xmax< cp1[i].x) xmax = cp1[i].x; if(ymin> cp1[i].y) ymin = cp1[i].y; if(ymax< cp1[i].y) ymax = cp1[i].y; } if(xmax>width||xmin<0||ymax>height||ymin<0) return TRS_FAIL; lower = -upper; /* upper = 3;*/ seed = 345753; cvRandInit(&state, (float)lower,(float)upper, seed ); for(i=0; i<nPoints2; i++) { cvbRand( &state, &fr, 1 ); cp2[i].x =(int)fr+(int)(a2*cos(2*pi*i/nPoints2)*cos(2*pi*fi/360.))- (int)(b2*sin(2*pi*i/nPoints2)*sin(2*pi*fi/360.))+xc; cvbRand( &state, &fr, 1 ); cp2[i].y =(int)fr+(int)(a2*cos(2*pi*i/nPoints2)*sin(2*pi*fi/360.))+ (int)(b2*sin(2*pi*i/nPoints2)*cos(2*pi*fi/360.))+yc; if(xmin> cp2[i].x) xmin = cp2[i].x; if(xmax< cp2[i].x) xmax = cp2[i].x; if(ymin> cp2[i].y) ymin = cp2[i].y; if(ymax< cp2[i].y) ymax = cp2[i].y; } if(xmax>width||xmin<0||ymax>height||ymin<0) return TRS_FAIL; /* contours initialazing */ type_seq = CV_SEQ_POLYGON; cvMakeSeqHeaderForArray( type_seq, sizeof(CvContour), sizeof(CvPoint), (char*)cp1, nPoints1, (CvSeq*)&contour_h1, &contour_blk1); cvMakeSeqHeaderForArray( type_seq, sizeof(CvContour), sizeof(CvPoint), (char*)cp2, nPoints2, (CvSeq*)&contour_h2, &contour_blk2); /* contour trees created*/ storage = cvCreateMemStorage( block_size ); tree1 = cvCreateContourTree ((CvSeq*)&contour_h1, storage, threshold); tree2 = cvCreateContourTree ((CvSeq*)&contour_h2, storage, threshold); /* countours matchig */ error_test = 0.; method = 1; rezult = cvMatchContourTrees (tree1, tree2, (CvContourTreesMatchMethod)method,threshold2); error_test+=rezult; if(error_test > eps_rez ) code = TRS_FAIL; else code = TRS_OK; trsWrite( ATS_CON | ATS_LST | ATS_SUM, "contours matching error_test =%f \n", error_test); cvReleaseMemStorage ( &storage ); trsFree (cp2); trsFree (cp1); } /* _getch(); */ return code; }
int testShrinkObservedNodes() { int i/*,j*/; int ret = TRS_OK; /*prepare to read the values from console*/ EDistributionType dt; int disType = -1; EFactorType pt; int paramType = -1; /*read int disType corresponding DistributionType*/ while((disType<0)||(disType>0))/*now we have only Tabulars&Gaussian*/ { trsiRead( &disType, "0", "DistributionType"); } /*read int paramType corresponding FactorType*/ while((paramType<0)||(paramType>2)) { trsiRead( ¶mType, "0", "FactorType"); } dt = EDistributionType(disType); pt = EFactorType(paramType); int numberOfNodes = 0; /*read number of nodes in Factor domain*/ while(numberOfNodes<=0) { trsiRead( &numberOfNodes, "1", "Number of Nodes in domain"); } int numNodeTypes = 0; /*read number of node types in model*/ while(numNodeTypes<=0) { trsiRead( &numNodeTypes, "1", "Number of node types in Domain"); } //int seed1 = pnlTestRandSeed()/*%100000*/; /*create string to display the value*/ /* char *value = new char[20]; value = _itoa(seed1, value, 10); trsiRead(&seed1, value, "Seed for srand to define NodeTypes etc."); delete []value; trsWrite(TW_CON|TW_RUN|TW_DEBUG|TW_LST, "seed for rand = %d\n", seed1); int *domain = (int *)trsGuardcAlloc(numberOfNodes, sizeof(int)); CNodeType * allNodeTypes = (CNodeType*)trsGuardcAlloc(numNodeTypes, sizeof(CNodeType)); //To generate the NodeTypes we use rand()% and creates only Tabular now for(i=0; i<numNodeTypes; i++) { allNodeTypes[i] = CNodeType(1, 1+rand()%(numNodeTypes+3)); } */ /*load data for parameter::ShrinkObservedNodes from console*/ intVector domain; domain.assign( numberOfNodes, 0 ); nodeTypeVector allNodeTypes; allNodeTypes.assign( numNodeTypes, CNodeType() ); /*read node types*/ for(i=0; i < numNodeTypes; i++) { int IsDiscrete = -1; int NodeSize = -1; while((IsDiscrete<0)||(IsDiscrete>1)) /*now we have tabular & Gaussian nodes!! */ trsiRead(&IsDiscrete, "1", "Is the node discrete?"); while(NodeSize<0) trsiRead(&NodeSize, "2", "NodeSize of node"); allNodeTypes[i] = CNodeType( IsDiscrete != 0, NodeSize ); } const CNodeType **nodeTypesOfDomain = (const CNodeType**) trsGuardcAlloc(numberOfNodes, sizeof(CNodeType*)); int numData = 1; int *Ranges = (int*)trsGuardcAlloc(numberOfNodes, sizeof(int)); /*associate nodes to node types*/ for(i=0; i<numberOfNodes; i++) { domain[i] = i; int nodeAssociationToNodeType = -1; while((nodeAssociationToNodeType<0)||(nodeAssociationToNodeType>= numNodeTypes)) trsiRead(&nodeAssociationToNodeType, "0", "node i has type nodeAssociationToNodeType"); nodeTypesOfDomain[i] = &allNodeTypes[nodeAssociationToNodeType]; // nodeTypesOfDomain[i] = &allNodeTypes[rand()%numNodeTypes]; Ranges[i] = nodeTypesOfDomain[i]->GetNodeSize(); numData=numData*Ranges[i]; } CModelDomain* pMD = CModelDomain::Create( allNodeTypes, domain ); /*create factor according all information*/ CFactor *pMyParam = NULL; float *data = (float *)trsGuardcAlloc(numData, sizeof(float)); char *stringVal;/* = (char*)trsGuardcAlloc(50, sizeof(char));*/ double val=0; /*read the values from console*/ if(pt == ftPotential) { pMyParam = CTabularPotential::Create( &domain.front(), numberOfNodes, pMD ); /*here we can create data by multiply on 0.1 - numbers are nonnormalized*/ for(i=0; i<numData; i++) { val = 0.1*i; stringVal = trsDouble(val); trsdRead(&val, stringVal, "value of i's data position"); data[i] = (float)val; //data[i] = (float)rand()/1000; } } else { /*we can only read data from console - it must be normalized!! (according their dimensions) - or we can normalize it by function!*/ if(pt == ftCPD) pMyParam = CTabularCPD::Create( &domain.front(), numberOfNodes, pMD ); for(i=0; i<numData; i++) { val = -1; while((val<0)||(val>1)) { trsdRead(&val, "-1", "value of (2*i)'s data position"); } data[i] = (float)val; } } //trsWrite(TW_CON|TW_RUN|TW_DEBUG|TW_LST, "data for Factor = %d\n", data[i]); pMyParam->AllocMatrix(data,matTable); int nObsNodes = 0; /*rand()%numberOfNodes;*/ while((nObsNodes<=0)||(nObsNodes>numberOfNodes)) { trsiRead(&nObsNodes, "1", "Number of Observed Nodes"); } intVector myHelpForEvidence = intVector(domain.begin(), domain.end() ); int *ObsNodes = (int *)trsGuardcAlloc(nObsNodes, sizeof(int)); valueVector TabularValues; TabularValues.assign( nObsNodes, (Value)0 ); char *strVal; for(i=0; i<nObsNodes; i++) { //fixme - we need to have noncopy only different ObsNodes /* j = rand()%(numberOfNodes-i);*/ int numberOfObsNode = -1; strVal = trsInt(i); intVector::iterator j = std::find( myHelpForEvidence.begin(), myHelpForEvidence.end(), numberOfObsNode ); while((numberOfObsNode<0)||(numberOfObsNode>numberOfNodes)|| (j==myHelpForEvidence.end())) { trsiRead(&numberOfObsNode, strVal,"Number of i's observed node"); j = std::find(myHelpForEvidence.begin(), myHelpForEvidence.end(), numberOfObsNode); } //ObsNodes[i] = myHelpForEvidence[j]; myHelpForEvidence.erase( j ); ObsNodes[i] = numberOfObsNode; int valueOfNode = -1; int maxValue = (*nodeTypesOfDomain[ObsNodes[i]]).GetNodeSize(); while((valueOfNode<0)||(valueOfNode>=maxValue)) { trsiRead(&valueOfNode,"0","this is i's observed node value"); } TabularValues[i].SetInt(valueOfNode); /*rand()%((*nodeTypesOfDomain[ObsNodes[i]]).pgmGetNodeSize());*/ } CEvidence* pEvidence = CEvidence::Create( pMD, nObsNodes, ObsNodes, TabularValues ); myHelpForEvidence.clear(); CNodeType *ObservedNodeType = (CNodeType*)trsGuardcAlloc(1, sizeof(CNodeType)); *ObservedNodeType = CNodeType(1,1); CPotential *myTakedInFactor = static_cast<CPotential*>(pMyParam)->ShrinkObservedNodes(pEvidence); const int *myfactorDomain; int factorDomSize ; myTakedInFactor->GetDomain(&factorDomSize, &myfactorDomain); #if 0 CNumericDenseMatrix<float> *mySmallMatrix = static_cast< CNumericDenseMatrix<float>*>(myTakedInFactor->GetMatrix(matTable)); int n; const float* mySmallData; mySmallMatrix->GetRawData(&n, &mySmallData); int nDims; // = mySmallMatrix->GetNumberDims(); const int * mySmallRanges; mySmallMatrix->GetRanges(&nDims, &mySmallRanges); if(nDims!=numberOfNodes) { ret = TRS_FAIL; trsWrite(TW_CON|TW_RUN|TW_DEBUG|TW_LST, "nDims = %d\n", nDims); } else { int numSmallData = 1; for(i=0; i<nDims; i++) { numSmallData = numSmallData*mySmallRanges[i]; trsWrite(TW_CON|TW_RUN|TW_DEBUG|TW_LST, "Range[%d] = %d\n", i, mySmallRanges[i]); } for(i=0; i<numSmallData; i++) { trsWrite(TW_CON|TW_RUN|TW_DEBUG|TW_LST, "mySmallData[%d] = %f ", i, mySmallData[i]); } } #endif //getchar(); delete(myTakedInFactor); delete (pMyParam); delete pMD; //test gaussian parameter nodeTypeVector nTypes; nTypes.assign( 2, CNodeType() ); nTypes[0] = CNodeType( 0, 2 ); nTypes[1] = CNodeType( 0,1 ); intVector domn = intVector(3,0); domn[1] = 1; domn[2] = 1; CModelDomain* pMD1 = CModelDomain::Create( nTypes, domn ); domn[2] = 2; CPotential *BigFactor = CGaussianPotential::CreateUnitFunctionDistribution( &domn.front(), domn.size(), pMD1,0 ); float mean[] = { 1.0f, 3.2f}; CPotential *SmallDelta = CGaussianPotential::CreateDeltaFunction( &domn.front(), 1, pMD1, mean, 1 ); domn.resize( 2 ); domn[0] = 1; domn[1] = 2; CPotential *SmallFunct = CGaussianPotential::Create( &domn.front(), domn.size(), pMD1); float datH[] = { 1.1f, 2.2f, 3.3f }; float datK[] = { 1.2f, 2.3f, 2.3f, 3.4f, 5.6f, 6.7f, 3.4f, 6.7f, 9.0f }; SmallFunct->AllocMatrix( datH, matH ); SmallFunct->AllocMatrix( datK, matK ); static_cast<CGaussianPotential*>(SmallFunct)->SetCoefficient( 0.2f, 1 ); CPotential* multFact = BigFactor->Multiply( SmallDelta ); CPotential* nextMultFact = multFact->Multiply( SmallFunct ); domn[0] = 0; domn[1] = 1; CPotential *marginalized = static_cast<CPotential*>(nextMultFact->Marginalize( &domn.front(), domn.size() )); int isSpecific = marginalized->IsDistributionSpecific(); if( isSpecific ) { trsWrite(TW_CON|TW_RUN|TW_DEBUG|TW_LST, "\nGaussian Distribution is specific"); } delete BigFactor; delete SmallFunct; delete SmallDelta; delete pMD1; int ranges_memory_flag = trsGuardCheck(Ranges); int data_memory_flag = trsGuardCheck(data); int nodeTypesOfDomain_mem_b = trsGuardCheck(nodeTypesOfDomain); int ObsNodes_mem_b = trsGuardCheck(ObsNodes); int ObsNodeType_mem_b = trsGuardCheck(ObservedNodeType); if(((ranges_memory_flag)||(data_memory_flag)|| (nodeTypesOfDomain_mem_b)|| (ObsNodes_mem_b)||(ObsNodeType_mem_b))) { ret = TRS_FAIL; return trsResult( ret, ret == TRS_OK ? "No errors" : "Bad test on ShrinkObservedNodes Method - memory"); } else { trsGuardFree(ObservedNodeType); trsGuardFree(ObsNodes); trsGuardFree(nodeTypesOfDomain); trsGuardFree(data); trsGuardFree(Ranges); } return trsResult( ret, ret == TRS_OK ? "No errors" : "Bad test on ShrinkObservedNodes Method"); }
int testNormalizePotential() { int ret = TRS_OK; int seed1 = pnlTestRandSeed(); /*create string to display the value*/ char *value = new char[20]; #if 0 value = _itoa(seed1, value, 10); #else sprintf( value, "%d", seed1 ); #endif trsiRead(&seed1, value, "Seed for srand to define NodeTypes etc."); delete []value; trsWrite(TW_CON|TW_RUN|TW_DEBUG|TW_LST, "seed for rand = %d\n", seed1); srand ((unsigned int)seed1); int a1 = 2+rand()%((int) 20); const int nnodes = a1; const int numnt = 2; intVector nodeAssociation; nodeAssociation.assign( nnodes, 0 ); nodeTypeVector nodeTypes; nodeTypes.assign( numnt, CNodeType() ); nodeTypes[0].SetType(1, 1); nodeTypes[1].SetType(1, 2); int * domain = (int*)trsGuardcAlloc( nnodes, sizeof(int) ); int Nlength = 1; for (int i2=0; i2 < nnodes; i2++) { int n = rand()%((int) numnt); nodeAssociation[i2] = n; domain[i2] = i2; Nlength = Nlength *(n+1); } CModelDomain* pMD = CModelDomain::Create( nodeTypes,nodeAssociation); float * data = (float*)trsGuardcAlloc( Nlength, sizeof(float) ); for (int i0=0; i0 < Nlength; data[i0]=1, i0++){}; EMatrixType mType=matTable; CTabularPotential *pxFactor = CTabularPotential::Create( domain, nnodes, pMD); pxFactor->AllocMatrix(data, mType); CPotential *pxFactor_res=pxFactor->GetNormalized() ; const CNumericDenseMatrix<float> *pxMatrix=static_cast< CNumericDenseMatrix<float>*>(pxFactor_res->GetMatrix(mType)); const float* dmatrix1 = (const float*)trsGuardcAlloc( Nlength, sizeof(float) ); int n; pxMatrix->GetRawData(&n, &dmatrix1); float *testdata = new float[Nlength]; for (int k1=0; k1 < Nlength; testdata[k1]=1.0f/Nlength, k1++); for(int j = 0; j < Nlength; j++) { // Test the values... //printf("%3d %4.2f %4.2f\n", j, dmatrix1[j], testdata[j] ); if(fabs(testdata[j] - dmatrix1[j]) > eps ) { return trsResult(TRS_FAIL, "data doesn't agree at max=0"); } } int data_memory_flag = trsGuardCheck( data); int domain_memory_flag = trsGuardCheck( domain ); trsGuardFree( data ); trsGuardFree( domain ); if(data_memory_flag || domain_memory_flag ) { return trsResult( TRS_FAIL, "Dirty memory"); } delete [] testdata; delete pxFactor; delete pxFactor_res; delete pMD; return trsResult( ret, ret == TRS_OK ? "No errors" : "Normalize FAILED"); }
static int aGestureRecognition(void) { IplImage *image, *imagew, *image_rez, *mask_rez, *image_hsv, *img_p[2],*img_v, *init_mask_ver = 0, *final_mask_ver = 0; CvPoint3D32f *pp, p; CvPoint pt; CvSize2D32f fsize; CvPoint3D32f center, cf; IplImage *image_mask, *image_maskw; CvSize size; CvHistogram *hist, *hist_mask; int width, height; int k_points, k_indexs; int warpFlag, interpolate; int hdim[2] = {20, 20}; double coeffs[3][3], rect[2][2], rez = 0, eps_rez = 2.5, rez_h; float *thresh[2]; float hv[3]; float reps, aeps, ww; float line[6], in[3][3], h[3][3]; float cx, cy, fx, fy; static char num[4]; char *name_image; char *name_range_image; char *name_verify_data; char *name_init_mask_very; char *name_final_mask_very; CvSeq *numbers; CvSeq *points; CvSeq *indexs; CvMemStorage *storage; CvRect hand_roi, hand_roi_trans; int i,j, lsize, block_size = 1000, flag; int code; FILE *filin, *fil_ver; /* read tests params */ code = TRS_OK; /* define input information */ strcpy (num, "001"); lsize = strlen(data_path)+12; name_verify_data = (char*)trsmAlloc(lsize); name_range_image = (char*)trsmAlloc(lsize); name_image = (char*)trsmAlloc(lsize); name_init_mask_very = (char*)trsmAlloc(lsize); name_final_mask_very = (char*)trsmAlloc(lsize); /* define input range_image file path */ strcpy(name_range_image, data_path); strcat(name_range_image, "rpts"); strcat(name_range_image, num); strcat(name_range_image, ".txt"); /* define input image file path */ strcpy(name_image, data_path); strcat(name_image, "real"); strcat(name_image, num); strcat(name_image, ".bmp"); /* define verify data file path */ strcpy(name_verify_data, data_path); strcat(name_verify_data, "very"); strcat(name_verify_data, num); strcat(name_verify_data, ".txt"); /* define verify init mask file path */ strcpy(name_init_mask_very, data_path); strcat(name_init_mask_very, "imas"); strcat(name_init_mask_very, num); strcat(name_init_mask_very, ".bmp"); /* define verify final mask file path */ strcpy(name_final_mask_very, data_path); strcat(name_final_mask_very, "fmas"); strcat(name_final_mask_very, num); strcat(name_final_mask_very, ".bmp"); filin = fopen(name_range_image,"r"); fil_ver = fopen(name_verify_data,"r"); fscanf( filin, "\n%d %d\n", &width, &height); printf("width=%d height=%d reading testing data...", width,height); OPENCV_CALL( storage = cvCreateMemStorage ( block_size ) ); OPENCV_CALL( points = cvCreateSeq( CV_SEQ_POINT3D_SET, sizeof(CvSeq), sizeof(CvPoint3D32f), storage ) ); OPENCV_CALL (indexs = cvCreateSeq( CV_SEQ_POINT_SET, sizeof(CvSeq), sizeof(CvPoint), storage ) ); pp = 0; /* read input image from file */ image = atsCreateImageFromFile( name_image ); if(image == NULL) {code = TRS_FAIL; goto m_exit;} /* read input 3D points from input file */ for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { fscanf( filin, "%f %f %f\n", &p.x, &p.y, &p.z); if(/*p.x != 0 || p.y != 0 ||*/ p.z != 0) { OPENCV_CALL(cvSeqPush(points, &p)); pt.x = j; pt.y = i; OPENCV_CALL(cvSeqPush(indexs, &pt)); } } } k_points = points->total; k_indexs = indexs->total; /* convert sequence to array */ pp = (CvPoint3D32f*)trsmAlloc(k_points * sizeof(CvPoint3D32f)); OPENCV_CALL(cvCvtSeqToArray(points, pp )); /* find 3D-line */ reps = (float)0.1; aeps = (float)0.1; ww = (float)0.08; OPENCV_CALL( cvFitLine3D(pp, k_points, CV_DIST_WELSCH, &ww, reps, aeps, line )); /* find hand location */ flag = -1; fsize.width = fsize.height = (float)0.22; // (hand size in m) numbers = NULL; OPENCV_CALL( cvFindHandRegion (pp, k_points, indexs,line, fsize, flag,¢er,storage, &numbers)); /* read verify data */ fscanf( fil_ver, "%f %f %f\n", &cf.x, &cf.y, &cf.z); rez+= cvSqrt((center.x - cf.x)*(center.x - cf.x)+(center.y - cf.y)*(center.y - cf.y)+ (center.z - cf.z)*(center.z - cf.z))/3.; /* create hand mask */ size.height = height; size.width = width; OPENCV_CALL( image_mask = cvCreateImage(size, IPL_DEPTH_8U, 1) ); OPENCV_CALL( cvCreateHandMask(numbers, image_mask, &hand_roi) ); /* read verify initial image mask */ init_mask_ver = atsCreateImageFromFile( name_init_mask_very ); if(init_mask_ver == NULL) {code = TRS_FAIL; goto m_exit;} rez+= iplNorm(init_mask_ver, image_mask, IPL_L2) / (width*height+0.); /* calculate homographic transformation matrix */ cx = (float)(width / 2.); cy = (float)(height / 2.); fx = fy = (float)571.2048; /* define intrinsic camera parameters */ in[0][1] = in[1][0] = in[2][0] = in[2][1] = 0; in[0][0] = fx; in[0][2] = cx; in[1][1] = fy; in[1][2] = cy; in[2][2] = 1; OPENCV_CALL( cvCalcImageHomography(line, ¢er, in, h) ); rez_h = 0; for(i=0;i<3;i++) { fscanf( fil_ver, "%f %f %f\n", &hv[0], &hv[1], &hv[2]); for(j=0;j<3;j++) { rez_h+=(hv[j] - h[i][j])*(hv[j] - h[i][j]); } } rez+=sqrt(rez_h)/9.; /* image unwarping */ size.width = image->width; size.height = image->height; OPENCV_CALL( imagew = cvCreateImage(size, IPL_DEPTH_8U,3) ); OPENCV_CALL( image_maskw = cvCreateImage(size, IPL_DEPTH_8U,1) ); iplSet(image_maskw, 0); cvSetImageROI(image, hand_roi); cvSetImageROI(image_mask, hand_roi); /* convert homographic transformation matrix from float to double */ for(i=0;i<3;i++) for(j=0;j<3;j++) coeffs[i][j] = (double)h[i][j]; /* get bounding rectangle for image ROI */ iplGetPerspectiveBound(image, coeffs, rect); width = (int)(rect[1][0] - rect[0][0]); height = (int)(rect[1][1] - rect[0][1]); hand_roi_trans.x = (int)rect[0][0];hand_roi_trans.y = (int)rect[0][1]; hand_roi_trans.width = width; hand_roi_trans.height = height; cvMaxRect(&hand_roi, &hand_roi_trans, &hand_roi); iplSetROI((IplROI*)image->roi, 0, hand_roi.x, hand_roi.y, hand_roi.width,hand_roi.height); iplSetROI((IplROI*)image_mask->roi, 0, hand_roi.x, hand_roi.y, hand_roi.width,hand_roi.height); warpFlag = IPL_WARP_R_TO_Q; /* interpolate = IPL_INTER_CUBIC; */ /* interpolate = IPL_INTER_NN; */ interpolate = IPL_INTER_LINEAR; iplWarpPerspective(image, imagew, coeffs, warpFlag, interpolate); iplWarpPerspective(image_mask, image_maskw, coeffs, warpFlag, IPL_INTER_NN); /* set new image and mask ROI after transformation */ iplSetROI((IplROI*)imagew->roi,0, (int)rect[0][0], (int)rect[0][1],(int)width,(int)height); iplSetROI((IplROI*)image_maskw->roi,0, (int)rect[0][0], (int)rect[0][1],(int)width,(int)height); /* copy image ROI to new image and resize */ size.width = width; size.height = height; image_rez = cvCreateImage(size, IPL_DEPTH_8U,3); mask_rez = cvCreateImage(size, IPL_DEPTH_8U,1); iplCopy(imagew,image_rez); iplCopy(image_maskw,mask_rez); /* convert rezult image from RGB to HSV */ image_hsv = iplCreateImageHeader(3, 0, IPL_DEPTH_8U, "HSV", "HSV", IPL_DATA_ORDER_PIXEL, IPL_ORIGIN_TL,IPL_ALIGN_DWORD, image_rez->width, image_rez->height, NULL, NULL, NULL, NULL); iplAllocateImage(image_hsv, 0, 0 ); strcpy(image_rez->colorModel, "RGB"); strcpy(image_rez->channelSeq, "RGB"); image_rez->roi = NULL; iplRGB2HSV(image_rez, image_hsv); /* convert to three images planes */ img_p[0] = cvCreateImage(size, IPL_DEPTH_8U,1); img_p[1] = cvCreateImage(size, IPL_DEPTH_8U,1); img_v = cvCreateImage(size, IPL_DEPTH_8U,1); cvCvtPixToPlane(image_hsv, img_p[0], img_p[1], img_v, NULL); /* calculate histograms */ hist = cvCreateHist ( 2, hdim, CV_HIST_ARRAY); hist_mask = cvCreateHist ( 2, hdim, CV_HIST_ARRAY); /* install histogram threshold */ thresh[0] = (float*) trsmAlloc(2*sizeof(float)); thresh[1] = (float*) trsmAlloc(2*sizeof(float)); thresh[0][0] = thresh[1][0] = -0.5; thresh[0][1] = thresh[1][1] = 255.5; cvSetHistThresh( hist, thresh, 1); cvSetHistThresh( hist_mask, thresh, 1); cvCalcHist(img_p, hist, 0); cvCalcHistMask(img_p, mask_rez, hist_mask, 0); cvCalcProbDensity(hist, hist_mask, hist_mask); cvCalcBackProject( img_p, mask_rez, hist_mask ); /* read verify final image mask */ final_mask_ver = atsCreateImageFromFile( name_final_mask_very ); if(final_mask_ver == NULL) {code = TRS_FAIL; goto m_exit;} rez+= iplNorm(final_mask_ver, mask_rez, IPL_L2) / (width*height+0.); trsWrite( ATS_CON | ATS_SUM, "\n gesture recognition \n"); trsWrite( ATS_CON | ATS_SUM, "result testing error = %f \n",rez); if(rez > eps_rez) code = TRS_FAIL; else code = TRS_OK; m_exit: cvReleaseImage(&image_mask); cvReleaseImage(&mask_rez); cvReleaseImage(&image_rez); atsReleaseImage(final_mask_ver); atsReleaseImage(init_mask_ver); cvReleaseImage(&imagew); cvReleaseImage(&image_maskw); cvReleaseImage(&img_p[0]); cvReleaseImage(&img_p[1]); cvReleaseImage(&img_v); cvReleaseHist( &hist); cvReleaseHist( &hist_mask); cvReleaseMemStorage ( &storage ); trsFree(pp); trsFree(name_final_mask_very); trsFree(name_init_mask_very); trsFree(name_image); trsFree(name_range_image); trsFree(name_verify_data); fclose(filin); fclose(fil_ver); /* _getch(); */ return code; }
static int aPyrSegmentation(void* agr) { CvPoint _cp[] ={33,33, 43,33, 43,43, 33,43}; CvPoint _cp2[] ={50,50, 70,50, 70,70, 50,70}; CvPoint* cp = _cp; CvPoint* cp2 = _cp2; CvConnectedComp *dst_comp[3]; CvRect rect[3] = {50,50,21,21, 0,0,128,128, 33,33,11,11}; double a[3] = {441.0, 15822.0, 121.0}; /* ippiPoint cp3[] ={130,130, 150,130, 150,150, 130,150}; */ /* CvPoint cp[] ={0,0, 5,5, 5,0, 10,5, 10,0, 15,5, 15,0}; */ int chanels = (int)agr; /* number of the color chanels */ int width = 128; int height = 128; int nPoints = 4; int block_size = 1000; int color1 = 30, color2 = 110, color3 = 180; int level = 5; long diff, l; int code; CvMemStorage *storage; /* storage for connected component writing */ CvSeq *comp; double lower, upper; unsigned seed; char rand; AtsRandState state; int i,j; IplImage *image, *image_f, *image_s; CvSize size; uchar *f_cur, *f_row; uchar *row; uchar *cur; int threshold1, threshold2; code = TRS_OK; if(chanels != 1 && chanels != 3) return TRS_UNDEF; /* read tests params */ if(!trsiRead( &width, "128", "image width" )) return TRS_UNDEF; if(!trsiRead( &height, "128", "image height" )) return TRS_UNDEF; if(!trsiRead( &level, "5", "pyramid level" )) return TRS_UNDEF; /* create Image */ l = width*height; size.width = width; size.height = height; rect[1].height = height; rect[1].width = width; a[1] = l - a[0] - a[2]; image = cvCreateImage(cvSize(size.width, size.height), IPL_DEPTH_8U, chanels); image_s = cvCreateImage(cvSize(size.width, size.height), IPL_DEPTH_8U, chanels); memset(image->imageData, color1, chanels*l); image_f = cvCreateImage(cvSize(size.width, size.height), IPL_DEPTH_8U, chanels); OPENCV_CALL( storage = cvCreateMemStorage( block_size ) ); /* do noise */ upper = 20; lower = -upper; seed = 345753; atsRandInit( &state, lower, upper, seed ); /* segmentation by pyramid */ threshold1 = 50; threshold2 = 50; switch(chanels) { case 1: { cvFillPoly( image, &cp, &nPoints, 1, color2); cvFillPoly( image, &cp2, &nPoints, 1, color3); row = (uchar*)image->imageData; f_row = (uchar*)image_f->imageData; for(i = 0; i<size.height; i++) { cur = row; f_cur = f_row; for(j = 0; j<size.width; j++) { atsbRand8s( &state, &rand, 1); *(f_cur)=(uchar)((*cur) + rand); cur++; f_cur++; } row+=image->widthStep; f_row+=image_f->widthStep; } cvPyrSegmentation( image_f, image_s, storage, &comp, level, threshold1, threshold2 ); //if(comp->total != 3) { code = TRS_FAIL; goto exit; } /* read the connected components */ /*dst_comp[0] = (CvConnectedComp*)CV_GET_SEQ_ELEM( CvConnectedComp, comp, 0 ); dst_comp[1] = (CvConnectedComp*)CV_GET_SEQ_ELEM( CvConnectedComp, comp, 1 ); dst_comp[2] = (CvConnectedComp*)CV_GET_SEQ_ELEM( CvConnectedComp, comp, 2 );*/ break; } case 3: { cvFillPoly( image, &cp, &nPoints, 1, CV_RGB(color2,color2,color2)); cvFillPoly( image, &cp2, &nPoints, 1, CV_RGB(color3,color3,color3)); row = (uchar*)image->imageData; f_row = (uchar*)image_f->imageData; for(i = 0; i<size.height; i++) { cur = row; f_cur = f_row; for(j = 0; j<size.width; j++) { atsbRand8s( &state, &rand, 1); *(f_cur)=(uchar)((*cur) + rand); atsbRand8s( &state, &rand, 1); *(f_cur+1)=(uchar)(*(cur+1) + rand); atsbRand8s( &state, &rand, 1); *(f_cur+2)=(uchar)(*(cur+2) + rand); cur+=3; f_cur+=3; } row+=image->widthStep; f_row+=image_f->widthStep; } cvPyrSegmentation(image_f, image_s, storage, &comp, level, threshold1, threshold2); /* read the connected components */ if(comp->total != 3) { code = TRS_FAIL; goto exit; } dst_comp[0] = (CvConnectedComp*)CV_GET_SEQ_ELEM( CvConnectedComp, comp, 0 ); dst_comp[1] = (CvConnectedComp*)CV_GET_SEQ_ELEM( CvConnectedComp, comp, 1 ); dst_comp[2] = (CvConnectedComp*)CV_GET_SEQ_ELEM( CvConnectedComp, comp, 2 ); break; } } diff = 0; /*diff = atsCompare1Db( (uchar*)image->imageData, (uchar*)image_s->imageData, chanels*l, 4); for(i = 0; i < 3; i++) { if(dst_comp[i]->area != a[i]) diff++; if(dst_comp[i]->rect.x != rect[i].x) diff++; if(dst_comp[i]->rect.y != rect[i].y) diff++; if(dst_comp[i]->rect.width != rect[i].width) diff++; if(dst_comp[i]->rect.height != rect[i].height) diff++; }*/ trsWrite( ATS_CON | ATS_LST | ATS_SUM, "upper =%f diff =%ld \n",upper, diff); if(diff > 0 ) code = TRS_FAIL; else code = TRS_OK; exit: cvReleaseMemStorage( &storage ); cvReleaseImage(&image_f); cvReleaseImage(&image); cvReleaseImage(&image_s); /* trsFree(cp); */ /* _getch(); */ return code; }
/* ///////////////////// moments_test ///////////////////////// */ static int moments_test( void* arg ) { static double weight[] = { 1e6, 1e6, 1e6, /* m00, m10, m01 */ 1e6, 1e6, 1e6, 1, 1, 1, 1, /* m20 - m03 */ 1, 1e-4, 1, 1e-5, 1e-5, 1e-5, 1e-5, /* mu20 - mu03 */ 1, 1, 1, 1, 1, 1, 1 }; /* nu20 - nu03 */ const double success_error_level = 1e-4; int param = (int)arg; int binary = param >= 6; int depth = (param % 6)/2; int channels = (param & 1); int seed = atsGetSeed(); /* position where the maximum error occured */ int merr_w = 0, merr_h = 0, merr_iter = 0, merr_c = 0; /* test parameters */ int w = 0, h = 0, i = 0, c = 0; double max_err = 0.; //int code = TRS_OK; IplROI roi; IplImage *img; AtsRandState rng_state; atsRandInit( &rng_state, 0, 1, seed ); read_moments_params(); if( !(ATS_RANGE( binary, fn_l, fn_h+1 ) && ATS_RANGE( depth, dt_l, dt_h+1 ) && ATS_RANGE( channels, ch_l, ch_h+1 ))) return TRS_UNDEF; depth = depth == 2 ? IPL_DEPTH_32F : depth == 1 ? IPL_DEPTH_8S : IPL_DEPTH_8U; channels = channels*2 + 1; img = atsCreateImage( max_img_size, max_img_size, depth, channels, 0 ); roi.coi = 0; roi.xOffset = roi.yOffset = 0; img->roi = &roi; for( h = min_img_size; h <= max_img_size; ) { for( w = min_img_size; w <= max_img_size; ) { int denom = (w - min_img_size + 1)*(h - min_img_size + 1)*channels; int iters = (base_iters*2 + denom)/(2*denom); roi.width = w; roi.height = h; if( iters < 1 ) iters = 1; for( i = 0; i < iters; i++ ) { switch( depth ) { case IPL_DEPTH_8U: atsRandSetBounds( &rng_state, 0, img8u_range ); break; case IPL_DEPTH_8S: atsRandSetBounds( &rng_state, -img8s_range, img8s_range ); break; case IPL_DEPTH_32F: atsRandSetBounds( &rng_state, -img32f_range, img32f_range ); if( binary ) atsRandSetFloatBits( &rng_state, img32f_bits ); break; } roi.coi = 0; atsFillRandomImageEx( img, &rng_state ); /*iplSet( img, depth == IPL_DEPTH_8S ? 125 : 251 );*/ for( c = 1; c <= channels; c++ ) { double err0 = 0; AtsMomentState astate0, astate1; CvMoments istate; double* a0 = (double*)&astate0; double* a1 = (double*)&astate1; int j; roi.coi = c; /* etalon function */ atsCalcMoments( img, &astate0, binary ); /* cv function */ cvMoments( img, &istate, binary ); atsGetMoments( &istate, &astate1 ); /*iplMoments( img, lstate ); */ /*convert_ipl_to_ats( lstate, &astate1 ); */ for( j = 0; j < sizeof(astate0)/sizeof(double); j++ ) { double err = rel_err( a0[j], a1[j] )*weight[j]; err0 = MAX( err0, err ); } if( err0 > max_err ) { merr_w = w; merr_h = h; merr_iter = i; merr_c = c; max_err = err0; if( max_err > success_error_level ) goto test_exit; } } } ATS_INCREASE( w, img_size_delta_type, img_size_delta ); } /* end of the loop by w */ ATS_INCREASE( h, img_size_delta_type, img_size_delta ); } /* end of the loop by h */ test_exit: img->roi = 0; iplDeallocate( img, IPL_IMAGE_ALL ); //if( code == TRS_OK ) { trsWrite( ATS_LST, "Max err is %g at w = %d, h = %d, " "iter = %d, c = %d, seed = %08x", max_err, merr_w, merr_h, merr_iter, merr_c, seed ); return max_err <= success_error_level ? trsResult( TRS_OK, "No errors" ) : trsResult( TRS_FAIL, "Bad accuracy" ); } /*else { trsWrite( ATS_LST, "Fatal error at w = %d, h = %d, " "iter = %d, c = %d, seed = %08x", w, h, i, c, seed ); return trsResult( TRS_FAIL, "Function returns error code" ); }*/ }
/*=================================================== Test body ========================== */ static int fmaFloodFill( void ) { /* Some Variables */ int nx, ny, stepX, stepY, numTest, ROI_offset, mp=0, mp4=0; int i, j, k, ij, it, n, n4, ov, d1, d2, ntest2, nerr, nerr1=0, nerr2=0, nerr3=0, nerr4=0; int step, step4; uchar *pI0, *pI1, *pI2; float* pI3, *pI4; IplImage *I0, *I1, *I2, *I3, *I4; CvSize size; CvPoint seed; CvConnectedComp Comp; CvStatus r; /* Reading test parameters */ trsiRead( &nx, "64", "Image width" ); trsiRead( &stepX, "16", "Seed point horizontal step" ); trsiRead( &numTest, "32", "Number of each seed point tests" ); trsiRead( &ROI_offset, "0", "ROI offset" ); ny = nx; stepY = stepX; n = nx*ny; ntest2 = numTest/2; size.width = nx; size.height = ny; I0 = cvCreateImage( size, IPL_DEPTH_8U, 1 ); I1 = cvCreateImage( size, IPL_DEPTH_8U, 1 ); I2 = cvCreateImage( size, IPL_DEPTH_8U, 1 ); I3 = cvCreateImage( size, IPL_DEPTH_32F,1 ); I4 = cvCreateImage( size, IPL_DEPTH_32F,1 ); pI0 = (uchar*)I0->imageData; pI1 = (uchar*)I1->imageData; pI2 = (uchar*)I2->imageData; pI3 = (float*)I3->imageData; pI4 = (float*)I4->imageData; step = I1->widthStep; step4 = I3->widthStep; n = step*ny; n4 = (step4/4)*ny; if(ROI_offset) { mp = ROI_offset + ROI_offset*step; mp4= ROI_offset + ROI_offset*step4; size.width = nx - 2*ROI_offset; size.height = ny - 2*ROI_offset; I1->roi->xOffset = I1->roi->yOffset = ROI_offset; I1->roi->height = size.height; I1->roi->width = size.width; I3->roi->xOffset = I3->roi->yOffset = ROI_offset; I3->roi->height = size.height; I3->roi->width = size.width; } /* T E S T I N G */ /* Zero interval */ d1 = d2 = 0; ats1bInitRandom ( 0, 1.5, pI0, n ); /*for(i=0;i<n;i++)printf(" %d",pI0[i]);getchar(); */ for(j=0; j<size.height; j=j+stepY) { seed.y = j; for(i=0; i<size.width; i=i+stepX) { seed.x = i; for(k=0; k<n; k++) pI1[k]=pI2[k]=pI0[k]; for(k=0; k<n4; k++) pI3[k]=pI4[k]=(float)pI0[k]; /* 8U */ Counter = 0; X1 = X2 = i; Y1 = Y2 = j; /* Run CVL function */ cvFloodFill ( I1, seed, 10.0, 0.0, 0.0, &Comp ); /* Run test function */ r = _cvFloodFill8uC1R_slow (pI2+mp, step, size, seed, 10, 0, 0 ); /* Comparison */ for(k=0; k<n; k++) if( (pI1[k]-pI2[k]) ) nerr1++; if( Comp.area!=Counter ) nerr1++; if(X1!=Comp.rect.x) nerr1++; if(Y1!=Comp.rect.y) nerr1++; if((X2-X1+1)!=Comp.rect.width) nerr1++; if((Y2-Y1+1)!=Comp.rect.height) nerr1++; /* 32F */ Counter = 0; X1 = X2 = i; Y1 = Y2 = j; /* Run CVL function */ cvFloodFill ( I3, seed, 10.0, 0.0, 0.0, &Comp ); /* Run test function */ r = _cvFloodFill32fC1R_slow (pI4+mp4, step4, size, seed, 10.0, 0.0f, 0.0f ); /* Comparison */ for(k=0; k<n4; k++) if( (pI3[k]-pI4[k]) ) nerr2++; if( Comp.area!=Counter ) nerr2++; if(X1!=Comp.rect.x) nerr2++; if(Y1!=Comp.rect.y) nerr2++; if((X2-X1+1)!=Comp.rect.width) nerr2++; if((Y2-Y1+1)!=Comp.rect.height) nerr2++; if( nerr1 != 0 || nerr2 != 0 ) goto test_end; } } /* Non-zero interval */ ats1bInitRandom ( 0, 254.99, pI0, n ); for(j=1; j<size.height; j=j+stepY) { seed.y = j; for(i=1; i<size.width; i=i+stepX) { ij=i+step*j; ov=pI0[ij+mp]; seed.x = i; for(it=0; it<numTest; it++) { for(k=0; k<n; k++) pI1[k]=pI2[k]=pI0[k]; for(k=0; k<n4; k++) pI3[k]=pI4[k]=(float)pI0[k]; if(it<ntest2) /* sequential increase interval */ { d1=(ov*(it+1))/ntest2; d2=((255-ov)*(it+1))/ntest2; } else /* random interval */ { d1 = (int)atsInitRandom(1.0, 127); d2 = (int)atsInitRandom(1.0, 127); if(it>(3*numTest)/4){d1/=2; d2/=2;} } /* 8U */ Counter = 0; X1 = X2 = i; Y1 = Y2 = j; /* Run CVL function */ cvFloodFill ( I1, seed, 255.0, (double)d1, (double)d2, &Comp ); /* Run test function */ r = _cvFloodFill8uC1R_slow (pI2+mp, step, size, seed, 255, d1, d2 ); /* Comparison */ for(k=0; k<n; k++) if( (pI1[k]-pI2[k]) ) nerr3++; if( Comp.area!=Counter ) nerr3++; if(X1!=Comp.rect.x) nerr3++; if(Y1!=Comp.rect.y) nerr3++; if((X2-X1+1)!=Comp.rect.width) nerr3++; if((Y2-Y1+1)!=Comp.rect.height) nerr3++; /* 32F */ Counter = 0; X1 = X2 = i; Y1 = Y2 = j; /* Run CVL function */ cvFloodFill ( I3, seed, 255.0, (double)d1, (double)d2, &Comp ); /* Run test function */ r = _cvFloodFill32fC1R_slow (pI4+mp4, step4, size, seed, 255.0, (float)d1, (float)d2 ); /* Comparison */ for(k=0; k<n4; k++) if( (pI3[k]-pI4[k]) ) nerr4++; if( Comp.area!=Counter ) nerr4++; if(X1!=Comp.rect.x) nerr4++; if(Y1!=Comp.rect.y) nerr4++; if((X2-X1+1)!=Comp.rect.width) nerr4++; if((Y2-Y1+1)!=Comp.rect.height) nerr4++; if( nerr3 != 0 || nerr4 != 0 ) goto test_end; } } trsWrite(TW_RUN|TW_CON, " %d%% ", ((j+stepY)*100)/size.height); } test_end: cvReleaseImage( &I0 ); cvReleaseImage( &I1 ); cvReleaseImage( &I2 ); cvReleaseImage( &I3 ); cvReleaseImage( &I4 ); nerr = nerr1 + nerr2 + nerr3 + nerr4; printf( "\n zero: %d %d non-zero: %d %d\n", nerr1, nerr2, nerr3, nerr4 ); trsWrite(TW_RUN|TW_CON|TW_SUM, " Nerr = %d\n", nerr); if( nerr == 0 ) return trsResult( TRS_OK, "No errors fixed by this test" ); else return trsResult( TRS_FAIL, "Total fixed %d errors", nerr ); } /*fma*/
int testEvidence() { int ret = TRS_OK; int nnodes = 0; int nObsNodes = 0; int i,j; while(nnodes <= 0) { trsiRead( &nnodes, "10", "Number of nodes in Model" ); } while((nObsNodes <= 0)||(nObsNodes>nnodes)) { trsiRead( &nObsNodes, "2", "Number of Observed nodes from all nodes in model"); } int seed1 = pnlTestRandSeed(); /*create string to display the value*/ char value[42]; sprintf(value, "%i", seed1); trsiRead(&seed1, value, "Seed for srand to define NodeTypes etc."); trsWrite(TW_CON|TW_RUN|TW_DEBUG|TW_LST, "seed for rand = %d\n", seed1); CNodeType *modelNodeType = new CNodeType[2]; modelNodeType[0] = CNodeType( 1, 4 ); modelNodeType[1] = CNodeType( 0, 3 ); int *NodeAssociat=new int [nnodes+1]; for(i=0; i<(nnodes+1)/2; i++) { NodeAssociat[2*i]=0; NodeAssociat[2*i+1]=1; } //create random graph - number of nodes for every node is rand too int lowBorder = nnodes - 1; int upperBorder = int((nnodes * (nnodes - 1)) / 2); int numEdges = rand()%(upperBorder - lowBorder)+lowBorder; CGraph* theGraph = tCreateRandomDAG( nnodes, numEdges, 1 ); CBNet *grModel = CBNet::Create(nnodes, 2, modelNodeType, NodeAssociat,theGraph); int *obsNodes = (int*)trsGuardcAlloc(nObsNodes, sizeof(int)); srand ((unsigned int)seed1); intVector residuaryNodes; for (i=0; i<nnodes; i++) { residuaryNodes.push_back(i); } int num = 0; valueVector Values; Values.reserve(3*nnodes); Value val; for (i = 0; i<nObsNodes; i++) { num = rand()%(nnodes-i); obsNodes[i] = residuaryNodes[num]; residuaryNodes.erase(residuaryNodes.begin()+num); CNodeType nt = modelNodeType[NodeAssociat[obsNodes[i]]]; if(nt.IsDiscrete()) { val.SetInt(1); Values.push_back(val); } else { val.SetFlt(1.0f); Values.push_back(val); val.SetFlt(2.0f); Values.push_back(val); val.SetFlt(3.0f); Values.push_back(val); } } residuaryNodes.clear(); CEvidence *pMyEvid = CEvidence::Create(grModel, nObsNodes, obsNodes, Values) ; int nObsNodesFromEv = pMyEvid->GetNumberObsNodes(); const int *pObsNodesNow = pMyEvid->GetObsNodesFlags(); // const int *myOffset = pMyEvid->GetOffset(); const int *myNumAllObsNodes = pMyEvid->GetAllObsNodes(); valueVector ev; pMyEvid->GetRawData(&ev); const Value* vall = pMyEvid->GetValue(obsNodes[0]); if( NodeAssociat[obsNodes[0]] == 0 ) { if( (vall)[0].GetInt() != 1 ) { ret = TRS_FAIL; } } else { for( j=0; j<3; j++) { if( (vall)[j].GetFlt() != (j+1)*1.0f ) { ret = TRS_FAIL; break; } } } if(nObsNodesFromEv == nObsNodes) { intVector numbersOfReallyObsNodes; int numReallyObsNodes=0; for ( i=0; i<nObsNodesFromEv; i++) { if (pObsNodesNow[i]) { numbersOfReallyObsNodes.push_back(myNumAllObsNodes[i]); numReallyObsNodes++; } } #if 0 const CNodeType ** AllNodeTypesFromModel= new const CNodeType*[nnodes]; for (i=0; i<nnodes; i++) { AllNodeTypesFromModel[i] = grModel->GetNodeType(i); } for (i=0; i<nObsNodesFromEv; i++) { //Test the values which are keep in Evidence CNodeType nt = *AllNodeTypesFromModel[myNumAllObsNodes[i]]; int IsDiscreteNode = nt.IsDiscrete(); if(IsDiscreteNode) { int valFromEv = (ev[myOffset[i]].GetInt()); if(!(Values[i].GetInt() == valFromEv)) { ret=TRS_FAIL; break; } } else { ; for (j=0; j<3; j++) { if(!((ev[myOffset[i]+j]).GetFlt() == Values[i+j].GetFlt())) { ret=TRS_FAIL; break; } } } } delete []AllNodeTypesFromModel; #endif } else { ret = TRS_FAIL; } //Toggle some Node int someNumber = (int)(rand()*nObsNodesFromEv/RAND_MAX); int *someOfNodes = new int[someNumber]; intVector residuaryNums = intVector(myNumAllObsNodes, myNumAllObsNodes+nObsNodesFromEv); num=0; for(i=0; i<someNumber;i++) { num = (int)(rand()%(nObsNodes-i)); someOfNodes[i] = residuaryNums[num]; residuaryNums.erase(residuaryNums.begin()+num); } residuaryNums.clear(); pMyEvid->ToggleNodeState(someNumber, someOfNodes); const int *pObsNodesAfterToggle = pMyEvid->GetObsNodesFlags(); for (i=0; i<nObsNodesFromEv; i++) { //Test the ToggleNode method... if(pObsNodesAfterToggle[i]) { for(j=0; j<someNumber;j++) { if(myNumAllObsNodes[i]==someOfNodes[j]) { ret=TRS_FAIL; break; } } } } delete grModel; delete pMyEvid; delete []modelNodeType; delete []NodeAssociat; delete []someOfNodes; int obsNodes_memory_flag = trsGuardCheck( obsNodes ); if( obsNodes_memory_flag) { return trsResult( TRS_FAIL, "Dirty memory"); } trsGuardFree( obsNodes ); return trsResult( ret, ret == TRS_OK ? "No errors" : "Bad test on Values"); }
int timeJTreeInfEngine() { int ret = TRS_OK; char filename[120]; trstRead(filename, sizeof(filename), DSL_NETWORK_NAME, "Model name"); trsTimerStart(0); CBNet* pBNet = ConvertFromDSLNet(filename); trsTimerStop(0); double timeOfDSL2PNLConversion = trsTimerSec(0); if( pBNet == NULL ) { ret = TRS_FAIL; return trsResult( ret, ret == TRS_OK ? "No errors" : "JTree timing FAILED"); } const CModelDomain* pModelDomain = pBNet->GetModelDomain(); const int numOfNds = pBNet->GetNumberOfNodes(); const int numOfObsNds = NUM_OF_OBS_NDS; assert( numOfObsNds <= numOfNds ); intVector obsNds(numOfObsNds); valueVector obsNdsVals(numOfObsNds); SetRndObsNdsAndVals( pModelDomain, &obsNds, &obsNdsVals ); CEvidence* pEvidence = CEvidence::Create( pModelDomain, obsNds, obsNdsVals ); trsTimerStart(1); CJtreeInfEngine* pJTreeInfEngine = CJtreeInfEngine::Create(pBNet); trsTimerStop(1); double timeOfInfCreation = trsTimerSec(1); const int numOfEnterEvidenceLoops = TIMES_TO_RUN_ENTER_EVIDENCE; assert( numOfEnterEvidenceLoops > 0 ); trsTimerStart(2); int i = 0; for( ; i < numOfEnterEvidenceLoops; ++i ) { pJTreeInfEngine->EnterEvidence(pEvidence); } trsTimerStop(2); double timeOfEnterEvidence = trsTimerSec(2); double averageTimeOfEnterEvidence = timeOfEnterEvidence /numOfEnterEvidenceLoops; double freqCPU = trsClocksPerSec(); trsCSVString8( "d", func_name, trsDouble(timeOfInfCreation), trsDouble(averageTimeOfEnterEvidence), trsDouble(freqCPU), "\n JTree inference creation ", "\n average time for entering evidence ", "\n CPU frequency " ); trsWrite( TW_RUN | TW_CON, " %s performance measurement:\n\n", func_name ); trsWrite( TW_RUN | TW_CON, " Conversion from DSL to PNL network took %g seconds\n" " JTree inference engine creation took %g seconds\n" " Average entering evidence time is %g seconds\n", timeOfDSL2PNLConversion, timeOfInfCreation, averageTimeOfEnterEvidence ); delete pEvidence; //CJtreeInfEngine::Release(&pJTreeInfEngine); delete pJTreeInfEngine; delete pBNet; return trsResult( ret, ret == TRS_OK ? "No errors" : "JTree timing FAILED"); }