Exemplo n.º 1
0
int CV_CalcHistTest::prepare_test_case( int test_case_idx )
{
    int code = CV_BaseHistTest::prepare_test_case( test_case_idx );

    if( code > 0 )
    {
        CvRNG* rng = ts->get_rng();
        int i;

        for( i = 0; i <= CV_MAX_DIM; i++ )
        {
            if( i < cdims )
            {
                int nch = 1; //cvTsRandInt(rng) % 3 + 1;
                images[i] = cvCreateImage( img_size,
                    img_type == CV_8U ? IPL_DEPTH_8U : IPL_DEPTH_32F, nch );
                channels[i] = cvTsRandInt(rng) % nch;

                cvRandArr( rng, images[i], CV_RAND_UNI,
                    cvScalarAll(low), cvScalarAll(high) );
            }
            else if( i == CV_MAX_DIM && cvTsRandInt(rng) % 2 )
            {
                // create mask
                images[i] = cvCreateImage( img_size, IPL_DEPTH_8U, 1 );
                // make ~25% pixels in the mask non-zero
                cvRandArr( rng, images[i], CV_RAND_UNI,
                    cvScalarAll(-2), cvScalarAll(2) );
            }
        }
    }

    return code;
}
Exemplo n.º 2
0
int CV_CalcBackProjectTest::prepare_test_case( int test_case_idx )
{
    int code = CV_BaseHistTest::prepare_test_case( test_case_idx );

    if( code > 0 )
    {
        CvRNG* rng = ts->get_rng();
        int i, j, n, img_len = img_size.width*img_size.height;

        for( i = 0; i < CV_MAX_DIM + 3; i++ )
        {
            if( i < cdims )
            {
                int nch = 1; //cvTsRandInt(rng) % 3 + 1;
                images[i] = cvCreateImage( img_size,
                    img_type == CV_8U ? IPL_DEPTH_8U : IPL_DEPTH_32F, nch );
                channels[i] = cvTsRandInt(rng) % nch;

                cvRandArr( rng, images[i], CV_RAND_UNI,
                    cvScalarAll(low), cvScalarAll(high) );
            }
            else if( i == CV_MAX_DIM && cvTsRandInt(rng) % 2 )
            {
                // create mask
                images[i] = cvCreateImage( img_size, IPL_DEPTH_8U, 1 );
                // make ~25% pixels in the mask non-zero
                cvRandArr( rng, images[i], CV_RAND_UNI,
                    cvScalarAll(-2), cvScalarAll(2) );
            }
            else if( i > CV_MAX_DIM )
            {
                images[i] = cvCreateImage( img_size, images[0]->depth, 1 );
            }
        }

        cvTsCalcHist( images, hist[0], images[CV_MAX_DIM], channels );

        // now modify the images a bit to add some zeros go to the backprojection
        n = cvTsRandInt(rng) % (img_len/20+1);
        for( i = 0; i < cdims; i++ )
        {
            char* data = images[i]->imageData;
            for( j = 0; j < n; j++ )
            {
                int idx = cvTsRandInt(rng) % img_len;
                double val = cvTsRandReal(rng)*(high - low) + low;
                
                if( img_type == CV_8U )
                    ((uchar*)data)[idx] = (uchar)cvRound(val);
                else
                    ((float*)data)[idx] = (float)val;
            }
        }
    }

    return code;
}
Exemplo n.º 3
0
kalman::kalman(int winwidth, int winheight,CvRect rect)
{
	cvkalman = cvCreateKalman(4, 2, 0);
	process_noise = cvCreateMat(4, 1, CV_32FC1);
	measurement = cvCreateMat(2, 1, CV_32FC1);
	rng = cvRNG(-1);
	float A[4][4] = {
		1, 0, 1, 0,
		0, 1, 0, 1,
		0, 0, 1, 0,
		0, 0, 0, 1
	};
	this->rect = rect;
	memcpy(cvkalman->transition_matrix->data.fl,A,sizeof(A));
	cvSetIdentity(cvkalman->measurement_matrix,cvRealScalar(1));
	cvSetIdentity(cvkalman->process_noise_cov,cvRealScalar(1e-5));
	cvSetIdentity(cvkalman->measurement_noise_cov, cvRealScalar(1e-1));
	cvSetIdentity(cvkalman->error_cov_post, cvRealScalar(1));
	cvRandArr(&rng, cvkalman->state_post, CV_RAND_UNI, cvRealScalar(0), cvRealScalar(winheight>winwidth ? winwidth : winheight));
	//cvNamedWindow("kalman",1);
	img = cvCreateImage(cvSize(winwidth, winheight), 8, 3);
	cvSet(img, cvScalar(255, 255, 255, 0));
	cvRectangle(img, cvPoint(rect.x, rect.y), cvPoint(rect.x+rect.width, rect.y+rect.height), cvScalar(255, 0, 0));
	//cvShowImage("kalman",img);
	initlinklist(nl);
	sum = 0;
	num = 0;
}
Exemplo n.º 4
0
  pstable_l2_func(int _d, int _k, double _r, CvRNG& rng)
    : d(_d), k(_k), r(_r) {
    assert(sizeof(T) == CV_ELEM_SIZE1(cvtype));
    a = cvCreateMat(k, d, cvtype);
    b = cvCreateMat(k, 1, cvtype);
    r1 = cvCreateMat(k, 1, CV_32SC1);
    r2 = cvCreateMat(k, 1, CV_32SC1);
    cvRandArr(&rng, a, CV_RAND_NORMAL, cvScalar(0), cvScalar(1));
    cvRandArr(&rng, b, CV_RAND_UNI, cvScalar(0), cvScalar(r));
    cvRandArr(&rng, r1, CV_RAND_UNI,
	      cvScalar(std::numeric_limits<int>::min()),
	      cvScalar(std::numeric_limits<int>::max()));
    cvRandArr(&rng, r2, CV_RAND_UNI,
	      cvScalar(std::numeric_limits<int>::min()),
	      cvScalar(std::numeric_limits<int>::max()));
  }
