static void read_moments_params( void ) { if( !init_moments_params ) { int func, data_types, channels; /* Determine which tests are needed to run */ trsCaseRead( &func, "/a/m/mb", "a", "Function type: \n" "a - all\n" "m - moments\n" "mb - moments binary\n"); if( func != 0 ) fn_l = fn_h = func - 1; trsCaseRead( &data_types,"/a/8u/8s/32f", "a", "a - all, 8u - unsigned char, 8s - signed char, 32f - float" ); if( data_types != 0 ) dt_l = dt_h = data_types - 1; trsCaseRead( &channels, "/a/1/3", "a", "a - all, 1 - single channel, 3 - three channels" ); if( channels != 0 ) ch_l = ch_h = channels - 1; /* read tests params */ trsiRead( &min_img_size, "1", "Minimal width or height of image" ); trsiRead( &max_img_size, "1000", "Maximal width or height of image" ); trsCaseRead( &img_size_delta_type,"/a/m", "m", "a - add, m - multiply" ); trsiRead( &img_size_delta, "3", "Image size step(factor)" ); trsiRead( &base_iters, "100", "Base number of iterations" ); init_moments_params = 1; } }
int test1_5JTreeInfDBNCondGauss() { int ret = TRS_OK; int seed = pnlTestRandSeed(); std::cout<<"seed"<<seed<<std::endl; srand( seed ); CDBN *pDBN = tCreateArHMMwithGaussObs(); int nTimeSlice = -1; while(nTimeSlice <= 0) { trsiRead (&nTimeSlice, "4", "Number of slices"); } float eps = -1.0f; while( eps <= 0 ) { trssRead( &eps, "1e-2f", "accuracy in test"); } int result = 1; result = CompareSmoothingArHMM( pDBN, nTimeSlice, eps ); if( !result ) { ret = TRS_FAIL; } result = CompareFilteringArHMM( pDBN, nTimeSlice, eps ); if( !result ) { ret = TRS_FAIL; } result = CompareFixLagSmoothingArHMM( pDBN, nTimeSlice, eps ); if( !result ) { ret = TRS_FAIL; } result = CompareViterbyArHMM( pDBN, nTimeSlice, eps ); if( !result ) { ret = TRS_FAIL; } ////////////////////////////////////////////////////////////////////////// delete pDBN; return trsResult( ret, ret == TRS_OK ? "No errors" : "Bad test on 1_5 Slice JTree DBN"); }
static void read_arithm_params( void ) { if( !init_arithm_params ) { int data_types, channels; trsCaseRead( &data_types,"/a/8u/8s/16s/32s/32f/64f", "a", "a - all, 8u - uchar, 8s - char, 16s - short, 32s - int, 32f - float, 64f - float" ); if( data_types != 0 ) dt_l = dt_h = data_types - 1; trsCaseRead( &channels, "/a/1/2/3/4", "a", "a - all, 1 - 1, 2 - 2, 3 - 3, 4 - 4" ); if( channels != 0 ) ch_l = ch_h = channels - 1; /* read tests params */ trsiRead( &min_img_size, "1", "Minimal width or height of image" ); trsiRead( &max_img_size, "100", "Maximal width or height of image" ); trsiRead( &base_iters, "300", "Base number of iterations" ); init_arithm_params = 1; } }
int testMatrix() { int ret = TRS_OK; int dim = 0; int i; while(dim <= 0) { trsiRead( &dim, "128", "matrix dimension" ); } int* range = (int*)trsGuardcAlloc( dim, sizeof(int) ); float* data = (float*)trsGuardcAlloc( dim, sizeof(float) ); for(i = 0; i < dim; i++) { range[i] = 1; data[i] = 1.0f*i; } range[0] = dim; CNumericDenseMatrix<float>* m = CNumericDenseMatrix<float>::Create(1, range, data); int length; const float *mdata; m->GetRawData(&length, &mdata); for(i = 0; i < dim; i++) { // Test the values... if(mdata[i] != data[i]) { ret = TRS_FAIL; break; } } delete m; int range_memory_flag = trsGuardCheck( range ); int data_memory_flag = trsGuardCheck( data ); trsGuardFree( range ); trsGuardFree( data ); if(range_memory_flag || data_memory_flag) { return trsResult( TRS_FAIL, "Dirty memory"); } return trsResult( ret, ret == TRS_OK ? "No errors" : "Bad matrix data"); }
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 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 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; }
int testPearlInfEngForMRF2() { int ret = TRS_OK; // of course ;) int numOfRows = 0; while( ( numOfRows < 1 ) || ( numOfRows > MAX_NUM_OF_ROWS ) ) { trsiRead( &numOfRows, "3", "Number of rows in a 2-layered MRF2" ); } int numOfCols = 0; while( ( numOfCols < 1 ) || ( numOfCols > MAX_NUM_OF_COLS ) ) { trsiRead( &numOfCols, "3", "Number of columns in a 2-layered MRF2" ); } int numOfNodeVals = 0; while( ( numOfNodeVals < 1 ) || ( numOfNodeVals > MAX_NUM_OF_NODE_VALS ) ) { trsiRead( &numOfNodeVals, "10", "Number of values each node in a 2-layered MRF2 can take" ); } int numOfNodeValDims = 0; while( ( numOfNodeValDims < 1 ) || ( numOfNodeValDims > MAX_NUM_OF_NODE_VAL_DIMS ) ) { trsiRead( &numOfNodeValDims, "10", "Number of dimensions of each node value in a 2-layered MRF2" ); } int equalValNum = -2; while( ( equalValNum < -1 ) || ( equalValNum >= numOfNodeVals ) ) { trsiRead( &equalValNum, "0", "values of this number will be equal for all nodes MRF2\n" "if you choose value -1 (negative one), there will be no\n" "equal values for all nodes"); } int maxNumOfIters = 0; while( ( maxNumOfIters < 1 ) || ( maxNumOfIters > MAX_NUM_OF_ITERS ) ) { trsiRead( &maxNumOfIters, "3", "Number of iterations Pearl Inference engine will run for" ); } int chosenType = 1; char *strVal; strVal = trsInt(chosenType); int typeOfPotential = -1; while( ( typeOfPotential < 0 ) ) { trsiRead( &typeOfPotential, strVal, "Type of potential in created model" ); } const int numOfNds = 2*numOfRows*numOfCols; int numOfObsNds = numOfNds/2; nodeTypeVector nodeTypes(2); nodeTypes[0].SetType( true, numOfNodeVals ); nodeTypes[1].SetType( true, 1 ); intVector nodeAssociation( numOfNds, 0 ); std::fill( nodeAssociation.begin() + numOfNds/2, nodeAssociation.end(), 1 ); CModelDomain* pModelDomain = CModelDomain::Create( nodeTypes, nodeAssociation ); pnlVector< floatVecVector > nodeVals( numOfNds/2, floatVecVector( numOfNodeVals, floatVector(numOfNodeValDims) ) ); int i; for( i = 0; i < numOfNds/2; ++i ) { int j; for( j = 0; j < numOfNodeVals; ++j ) { if( j != equalValNum ) { super_helper::GetRandomNodeVal( &nodeVals[i][j] ); } else { super_helper::GetEqualNodeVal( &nodeVals[i][j] ); } } } // for( i = 0 ; i < numOfNds/2; ++i ) // { // for_each( nodeVals[i].begin(), nodeVals[i].end(), // super_helper::PrintVector<float>() ); // } CMRF2* p2LMRF2Model = SuperResolution2lMRF2( numOfRows, numOfCols, pModelDomain, nodeVals ); intVector obsNds(numOfObsNds); valueVector obsNdsVals(numOfObsNds); for( i = 0; i < numOfObsNds; ++i ) { obsNds[i] = numOfObsNds + i; obsNdsVals[i].SetInt(0); } CEvidence* pEvidence = CEvidence::Create( p2LMRF2Model, obsNds, obsNdsVals ); CPearlInfEngine* pPearlInfEngine = CPearlInfEngine::Create(p2LMRF2Model); CSpecPearlInfEngine* pSpecPearlInfEngine = CSpecPearlInfEngine::Create(p2LMRF2Model); pPearlInfEngine->SetMaxNumberOfIterations(maxNumOfIters); pSpecPearlInfEngine->SetMaxNumberOfIterations(maxNumOfIters); pPearlInfEngine->EnterEvidence( pEvidence, true ); pSpecPearlInfEngine->EnterEvidence( pEvidence, true ); intVector maxIndices(numOfNds/2); intVector specMaxIndices(numOfNds/2); for( i = 0; i < numOfNds/2; ++i ) { pPearlInfEngine->MarginalNodes( &i, 1 ); const CEvidence* pMPE = pPearlInfEngine->GetMPE(); pSpecPearlInfEngine->MarginalNodes( &i, 1 ); const CEvidence* pSpecMPE = pSpecPearlInfEngine->GetMPE(); intVector MPEobsNdsNums; pConstValueVector MPEobsNdsVals; pConstNodeTypeVector MPENodeTypes; pMPE->GetObsNodesWithValues( &MPEobsNdsNums, &MPEobsNdsVals, &MPENodeTypes ); maxIndices[i] = MPEobsNdsVals[0]->GetInt(); pSpecMPE->GetObsNodesWithValues( &MPEobsNdsNums, &MPEobsNdsVals, &MPENodeTypes ); specMaxIndices[i] = MPEobsNdsVals[0]->GetInt(); } std::cout << "Here're the numbers of node values chosen" " by Pearl (max_indices)" << std::endl; std::for_each( maxIndices.begin(), maxIndices.end(), super_helper::Print<int>() ); //compare results int numIndices = maxIndices.size(); for( i = 0; i < numIndices; i++ ) { if( specMaxIndices[i] != maxIndices[i] ) { ret = TRS_FAIL; } } if( ( equalValNum != -1 ) && ( std::count_if( maxIndices.begin(), maxIndices.end(), super_helper::NotEqual<int>(equalValNum) ) > 0 ) ) { ret = TRS_FAIL; } //add the code for testing specPearl CMRF2* pModelToWorkWith = pnlExCreateBigMRF2( typeOfPotential, 15, 15, 4, 1.0f, 1.0f ); const int numNodes = pModelToWorkWith->GetNumberOfNodes(); maxNumOfIters = numNodes/2; numOfObsNds = rand()%( numNodes - 2 ); intVector obsNdsSp(numOfObsNds); valueVector obsNdsValsSp(numOfObsNds); SetRndObsNdsAndVals( pModelToWorkWith->GetModelDomain(), &obsNdsSp, &obsNdsValsSp ); CEvidence* pEvidenceSp = CEvidence::Create( pModelToWorkWith, obsNdsSp, obsNdsValsSp ); CPearlInfEngine* pPearlEng = CPearlInfEngine::Create(pModelToWorkWith); pPearlEng->SetMaxNumberOfIterations(maxNumOfIters); // trsTimerStart(0); pPearlEng->EnterEvidence(pEvidenceSp); // trsTimerStop(0); // double timeOfEnterEvidenceForPearl = trsTimerSec(0); int numProvIters = pPearlEng->GetNumberOfProvideIterations(); CSpecPearlInfEngine* pPearlEng1 = CSpecPearlInfEngine::Create(pModelToWorkWith); pPearlEng1->SetMaxNumberOfIterations(maxNumOfIters); // trsTimerStart(0); pPearlEng1->EnterEvidence(pEvidenceSp); // trsTimerStop(0); // double timeOfEnterEvidenceForPearl1 = trsTimerSec(0); int numProvIters1 = pPearlEng1->GetNumberOfProvideIterations(); //check are the potentials the same int potsAreTheSame = 1; float eps = 1e-5f; float maxDiff = 0.0f; const CPotential* potPearl = NULL; const CPotential* pot1Pearl = NULL; for( i = 0; i < numNodes; i++ ) { pPearlEng->MarginalNodes(&i, 1); potPearl = pPearlEng->GetQueryJPD(); pPearlEng1->MarginalNodes(&i, 1); pot1Pearl = pPearlEng1->GetQueryJPD(); if( !potPearl->IsFactorsDistribFunEqual(pot1Pearl, eps, 0, &maxDiff ) ) { potsAreTheSame = 0; } } std::cout<<"num iterations pearl: "<<numProvIters<<std::endl; std::cout<<"num iterations spec pearl: "<<numProvIters1<<std::endl; // std::cout<<"time pearl: "<<timeOfEnterEvidenceForPearl<<std::endl; // std::cout<<"time spec pearl: "<<timeOfEnterEvidenceForPearl1<<std::endl; delete pPearlEng; delete pPearlEng1; delete pModelToWorkWith; delete pEvidenceSp; //create other model //add the code for testing specPearl CMRF2* pOtherModel= pnlExCreateBigMRF2( 5, 5, 5, 6, 1.0f, 1.0f ); const int numOtherNodes = pOtherModel->GetNumberOfNodes(); numOfObsNds = rand()%( numOtherNodes - 2 ); intVector obsNdsOtherSp(numOfObsNds); valueVector obsNdsValsOtherSp(numOfObsNds); SetRndObsNdsAndVals( pOtherModel->GetModelDomain(), &obsNdsOtherSp, &obsNdsValsOtherSp ); CEvidence* pEvidenceOtherSp = CEvidence::Create( pOtherModel, obsNdsOtherSp, obsNdsValsOtherSp ); CPearlInfEngine* pOtherPearlEng = CPearlInfEngine::Create(pOtherModel); pOtherPearlEng->SetMaxNumberOfIterations(maxNumOfIters); pOtherPearlEng->EnterEvidence(pEvidenceOtherSp); CSpecPearlInfEngine* pOtherPearlEng1 = CSpecPearlInfEngine::Create(pOtherModel); pOtherPearlEng1->SetMaxNumberOfIterations(maxNumOfIters); pOtherPearlEng1->EnterEvidence(pEvidenceOtherSp); //check are the potentials the same potsAreTheSame = 1; maxDiff = 0.0f; for( i = 0; i < numOtherNodes; i++ ) { pOtherPearlEng->MarginalNodes(&i, 1); potPearl = pOtherPearlEng->GetQueryJPD(); pOtherPearlEng1->MarginalNodes(&i, 1); pot1Pearl = pOtherPearlEng1->GetQueryJPD(); if( !potPearl->IsFactorsDistribFunEqual(pot1Pearl, eps, 0, &maxDiff ) ) { potsAreTheSame = 0; } } delete pEvidenceOtherSp; delete pOtherPearlEng; delete pOtherPearlEng1; delete pOtherModel; delete pEvidence; //CPearlInfEngine::Release(&pPearlInfEngine); delete pPearlInfEngine; delete pSpecPearlInfEngine; delete p2LMRF2Model; delete pModelDomain; return ret; }
//--------------------------------------------------- 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 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"); }
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; }
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 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; }
/*=================================================== Test body ========================== */ static int fmaNormMask(void) { /* Some Variables */ int nx, ny, n, n4, it, ir, nr, nerr=0, coi, step, step4; int xoff, yoff, roiw, roih, nerrt[9]; CvSize size; AtsRandState state1, state2, state3, state4; IplImage *A_8uC1, *A_8sC1, *A_32fC1, *B_8uC1, *B_8sC1, *B_32fC1; IplImage *A_8uC3, *A_8sC3, *A_32fC3, *B_8uC3, *B_8sC3, *B_32fC3; IplImage *mask; IplROI r, rm; double norm, testnorm, err; double Mask_density, d1, d2; trsiRead( &Min_Image_Width, "1", "Minimal image width" ); trsiRead( &Max_Image_Width, "32", "Maximal image width" ); trsiRead( &Max_ROI_Offset, "8", "Maximal ROI offset" ); trsdRead( &Mask_density, "0.5", "Mask density (0 - 1)" ); if( Min_Image_Width < 1 ) Min_Image_Width = 1; if( Max_Image_Width < Min_Image_Width ) Max_Image_Width = Min_Image_Width; if( Max_ROI_Offset < 0 ) Max_ROI_Offset = 0; if( Mask_density < 0.0 ) Mask_density = 0.0; if( Mask_density >= 1.0 ) { d1 = 2.0; d2 = 4.0; } else { d1 = 0.0; d2 = 1.0/(1.0-Mask_density); } if(d2>256.0) d2=256.0; atsRandInit( &state1, MIN_VAL(IPL_DEPTH_8U), MAX_VAL(IPL_DEPTH_8U), 13 ); atsRandInit( &state2, MIN_VAL(IPL_DEPTH_8S), MAX_VAL(IPL_DEPTH_8S), 14 ); atsRandInit( &state3, MIN_VAL(IPL_DEPTH_32F), MAX_VAL(IPL_DEPTH_32F), 15 ); atsRandInit( &state4, d1, d2, 16 ); for( it=0; it<9; it++ ) nerrt[it] = 0; /* Image size cycle starts ________________________ */ for( nx = Min_Image_Width; nx<=Max_Image_Width; nx++ ) { ny = nx; /*if(nx>1)ny=(int)(0.7*nx); // Non-square images test */ size.width = nx; size.height = ny; /* Initial images allocating & random filling */ A_8uC1 = cvCreateImage( size, IPL_DEPTH_8U, 1 ); A_8sC1 = cvCreateImage( size, IPL_DEPTH_8S, 1 ); A_32fC1 = cvCreateImage( size, IPL_DEPTH_32F, 1 ); B_8uC1 = cvCreateImage( size, IPL_DEPTH_8U, 1 ); B_8sC1 = cvCreateImage( size, IPL_DEPTH_8S, 1 ); B_32fC1 = cvCreateImage( size, IPL_DEPTH_32F, 1 ); A_8uC3 = cvCreateImage( size, IPL_DEPTH_8U, 3 ); A_8sC3 = cvCreateImage( size, IPL_DEPTH_8S, 3 ); A_32fC3 = cvCreateImage( size, IPL_DEPTH_32F, 3 ); B_8uC3 = cvCreateImage( size, IPL_DEPTH_8U, 3 ); B_8sC3 = cvCreateImage( size, IPL_DEPTH_8S, 3 ); B_32fC3 = cvCreateImage( size, IPL_DEPTH_32F, 3 ); mask = cvCreateImage( size, IPL_DEPTH_8U, 1 ); step = A_8uC1->widthStep; step4 = (A_32fC1->widthStep)/4; n = ny*step; n4 = ny*step4; atsbRand8u ( &state1, (uchar*)A_8uC1->imageData, n ); atsbRand8s ( &state2, A_8sC1->imageData, n ); atsbRand32f( &state3, (float*)A_32fC1->imageData, n4); atsbRand8u ( &state1, (uchar*)B_8uC1->imageData, n ); atsbRand8s ( &state2, B_8sC1->imageData, n ); atsbRand32f( &state3, (float*)B_32fC1->imageData, n4); atsbRand8u ( &state4, (uchar*)mask->imageData, n ); for(ir=0; ir<n; ir++) if((mask->imageData)[ir]>1) (mask->imageData)[ir]=1; (mask->imageData)[0] = 1; step = A_8uC3->widthStep; step4 = (A_32fC3->widthStep)/4; n = ny*step; n4 = ny*step4; atsbRand8u ( &state1, (uchar*)A_8uC3->imageData, n ); atsbRand8s ( &state2, A_8sC3->imageData, n ); atsbRand32f( &state3, (float*)A_32fC3->imageData, n4); atsbRand8u ( &state1, (uchar*)B_8uC3->imageData, n ); atsbRand8s ( &state2, B_8sC3->imageData, n ); atsbRand32f( &state3, (float*)B_32fC3->imageData, n4); nr = (ny-1)/2>Max_ROI_Offset ? Max_ROI_Offset : (ny-1)/2; A_8uC1->roi = A_8sC1->roi = A_32fC1->roi = A_8uC3->roi = A_8sC3->roi = A_32fC3->roi = B_8uC1->roi = B_8sC1->roi = B_32fC1->roi = B_8uC3->roi = B_8sC3->roi = B_32fC3->roi = &r; for( ir = 0; ir<=nr; ir++) /* ROI size cycle starts ----------------- */ { /* IPL ROI structures filling */ xoff = ir/11; yoff = ir; roiw = nx - (int)(1.2*xoff); roih = ny - (int)(1.5*yoff); r.xOffset = xoff; r.yOffset = yoff; r.width = roiw; r.height = roih; rm = r; rm.coi = 0; mask->roi = &rm; /* T E S T I N G */ for(it = 0; it<9; it++) { IplImage* B; r.coi = 0; //if( it >= 3 ) // continue; B = it<3 ? NULL : B_8uC1; A_8uC1->maskROI = B_8uC1->maskROI = NULL; norm = cvNormMask( A_8uC1, B, mask, cvlType[it] ); testnorm = TestNormMask( A_8uC1, B, mask, cvlType[it] ); err = fabs((norm-testnorm)/testnorm); if( err > EPS ) { nerrt[it]++; printf(" 8uC1 %d norm fail: %f %f\n", it+1, norm, testnorm); } B = it<3 ? NULL : B_8sC1; A_8sC1->maskROI = B_8sC1->maskROI = NULL; norm = cvNormMask( A_8sC1, B, mask, cvlType[it] ); testnorm = TestNormMask( A_8sC1, B, mask, cvlType[it] ); err = fabs((norm-testnorm)/testnorm); if( err > EPS ) { nerrt[it]++; printf(" 8sC1 %d norm fail: %f %f\n", it+1, norm, testnorm); } B = it<3 ? NULL : B_32fC1; A_32fC1->maskROI = B_32fC1->maskROI = NULL; norm = cvNormMask( A_32fC1, B, mask, cvlType[it] ); testnorm = TestNormMask( A_32fC1, B, mask, cvlType[it] ); err = fabs((norm-testnorm)/testnorm); if( err > FEPS ) { nerrt[it]++; printf(" 32fC1 %d norm fail: %f %f\n", it+1, norm, testnorm); } B = it<3 ? NULL : B_8uC3; for( coi=1; coi<4; coi++ ) { r.coi = coi; A_8uC3->maskROI = B_8uC3->maskROI = NULL; norm = cvNormMask( A_8uC3, B, mask, cvlType[it] ); testnorm = TestNormMask( A_8uC3, B, mask, cvlType[it] ); err = fabs((norm-testnorm)/testnorm); if( err > EPS ) { nerrt[it]++; printf(" 8uC3 %d norm fail: %f %f, coi = %d\n", it+1, norm, testnorm, coi); } } B = it<3 ? NULL : B_8sC3; for( coi=1; coi<4; coi++ ) { r.coi = coi; A_8sC3->maskROI = B_8sC3->maskROI = NULL; norm = cvNormMask( A_8sC3, B, mask, cvlType[it] ); testnorm = TestNormMask( A_8sC3, B, mask, cvlType[it] ); err = fabs((norm-testnorm)/testnorm); if( err > EPS ) { nerrt[it]++; printf(" 8sC3 %d norm fail: %f %f, coi = %d\n", it+1, norm, testnorm, coi); } } B = it<3 ? NULL : B_32fC3; for( coi=1; coi<4; coi++ ) { r.coi = coi; A_32fC3->maskROI = B_32fC3->maskROI = NULL; norm = cvNormMask( A_32fC3, B, mask, cvlType[it] ); testnorm = TestNormMask( A_32fC3, B, mask, cvlType[it] ); err = fabs((norm-testnorm)/testnorm); if( err > FEPS ) { nerrt[it]++; printf(" 32fC3 %d norm fail: %f %f, coi = %d\n", it+1, norm, testnorm, coi); } } } /* norm type */ for( it=0; it<9; it++ ) nerr += nerrt[it]; } /* ROI */ A_8uC1->roi = A_8sC1->roi = A_32fC1->roi = A_8uC3->roi = A_8sC3->roi = A_32fC3->roi = B_8uC1->roi = B_8sC1->roi = B_32fC1->roi = B_8uC3->roi = B_8sC3->roi = B_32fC3->roi = 0; mask->roi = 0; A_8uC1->maskROI = A_8sC1->maskROI = A_32fC1->maskROI = A_8uC3->maskROI = A_8sC3->maskROI = A_32fC3->maskROI = B_8uC1->maskROI = B_8sC1->maskROI = B_32fC1->maskROI = B_8uC3->maskROI = B_8sC3->maskROI = B_32fC3->maskROI = 0; mask->maskROI = 0; cvReleaseImage( &A_8uC1 ); cvReleaseImage( &A_8sC1 ); cvReleaseImage( &A_32fC1 ); cvReleaseImage( &B_8uC1 ); cvReleaseImage( &B_8sC1 ); cvReleaseImage( &B_32fC1 ); cvReleaseImage( &A_8uC3 ); cvReleaseImage( &A_8sC3 ); cvReleaseImage( &A_32fC3 ); cvReleaseImage( &B_8uC3 ); cvReleaseImage( &B_8sC3 ); cvReleaseImage( &B_32fC3 ); cvReleaseImage( &mask ); } /* Nx */ /*trsWrite (TW_RUN|TW_CON|TW_SUM," %d norm %s%s flavor fail: %g %g\n", it+1, f1, f2, norm, testnorm);*/ if(nerr) return trsResult( TRS_FAIL, "Algorithm test has passed. %d errors.", nerr ); else return trsResult( TRS_OK, "Algorithm test has passed successfully" ); } /* fmaNorm */
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 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 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 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"); }
int testBKInfUsingClusters() { int ret = TRS_OK; int seed = pnlTestRandSeed(); pnlSeed( seed ); std::cout<<"seed"<<seed<<std::endl; int nTimeSlices = -1; while(nTimeSlices <= 5) { trsiRead (&nTimeSlices, "10", "Number of slices"); } float eps = -1.0f; while( eps <= 0 ) { trssRead( &eps, "1.0e-1f", "accuracy in test"); } CDBN *pDBN = CDBN::Create( pnlExCreateBatNetwork() ); intVecVector clusters; intVector interfNds; pDBN->GetInterfaceNodes( &interfNds ); int numIntNds = interfNds.size(); int numOfClusters = pnlRand( 1, numIntNds ); clusters.resize(numOfClusters); int i; for( i = 0; i < numIntNds; i++ ) { ( clusters[pnlRand( 0, numOfClusters-1 )] ).push_back( interfNds[i] ); } intVecVector validClusters; validClusters.reserve(numOfClusters); for( i = 0; i < clusters.size(); i++ ) { if(! clusters[i].empty()) { validClusters.push_back(clusters[i]); } } CBKInfEngine *pBKInf; pBKInf = CBKInfEngine::Create( pDBN, validClusters ); C1_5SliceJtreeInfEngine *pJTreeInf; pJTreeInf = C1_5SliceJtreeInfEngine::Create( pDBN ); intVector nSlices( 1, nTimeSlices ); pEvidencesVecVector pEvid; pDBN->GenerateSamples( &pEvid, nSlices); int nnodesPerSlice = pDBN->GetNumberOfNodes(); intVector nodes(nnodesPerSlice, 0); for( i = 0; i < nnodesPerSlice; i++ ) { nodes[i] = i; } intVector ndsToToggle; for( i = 0; i < nTimeSlices; i++ ) { std::random_shuffle( nodes.begin(), nodes.end() ); ndsToToggle.resize( pnlRand(1, nnodesPerSlice) ); int j; for( j = 0; j < ndsToToggle.size(); j++ ) { ndsToToggle[j] = nodes[j]; } (pEvid[0])[i]->ToggleNodeState( ndsToToggle ); } pBKInf->DefineProcedure( ptSmoothing, nTimeSlices ); pBKInf->EnterEvidence( &(pEvid[0]).front(), nTimeSlices ); pBKInf->Smoothing(); pJTreeInf->DefineProcedure( ptSmoothing, nTimeSlices ); pJTreeInf->EnterEvidence( &pEvid[0].front(), nTimeSlices ); pJTreeInf->Smoothing(); int querySlice = pnlRand( 0, nTimeSlices - 1 ); int queryNode = pnlRand( 0, nnodesPerSlice - 1); queryNode += (querySlice ? nnodesPerSlice : 0); intVector query; pDBN->GetGraph()->GetParents( queryNode, &query ); query.push_back( queryNode ); std::random_shuffle( query.begin(), query.end() ); query.resize( pnlRand(1, query.size()) ); pBKInf->MarginalNodes(&query.front(), query.size(), querySlice); pJTreeInf->MarginalNodes(&query.front(), query.size(), querySlice); const CPotential *potBK = pBKInf->GetQueryJPD(); const CPotential *potJTree = pJTreeInf->GetQueryJPD(); if( !potBK->IsFactorsDistribFunEqual( potJTree , eps ) ) { std::cout<<"BK query JPD \n"; potBK->Dump(); std::cout<<"JTree query JPD \n"; potJTree->Dump(); ret = TRS_FAIL; } for( i = 0; i < nTimeSlices; i++ ) { delete (pEvid[0])[i]; } delete pBKInf; delete pJTreeInf; delete pDBN; return trsResult( ret, ret == TRS_OK ? "No errors" : "Bad test on BK Inference using clusters"); }
static int fcaScharr( void ) { int KerX[15]; int KerY[15]; CvSize KerLens; int dx,dy; AtsRandState state; AtsRandState sizegen; double Error = 0; IplImage* src8u; IplImage* src8s; IplImage* src32f; IplImage* src16; IplImage* dst16; IplImage* test16; IplImage* dst32f; IplImage* test32f; IplImage* buf; IplConvKernel* KernelX; IplConvKernel* KernelY; IplConvKernelFP* KX; IplConvKernelFP* KY; /* Initialization global parameters */ if( !read_param ) { read_param = 1; /* Determining which test are needed to run */ trsCaseRead( &data_types,"/u/s/f/a", "a", "u - unsigned char, s - signed char, f - float, a - all" ); /* Reading test-parameters */ trsiRead( &lMinImageSize, "16", "Image height" ); trsiRead( &lMaxImageSize, "256", "Image width" ); trsiRead( &lTestNum, "20", "Test count" ); } if( data_types != 3 && data_types != 0 ) return TRS_UNDEF; atsRandInit(&sizegen,lMinImageSize,lMaxImageSize,0); /* Creating images for testing */ for(int i = 0; i < lTestNum; i++) { lImageWidth = atsRand32s(&sizegen); lImageHeight = atsRand32s(&sizegen); src8u= cvCreateImage(cvSize(lImageWidth, lImageHeight), IPL_DEPTH_8U, 1); src8s= cvCreateImage(cvSize(lImageWidth, lImageHeight), IPL_DEPTH_8S, 1); src32f = cvCreateImage(cvSize(lImageWidth, lImageHeight), IPL_DEPTH_32F, 1); src16 = cvCreateImage(cvSize(lImageWidth, lImageHeight), IPL_DEPTH_16S, 1); dst16 = cvCreateImage(cvSize(lImageWidth, lImageHeight), IPL_DEPTH_16S, 1); test16 = cvCreateImage(cvSize(lImageWidth, lImageHeight), IPL_DEPTH_16S, 1); buf = cvCreateImage(cvSize(lImageWidth, lImageHeight), IPL_DEPTH_32F, 1); dst32f = cvCreateImage(cvSize(lImageWidth, lImageHeight), IPL_DEPTH_32F, 1); test32f = cvCreateImage(cvSize(lImageWidth, lImageHeight), IPL_DEPTH_32F, 1); atsRandInit(&state,0,64,32); atsFillRandomImageEx(src8u, &state ); atsFillRandomImageEx(src8s, &state ); atsFillRandomImageEx(src32f, &state ); /* Calculating the kernels */ for(dx = 0; dx<=1; dx++) { dy=1-dx; atsCalcKernel(cv8u,dx,dy,CV_SCHARR,(char*)KerX,(char*)KerY,&KerLens,CV_ORIGIN_TL); KernelX = iplCreateConvKernel(KerLens.width,1,KerLens.width/2,0,KerX,0); KernelY = iplCreateConvKernel(1,KerLens.height,0,KerLens.height/2,KerY,0); /* Calculating the convolution */ atsConvert(src8u,src16); iplSetBorderMode(src16, IPL_BORDER_REPLICATE, IPL_SIDE_TOP|IPL_SIDE_BOTTOM|IPL_SIDE_RIGHT|IPL_SIDE_LEFT, 0); iplConvolveSep2D(src16,dst16,KernelX,KernelY); cvSobel(src8u,test16,dx,dy,CV_SCHARR); Error += iplNorm(dst16,test16,IPL_C); atsConvert(src8s,src16); iplSetBorderMode(src16, IPL_BORDER_REPLICATE, IPL_SIDE_TOP|IPL_SIDE_BOTTOM|IPL_SIDE_RIGHT|IPL_SIDE_LEFT, 0); iplSetBorderMode(src16, IPL_BORDER_REPLICATE, IPL_SIDE_TOP|IPL_SIDE_BOTTOM|IPL_SIDE_RIGHT|IPL_SIDE_LEFT, 0); iplConvolveSep2D(src16,dst16,KernelX,KernelY); cvSobel(src8s,test16,dx,dy,CV_SCHARR); Error += iplNorm(dst16,test16,IPL_C); atsCalcKernel(IPL_DEPTH_32F,dx,dy,CV_SCHARR,(char*)KerX,(char*)KerY,&KerLens,CV_ORIGIN_TL); KX = iplCreateConvKernelFP(KerLens.width,1,KerLens.width/2,0,(float*)KerX); KY = iplCreateConvKernelFP(1,KerLens.height,0,KerLens.height/2,(float*)KerY); iplSetBorderMode(src32f, IPL_BORDER_REPLICATE, IPL_SIDE_TOP|IPL_SIDE_BOTTOM|IPL_SIDE_RIGHT|IPL_SIDE_LEFT, 0); /* Calculating the convolution */ iplConvolveSep2DFP(src32f,dst32f,KX,KY); cvSobel(src32f,test32f,dx,dy,CV_SCHARR); /*for(i = 0; i<lImageHeight; i++) for(int j = 0; j<lImageWidth; j++) { float a = ((float*)(dst32f->imageData))[i*dst32f->widthStep/4+j]; float b = ((float*)(test32f->imageData))[i*test32f->widthStep/4+j]; } */ Error += iplNorm(test32f,dst32f,IPL_C); iplDeleteConvKernel(KernelX); iplDeleteConvKernel(KernelY); iplDeleteConvKernelFP(KX); iplDeleteConvKernelFP(KY); } /* Free Memory */ cvReleaseImage( &src8u ); cvReleaseImage( &src8s ); cvReleaseImage( &src32f ); cvReleaseImage( &src16 ); cvReleaseImage( &dst16 ); cvReleaseImage( &test16 ); cvReleaseImage( &dst32f ); cvReleaseImage( &test32f ); cvReleaseImage( &buf); } if(Error/lTestNum>=EPSILON)return TRS_FAIL; return TRS_OK; } /* fcaSobel8uC1R */