Exemplo n.º 5
0
void CV_BaseHistTest::init_hist( int /*test_case_idx*/, int hist_i )
{
    if( gen_random_hist )
    {
        CvRNG* rng = ts->get_rng();
        CvArr* h = hist[hist_i]->bins;
        
        if( hist_type == CV_HIST_ARRAY )
        {
            cvRandArr( rng, h, CV_RAND_UNI,
                cvScalarAll(0), cvScalarAll(gen_hist_max_val) );
        }
        else
        {
            int i, j, total_size = 1, nz_count;
            int idx[CV_MAX_DIM];
            for( i = 0; i < cdims; i++ )
                total_size *= dims[i];

            nz_count = cvTsRandInt(rng) % MAX( total_size/4, 100 );
            nz_count = MIN( nz_count, total_size );

            // a zero number of non-zero elements should be allowed
            for( i = 0; i < nz_count; i++ )
            {
                for( j = 0; j < cdims; j++ )
                    idx[j] = cvTsRandInt(rng) % dims[j];
                cvSetRealND( h, idx, cvTsRandReal(rng)*gen_hist_max_val );
            }
        }
    }
}
Exemplo n.º 6
0
void GaussianDiag3D::AddNoise(double* vin, double* vout)
{
  /* Tirage aleatoire du bruit des parametres continus (m=0 sd=1) */
  cvRandArr(&this->rng_state,this->RandVectorMat,CV_RAND_NORMAL,cvRealScalar(0),cvRealScalar(1));
  vout[0] = vin[0] + this->cholcov[0]*this->RandVector[0];
  vout[1] = vin[1] + this->cholcov[4]*this->RandVector[1];
  vout[2] = vin[2] + this->cholcov[8]*this->RandVector[2];
}
Exemplo n.º 7
0
/* Fills array with random numbers */
void cvRand( CvRandState* state, CvArr* arr )
{
    if( !state )
    {
        cvError( CV_StsNullPtr, "cvRand", "Null pointer to RNG state", "cvcompat.h", 0 );
        return;
    }
    cvRandArr( &state->state, arr, state->disttype, state->param[0], state->param[1] );
}
Exemplo n.º 8
0
void GaussianND::Draw(double* mm, double* vout)
{
  int i,j;
  double* ptcholcov;

  /* Tirage aleatoire du bruit des parametres continus (m=0 sd=1) */
  cvRandArr(&this->rng_state,this->RandVectorMat,CV_RAND_NORMAL,cvRealScalar(0),cvRealScalar(1));
  
  /* Tir autour de la moyenne mean avec une covariance cov */    
  for(i=0,ptcholcov=this->cholcov;i<this->dim;i++,ptcholcov+=this->dim)
    {
      vout[i] = mm[i];
      for(j=0;j<this->dim;j++)
	vout[i]+=ptcholcov[j]*this->RandVector[j];      
    }
}
Exemplo n.º 9
0
int
main (int argc, char **argv)
{
    IplImage *img = 0;
    CvRNG rng = cvRNG(cvGetTickCount());
    CvRect inner[RECT_NUM], outer;
    int i;
    CvMat *rnum = cvCreateMat(RECT_NUM*2, 1, CV_32SC2);

    // (1)allocate and initialize an image
    img = cvCreateImage(cvSize(640, 480), IPL_DEPTH_8U, 3);
    cvRectangle(img, cvPoint(0,0), cvPoint(640,480), CV_RGB(100,100,100), CV_FILLED, 8, 0);

    // (2)generate rundom coordinates within a center space
    cvRandArr(&rng, rnum, CV_RAND_UNI, cvScalar(img->width/8, img->height/8, 0, 0), cvScalar(img->width*7./8, img->height*7./8,0,0));

    // (3)draw rectangles based on generated coordinates
    for(i=0; i<RECT_NUM; i++) {
        int x1 = rnum->data.i[i*4+0];
        int y1 = rnum->data.i[i*4+1];
        int x2 = rnum->data.i[i*4+2];
        int y2 = rnum->data.i[i*4+3];
        CvPoint tl = cvPoint(MIN(x1, x2), MIN(y1,y2));
        CvPoint br = cvPoint(MAX(x1, x2), MAX(y1,y2));
        cvRectangle(img, tl, br, CV_RGB(255,200,200), 2, 8, 0);
        inner[i] = cvRect(tl.x, tl.y, br.x-tl.x, br.y-tl.y);
    }

    // (4)find a minimum rectangle including all rectangles
    outer = inner[0];
    for(i=1; i<RECT_NUM; i++)
        outer = cvMaxRect(&outer, &inner[i]);
    cvRectangle(img, cvPoint(outer.x, outer.y),
                cvPoint(outer.x+outer.width, outer.y+outer.height), CV_RGB(255,0,0), 3, 8, 0);

    // (5)show the iamge, and quit when any key pressed
    cvNamedWindow ("BoundingRect", CV_WINDOW_AUTOSIZE);
    cvShowImage ("BoundingRect", img);
    cvWaitKey (0);

    cvDestroyWindow("BoundingRect");
    cvReleaseImage(&img);

    return 0;
}
Exemplo n.º 10
0
/*!
 * \brief Add gaussian noise to a point sequence. 
 *
 * \param[in]    input point sequence
 * \param[out]   output point sequence (noisy)
 */
static void add_awgn (ptseq proto, ptseq *dst)
{

	int num = proto.ptr->total;
	CvMat *noise = cvCreateMat(num, 2, CV_32FC1);
	//CvMat *ang_bias = cvCreateMat(num, 2, CV_32FC1);

	cvRandArr(&rng_state, noise, CV_RAND_NORMAL,
		  cvScalar(0,0,0,0), cvScalar(XVAR,YVAR,0,0));

	int i;
	for (i=0; i<num; i++) {
		CvPoint p = ptseq_get(proto, i);
		
		p.x += (int)cvmGet(noise, i, 0);
		p.y += (int)cvmGet(noise, i, 1);

		ptseq_add(*dst, p);
	}
}
Exemplo n.º 11
0
void CV_PyrSegmentationTest::run( int /*start_from*/ )
{
    const int level = 5;
    const double range = 20;

    int code = CvTS::OK;

    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 nPoints = 4;
    int block_size = 1000;

    CvMemStorage *storage;   /*   storage for connected component writing  */
    CvSeq *comp;

    CvRNG* rng = ts->get_rng();
    int i, j, iter;

    IplImage *image, *image_f, *image_s;
    CvSize size = {128, 128};
    const int threshold1 = 50, threshold2 = 50;

    rect[1].width = size.width;
    rect[1].height = size.height;
    a[1] = size.width*size.height - a[0] - a[2];

    OPENCV_CALL( storage = cvCreateMemStorage( block_size ) );

    for( iter = 0; iter < 2; iter++ )
    {
        int channels = iter == 0 ? 1 : 3;
        int mask[] = {0,0,0};

        image = cvCreateImage(size, 8, channels );
        image_s = cvCloneImage( image );
        image_f = cvCloneImage( image );

        if( channels == 1 )
        {
            int color1 = 30, color2 = 110, color3 = 180;

            cvSet( image, cvScalarAll(color1));
            cvFillPoly( image, &cp, &nPoints, 1, cvScalar(color2));
            cvFillPoly( image, &cp2, &nPoints, 1, cvScalar(color3));
        }
        else
        {
            CvScalar color1 = CV_RGB(30,30,30), color2 = CV_RGB(255,0,0), color3 = CV_RGB(0,255,0);

            assert( channels == 3 );
            cvSet( image, color1 );
            cvFillPoly( image, &cp, &nPoints, 1, color2);
            cvFillPoly( image, &cp2, &nPoints, 1, color3);
        }

        cvRandArr( rng, image_f, CV_RAND_UNI, cvScalarAll(0), cvScalarAll(range*2) );
        cvAddWeighted( image, 1, image_f, 1, -range, image_f );

        cvPyrSegmentation( image_f, image_s,
                           storage, &comp,
                           level, threshold1, threshold2 );

        if(comp->total != 3)
        {
            ts->printf( CvTS::LOG,
                "The segmentation function returned %d (not 3) components\n", comp->total );
            code = CvTS::FAIL_INVALID_OUTPUT;
            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 );

        /*{
            for( i = 0; i < 3; i++ )
            {
                CvRect r = dst_comp[i]->rect;
                cvRectangle( image_s, cvPoint(r.x,r.y), cvPoint(r.x+r.width,r.y+r.height),
                    CV_RGB(255,255,255), 3, 8, 0 );
            }

            cvNamedWindow( "test", 1 );
            cvShowImage( "test", image_s );
            cvWaitKey(0);
        }*/

        code = cvTsCmpEps2( ts, image, image_s, 10, false, "the output image" );
        if( code < 0 )
            goto _exit_;

        for( i = 0; i < 3; i++)
        {
            for( j = 0; j < 3; j++ )
            {
                if( !mask[j] && dst_comp[i]->area == a[j] &&
                    dst_comp[i]->rect.x == rect[j].x &&
                    dst_comp[i]->rect.y == rect[j].y &&
                    dst_comp[i]->rect.width == rect[j].width &&
                    dst_comp[i]->rect.height == rect[j].height )
                {
                    mask[j] = 1;
                    break;
                }
            }
            if( j == 3 )
            {
                ts->printf( CvTS::LOG, "The component #%d is incorrect\n", i );
                code = CvTS::FAIL_BAD_ACCURACY;
                goto _exit_;
            }
        }

        cvReleaseImage(&image_f);
        cvReleaseImage(&image);
        cvReleaseImage(&image_s);
    }

_exit_:

    cvReleaseMemStorage( &storage );
    cvReleaseImage(&image_f);
    cvReleaseImage(&image);
    cvReleaseImage(&image_s);

    if( code < 0 )
        ts->set_failed_test_info( code );
}
Exemplo n.º 12
0
int main()
{
	#define MAX_CLUSTER 5
	CvScalar color_tab[MAX_CLUSTER];
	IplImage* img = cvCreateImage(cvSize(500,500) , 8 , 3);
	CvRNG rng = cvRNG(0xffffffff);

	color_tab[0] = CV_RGB(255 ,   0 ,   0);
	color_tab[1] = CV_RGB(  0 , 255 ,   0);
	color_tab[2] = CV_RGB(100 , 100 , 255);
	color_tab[3] = CV_RGB(255 ,   0 , 255);
	color_tab[4] = CV_RGB(255 , 255 ,   0);

	cvNamedWindow("clusters" , 1);

	while(1)
	{
		int cluster_count = cvRandInt(&rng)%MAX_CLUSTER + 1;
		int sample_count = cvRandInt(&rng)%1000 + 1;
		CvMat* points = cvCreateMat(sample_count , 1 , CV_32FC2);
		CvMat* clusters = cvCreateMat(sample_count , 1 ,CV_32SC1);
		int k;
		for (k = 0 ; k<cluster_count ; k++)
		{
			CvPoint center;
			CvMat point_chunk;
			center.x = cvRandInt(&rng)%(img->width);
			center.y = cvRandInt(&rng)%(img->height);

			cvGetRows( points , &point_chunk ,
					   k*sample_count/cluster_count ,
					   (k+1)*sample_count/cluster_count ,
					   1);

			cvRandArr(&rng , &point_chunk , CV_RAND_NORMAL ,
					  cvScalar(center.x , center.y , 0 , 0),
					  cvScalar(img->width/6 , img->height/6 , 0 , 0) );
		}

		int i;
		for (i = 0; i<sample_count/2 ; i++)
		{//random find two and exchange
			CvPoint2D32f* pt1 = (CvPoint2D32f*)points->data.fl + cvRandInt(&rng)%sample_count;
			CvPoint2D32f* pt2 = (CvPoint2D32f*)points->data.fl + cvRandInt(&rng)%sample_count;
			CvPoint2D32f temp;
			CV_SWAP(*pt1 , *pt2 , temp);
		}

		cvKMeans2(points , cluster_count , clusters ,
				  cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER,10,1.0),
				  1, 0, 0, 0, 0);

		cvZero(img);
		for (i = 0; i<sample_count/2 ; i++)
		{
			CvPoint2D32f pt = ((CvPoint2D32f*)points->data.fl)[i];
			int cluster_idx = clusters->data.i[i];
			cvCircle(img , cvPointFrom32f(pt), 2, color_tab[cluster_idx] ,
					CV_FILLED, 8, 0);
		}

		cvReleaseMat(&points);
		cvReleaseMat(&clusters);

		cvShowImage("clusters" , img);

		int key = cvWaitKey(0);
		if(key == 27)
				break;
	}//while(1)

	return 0;
}
Exemplo n.º 13
0
int main(int argc, char **argv)
{

	float priors[] = { 1.0, 10.0 };	// Edible vs poisonos weights

	CvMat *var_type;
	CvMat *data;				// jmh add
	data = cvCreateMat(20, 30, CV_8U);	// jmh add

	var_type = cvCreateMat(data->cols + 1, 1, CV_8U);
	cvSet(var_type, cvScalarAll(CV_VAR_CATEGORICAL));	// all these vars 
	// are categorical
	CvDTree *dtree;
	dtree = new CvDTree;
	dtree->train(data, CV_ROW_SAMPLE, responses, 0, 0, var_type, missing, CvDTreeParams(8,	// max depth
																						10,	// min sample count
																						0,	// regression accuracy: N/A here
																						true,	// compute surrogate split, 
																						//   as we have missing data
																						15,	// max number of categories 
																						//   (use sub-optimal algorithm for
																						//   larger numbers)
																						10,	// cross-validations 
																						true,	// use 1SE rule => smaller tree
																						true,	// throw away the pruned tree branches
																						priors	// the array of priors, the bigger 
																						//   p_weight, the more attention
																						//   to the poisonous mushrooms
				 )
		);

	dtree->save("tree.xml", "MyTree");
	dtree->clear();
	dtree->load("tree.xml", "MyTree");

#define MAX_CLUSTERS 5
	CvScalar color_tab[MAX_CLUSTERS];
	IplImage *img = cvCreateImage(cvSize(500, 500), 8, 3);
	CvRNG rng = cvRNG(0xffffffff);

	color_tab[0] = CV_RGB(255, 0, 0);
	color_tab[1] = CV_RGB(0, 255, 0);
	color_tab[2] = CV_RGB(100, 100, 255);
	color_tab[3] = CV_RGB(255, 0, 255);
	color_tab[4] = CV_RGB(255, 255, 0);

	cvNamedWindow("clusters", 1);

	for (;;) {
		int k, cluster_count = cvRandInt(&rng) % MAX_CLUSTERS + 1;
		int i, sample_count = cvRandInt(&rng) % 1000 + 1;
		CvMat *points = cvCreateMat(sample_count, 1, CV_32FC2);
		CvMat *clusters = cvCreateMat(sample_count, 1, CV_32SC1);

		/* generate random sample from multivariate 
		   Gaussian distribution */
		for (k = 0; k < cluster_count; k++) {
			CvPoint center;
			CvMat point_chunk;
			center.x = cvRandInt(&rng) % img->width;
			center.y = cvRandInt(&rng) % img->height;
			cvGetRows(points, &point_chunk,
					  k * sample_count / cluster_count,
					  k == cluster_count - 1 ? sample_count :
					  (k + 1) * sample_count / cluster_count);
			cvRandArr(&rng, &point_chunk, CV_RAND_NORMAL,
					  cvScalar(center.x, center.y, 0, 0),
					  cvScalar(img->width / 6, img->height / 6, 0, 0));
		}

		/* shuffle samples */
		for (i = 0; i < sample_count / 2; i++) {
			CvPoint2D32f *pt1 = (CvPoint2D32f *) points->data.fl +
				cvRandInt(&rng) % sample_count;
			CvPoint2D32f *pt2 = (CvPoint2D32f *) points->data.fl +
				cvRandInt(&rng) % sample_count;
			CvPoint2D32f temp;
			CV_SWAP(*pt1, *pt2, temp);
		}

		cvKMeans2(points, cluster_count, clusters,
				  cvTermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 10, 1.0));
		cvZero(img);
		for (i = 0; i < sample_count; i++) {
			CvPoint2D32f pt = ((CvPoint2D32f *) points->data.fl)[i];
			int cluster_idx = clusters->data.i[i];
			cvCircle(img, cvPointFrom32f(pt), 2,
					 color_tab[cluster_idx], CV_FILLED);
		}

		cvReleaseMat(&points);
		cvReleaseMat(&clusters);

		cvShowImage("clusters", img);

		int key = cvWaitKey(0);
		if (key == 27)			// 'ESC'
			break;
	}
}
Exemplo n.º 14
0
CV_IMPL void cvRandShuffle( CvArr* arr, CvRNG* rng, double iter_factor )
{
    CV_FUNCNAME( "cvRandShuffle" );

    __BEGIN__;

    const int sizeof_int = (int)sizeof(int);
    CvMat stub, *mat = (CvMat*)arr;
    int i, j, k, iters, delta = 0;
    int cont_flag, arr_size, elem_size, cols, step;
    const int pair_buf_sz = 100;
    int* pair_buf = (int*)cvStackAlloc( pair_buf_sz*sizeof(pair_buf[0])*2 );
    CvMat _pair_buf = cvMat( 1, pair_buf_sz*2, CV_32S, pair_buf );
    CvRNG _rng = cvRNG(-1);
    uchar* data = 0;
    int* idata = 0;
    
    if( !CV_IS_MAT(mat) )
        CV_CALL( mat = cvGetMat( mat, &stub ));

    if( !rng )
        rng = &_rng;

    cols = mat->cols;
    step = mat->step;
    arr_size = cols*mat->rows;
    iters = cvRound(iter_factor*arr_size)*2;
    cont_flag = CV_IS_MAT_CONT(mat->type);
    elem_size = CV_ELEM_SIZE(mat->type);
    if( elem_size % sizeof_int == 0 && (cont_flag || step % sizeof_int == 0) )
    {
        idata = mat->data.i;
        step /= sizeof_int;
        elem_size /= sizeof_int;
    }
    else
        data = mat->data.ptr;

    for( i = 0; i < iters; i += delta )
    {
        delta = MIN( iters - i, pair_buf_sz*2 );
        _pair_buf.cols = delta;
        cvRandArr( rng, &_pair_buf, CV_RAND_UNI, cvRealScalar(0), cvRealScalar(arr_size) );
        
        if( cont_flag )
        {
            if( idata )
                for( j = 0; j < delta; j += 2 )
                {
                    int* p = idata + pair_buf[j]*elem_size, *q = idata + pair_buf[j+1]*elem_size, t;
                    for( k = 0; k < elem_size; k++ )
                        CV_SWAP( p[k], q[k], t );
                }
            else
                for( j = 0; j < delta; j += 2 )
                {
                    uchar* p = data + pair_buf[j]*elem_size, *q = data + pair_buf[j+1]*elem_size, t;
                    for( k = 0; k < elem_size; k++ )
                        CV_SWAP( p[k], q[k], t );
                }
        }
        else
        {
            if( idata )
                for( j = 0; j < delta; j += 2 )
                {
                    int idx1 = pair_buf[j], idx2 = pair_buf[j+1], row1, row2;
                    int* p, *q, t;
                    row1 = idx1/step; row2 = idx2/step;
                    p = idata + row1*step + (idx1 - row1*cols)*elem_size;
                    q = idata + row2*step + (idx2 - row2*cols)*elem_size;
                    
                    for( k = 0; k < elem_size; k++ )
                        CV_SWAP( p[k], q[k], t );
                }
            else
                for( j = 0; j < delta; j += 2 )
                {
                    int idx1 = pair_buf[j], idx2 = pair_buf[j+1], row1, row2;
                    uchar* p, *q, t;
                    row1 = idx1/step; row2 = idx2/step;
                    p = data + row1*step + (idx1 - row1*cols)*elem_size;
                    q = data + row2*step + (idx2 - row2*cols)*elem_size;
                    
                    for( k = 0; k < elem_size; k++ )
                        CV_SWAP( p[k], q[k], t );
                }
        }
    }

    __END__;
}
int main(int argc, char** argv)
{
    const float A[] = { 1, 1, 0, 1 };//状态转移矩阵
    
    IplImage* img = cvCreateImage( cvSize(500,500), 8, 3 );//创建显示所用的图像
    CvKalman* kalman = cvCreateKalman( 2, 1, 0 );//创建cvKalman数据结构,状态向量为2维,观测向量为1维,无激励输入维
    CvMat* state = cvCreateMat( 2, 1, CV_32FC1 ); //(phi, delta_phi) 定义了状态变量
    CvMat* process_noise = cvCreateMat( 2, 1, CV_32FC1 );// 创建两行一列CV_32FC1的单通道浮点型矩阵
    CvMat* measurement = cvCreateMat( 1, 1, CV_32FC1 ); //定义观测变量
    CvRNG rng = cvRNG(-1);//初始化一个随机序列函数
    char code = -1;

    cvZero( measurement );//观测变量矩阵置零
    cvNamedWindow( "Kalman", 1 );

    for(;;)
    {		//用均匀分布或者正态分布的随机数填充输出数组state
        cvRandArr( &rng, state, CV_RAND_NORMAL, cvRealScalar(0), cvRealScalar(0.1) );//状态state
        memcpy( kalman->transition_matrix->data.fl, A, sizeof(A));//初始化状态转移F矩阵
        
        //cvSetIdentity()用法:把数组中除了行数与列数相等以外的所有元素的值都设置为0;行数与列数相等的元素的值都设置为1
        //我们将(第一个前假象阶段的)后验状态初始化为一个随机值
        cvSetIdentity( kalman->measurement_matrix, cvRealScalar(1) );//观测矩阵H
        cvSetIdentity( kalman->process_noise_cov, cvRealScalar(1e-5) );//过程噪声Q
        cvSetIdentity( kalman->measurement_noise_cov, cvRealScalar(1e-1) );//观测噪声R 
        cvSetIdentity( kalman->error_cov_post, cvRealScalar(1));//后验误差协方差
        cvRandArr( &rng, kalman->state_post, CV_RAND_NORMAL, cvRealScalar(0), cvRealScalar(0.1) );//校正状态
        
        //在时机动态系统上开始预测
        
        for(;;)
        {
            #define calc_point(angle)                                      \
                cvPoint( cvRound(img->width/2 + img->width/3*cos(angle)),  \
                         cvRound(img->height/2 - img->width/3*sin(angle))) 

            float state_angle = state->data.fl[0];
            CvPoint state_pt = calc_point(state_angle);
            
            const CvMat* prediction = cvKalmanPredict( kalman, 0 );//计算下一个时间点的预期值,激励项输入为0
            float predict_angle = prediction->data.fl[0];
            CvPoint predict_pt = calc_point(predict_angle);
            
            float measurement_angle;
            CvPoint measurement_pt;

            cvRandArr( &rng, measurement, CV_RAND_NORMAL, cvRealScalar(0),
                       cvRealScalar(sqrt(kalman->measurement_noise_cov->data.fl[0])) );

            /* generate measurement */
            cvMatMulAdd( kalman->measurement_matrix, state, measurement, measurement );
            //cvMatMulAdd(src1,src2,src3,dst)就是实现dist=src1*src2+src3; 

            measurement_angle = measurement->data.fl[0];
            measurement_pt = calc_point(measurement_angle);
            
            //调用Kalman滤波器并赋予其最新的测量值,接下来就是产生过程噪声,然后对状态乘以传递矩阵F完成一次迭代并加上我们产生的过程噪声
            /* plot points */
            #define draw_cross( center, color, d )                                 \
                cvLine( img, cvPoint( center.x - d, center.y - d ),                \
                             cvPoint( center.x + d, center.y + d ), color, 1, CV_AA, 0); \
                cvLine( img, cvPoint( center.x + d, center.y - d ),                \
                             cvPoint( center.x - d, center.y + d ), color, 1, CV_AA, 0 )

            cvZero( img );
            //使用上面宏定义的函数
            draw_cross( state_pt, CV_RGB(255,255,255), 3 );//白色,状态点
            draw_cross( measurement_pt, CV_RGB(255,0,0), 3 );//红色,测量点
            draw_cross( predict_pt, CV_RGB(0,255,0), 3 );//绿色,估计点
            cvLine( img, state_pt, measurement_pt, CV_RGB(255,0,0), 3, CV_AA, 0 );
            cvLine( img, state_pt, predict_pt, CV_RGB(255,255,0), 3, CV_AA, 0 );
            
            cvKalmanCorrect( kalman, measurement );//校正新的测量值

            cvRandArr( &rng, process_noise, CV_RAND_NORMAL, cvRealScalar(0),
                       cvRealScalar(sqrt(kalman->process_noise_cov->data.fl[0])));//设置正态分布过程噪声
            cvMatMulAdd( kalman->transition_matrix, state, process_noise, state );

            cvShowImage( "Kalman", img );
			//当按键按下时,开始新的循环,初始矩阵可能会改变,所以移动速率会改变
            code = (char) cvWaitKey( 100 );
            if( code > 0 )
                break;
        }
        if( code == 27 || code == 'q' || code == 'Q' )
            break;
    }
    
    cvDestroyWindow("Kalman");

    return 0;
}
Exemplo n.º 16
0
int CV_CalcBackProjectPatchTest::prepare_test_case( int test_case_idx )
{
    int code = CV_BaseHistTest::prepare_test_case( test_case_idx );

    if( code > 0 )
    {
        CvRNG* rng = ts->get_rng();
        int i, j, n, img_len = img_size.width*img_size.height;

        patch_size.width = cvTsRandInt(rng) % img_size.width + 1;
        patch_size.height = cvTsRandInt(rng) % img_size.height + 1;
        patch_size.width = MIN( patch_size.width, 30 );
        patch_size.height = MIN( patch_size.height, 30 );

        factor = 1.;
        method = cvTsRandInt(rng) % CV_CompareHistTest::MAX_METHOD;

        for( i = 0; i < CV_MAX_DIM + 2; i++ )
        {
            if( i < cdims )
            {
                int nch = 1; //cvTsRandInt(rng) % 3 + 1;
                images[i] = cvCreateImage( img_size,
                    img_type == CV_8U ? IPL_DEPTH_8U : IPL_DEPTH_32F, nch );
                channels[i] = cvTsRandInt(rng) % nch;

                cvRandArr( rng, images[i], CV_RAND_UNI,
                    cvScalarAll(low), cvScalarAll(high) );
            }
            else if( i >= CV_MAX_DIM )
            {
                images[i] = cvCreateImage(
                    cvSize(img_size.width - patch_size.width + 1,
                           img_size.height - patch_size.height + 1),
                    IPL_DEPTH_32F, 1 );
            }
        }

        cvTsCalcHist( images, hist[0], 0, channels );
        cvNormalizeHist( hist[0], factor );

        // now modify the images a bit
        n = cvTsRandInt(rng) % (img_len/10+1);
        for( i = 0; i < cdims; i++ )
        {
            char* data = images[i]->imageData;
            for( j = 0; j < n; j++ )
            {
                int idx = cvTsRandInt(rng) % img_len;
                double val = cvTsRandReal(rng)*(high - low) + low;
                
                if( img_type == CV_8U )
                    ((uchar*)data)[idx] = (uchar)cvRound(val);
                else
                    ((float*)data)[idx] = (float)val;
            }
        }
    }

    return code;
}