void
kinect_depth_handler (carmen_kinect_depth_message *kinect_depth_message)
{
	char *depth_img_filename, *depth_rgb_filename;
	char *depth_img_composed_path, *depth_rgb_composed_path;
	IplImage *depth_img, *depth_rgb_img;

	create_kinect_depth_img_filename_from_timestamp(message_index, &depth_img_filename);
	create_kinect_rgb_depth_img_filename_from_timestamp(message_index, &depth_rgb_filename);

	compose_output_path(output_dir_name, depth_img_filename, &depth_img_composed_path);
	compose_output_path(output_dir_name, depth_rgb_filename, &depth_rgb_composed_path);

	create_image_from_depth_buffer(kinect_depth_message->depth, &depth_img, kinect_depth_message->size, kinect_depth_message->height, kinect_depth_message->width);
	create_rgb_image_from_depth_buffer(kinect_depth_message->depth, &depth_rgb_img, kinect_depth_message->height, kinect_depth_message->width);

	cvSaveImage(depth_img_composed_path, depth_img, NULL);
	cvSaveImage(depth_rgb_composed_path, depth_rgb_img, NULL);

	printf("depth image saved: %s\n", depth_img_composed_path);

	free(depth_img_filename);
	free(depth_rgb_filename);
	free(depth_img_composed_path);
	free(depth_rgb_composed_path);

	cvRelease((void**) &depth_img);
	cvRelease((void**) &depth_rgb_img);

	message_index++;
}
void
save_image_to_file(carmen_bumblebee_basic_stereoimage_message *stereo_image, int camera)
{
	char *left_img_filename, *right_img_filename;
	char *left_composed_path, *right_composed_path;
	IplImage *left_img, *right_img;

	create_stereo_filename_from_timestamp(stereo_image->timestamp, &left_img_filename, &right_img_filename, camera);
	compose_output_path(output_dir_name, left_img_filename, &left_composed_path);
	compose_output_path(output_dir_name, right_img_filename, &right_composed_path);

	create_image_from_rgb_buffer(stereo_image->raw_left, &left_img, stereo_image->width, stereo_image->height);
	create_image_from_rgb_buffer(stereo_image->raw_right, &right_img, stereo_image->width, stereo_image->height);

	cvSaveImage(left_composed_path, left_img, NULL);
	cvSaveImage(right_composed_path, right_img, NULL);

	printf("left image saved: %s\n", left_composed_path);
	printf("right image saved: %s\n", right_composed_path);

	free(left_img_filename);
	free(left_composed_path);
	free(right_img_filename);
	free(right_composed_path);

	cvRelease((void**) &left_img);
	cvRelease((void**) &right_img);
}
void
save_stereo_image_to_file(carmen_simple_stereo_disparity_message *stereo_message, int camera)
{
	stereo_util util = get_stereo_instance(camera, 0, 0);

	char *disparity_img_filename, *reference_img_filename;
	char *disparity_composed_path, *reference_composed_path;
	IplImage *disparity_img, *reference_img;

	create_disparity_filename_from_timestamp(stereo_message->timestamp, &reference_img_filename, &disparity_img_filename, camera);
	compose_output_path(output_dir_name, disparity_img_filename, &disparity_composed_path);
	compose_output_path(output_dir_name, reference_img_filename, &reference_composed_path);

	create_image_from_float_buffer(stereo_message->disparity, &disparity_img, util.width, util.height);
	create_image_from_rgb_buffer(stereo_message->reference_image, &reference_img, util.width, util.height);

	cvSaveImage(disparity_composed_path, disparity_img, NULL);
	cvSaveImage(reference_composed_path, reference_img, NULL);

	printf("disparity image saved: %s\n", disparity_composed_path);
	printf("reference image saved: %s\n", reference_composed_path);

	free(disparity_img_filename);
	free(disparity_composed_path);
	free(reference_img_filename);
	free(reference_composed_path);

	cvRelease((void**) &disparity_img);
	cvRelease((void**) &reference_img);
}
Beispiel #4
0
float Histogram::calcEMD2(const Histogram* histogram1, const Histogram* histogram2, int distanceType)
{
    Signature* signature1 = histogram1->signature();
    Signature* signature2 = histogram2->signature();
    
    float emd2 = cvCalcEMD2(signature1, signature2, distanceType);
    
    cvRelease(&signature1);
    cvRelease(&signature2);
    
    return emd2;
}
Beispiel #5
0
static IplImage*
icvRetrieveImage( void* obj )
{
    IplImage* img = 0;

    if( CV_IS_IMAGE(obj) )
        img = (IplImage*)obj;
    else if( CV_IS_MAT(obj) )
    {
        CvMat* m = (CvMat*)obj;
        img = cvCreateImageHeader( cvSize(m->cols,m->rows),
                        CV_MAT_DEPTH(m->type), CV_MAT_CN(m->type) );
        cvSetData( img, m->data.ptr, m->step );
        img->imageDataOrigin = (char*)m->refcount;
        m->data.ptr = 0; m->step = 0;
        cvReleaseMat( &m );
    }
    else if( obj )
    {
        cvRelease( &obj );
        CV_Error( CV_StsUnsupportedFormat, "The object is neither an image, nor a matrix" );
    }

    return img;
}
Beispiel #6
0
static CvMat*
icvRetrieveMatrix( void* obj )
{
    CvMat* m = 0;

    CV_FUNCNAME( "icvRetrieveMatrix" );

    __BEGIN__;

    if( CV_IS_MAT(obj) )
        m = (CvMat*)obj;
    else if( CV_IS_IMAGE(obj) )
    {
        IplImage* img = (IplImage*)obj;
        CvMat hdr, *src = cvGetMat( img, &hdr );
        CV_CALL( m = cvCreateMat( src->rows, src->cols, src->type ));
        CV_CALL( cvCopy( src, m ));
        cvReleaseImage( &img );
    }
    else if( obj )
    {
        cvRelease( &obj );
        CV_ERROR( CV_StsUnsupportedFormat, "The object is neither an image, nor a matrix" );
    }

    __END__;

    return m;
}
void haarwrapper_destroy(t_haarwrapper* hc) {
  if (hc == NULL)
    return;

  cvReleaseMemStorage(&hc->storage);
  cvRelease((void**)&hc->cascade);

  free(hc);
}
Beispiel #8
0
void ArrayTest::clear()
{
    for( size_t i = 0; i < test_array.size(); i++ )
    {
        for( size_t j = 0; j < test_array[i].size(); j++ )
            cvRelease( &test_array[i][j] );
    }
    BaseTest::clear();
}
Beispiel #9
0
/*
 * Release OpenCV specific structure(i.e CvMat, IplImage..) from memory and delete from hashtable.
 */
void
release_object(void *ptr)
{
  if (ptr) {
    unregister_object(ptr);
    try {
      cvRelease(&ptr);
    }
    catch (cv::Exception& e) {
      raise_cverror(e);
    }
  }
}
Beispiel #10
0
IplImage* get128image(int argc,int **argv)
{
  IplImage *sorceimage=0,*resizedimage;
  char *imagename;
  imagename = argc > 1 ? argv[1] : "./none.png";
  sorceimage = cvLoadImage(imagename, CV_LOAD_IMAGE_COLOR);
  //sorceimage = cvLoadImage(imagename,CV_LOAD_IMAGE_GRAYSCALE );
  if(sorceimage == 0)
    return 0;
  resizedimage=cvCreateImage(cvSize(128,128),IPL_DEPTH_8U,3);
  cvResize(sorceimage,resizedimage,CV_INTER_NN);
  cvRelease(&sorceimage);
  return resizedimage;
}
Beispiel #11
0
void process_image( char* buffer, int len )
{
	GPtrArray *markers;    
    int i;
    CvMat *m = cvCreateMatHeader (len, 1, CV_8UC1);
    cvSetData (m, buffer, 1);
    IplImage *color = cvDecodeImage (m, CV_LOAD_IMAGE_COLOR);
    assert (color != NULL);

    IplImage *bw = cvCreateImage(cvGetSize(color), color->depth, 1);
    cvCvtColor (color, bw, CV_RGB2GRAY);

	koki_camera_params_t params;
	params.size.x = bw->width;
	params.size.y = bw->height;
	params.principal_point.x = params.size.x / 2;
	params.principal_point.y = params.size.y / 2;
	params.focal_length.x = 571.0;
	params.focal_length.y = 571.0;
	markers = koki_find_markers(koki, bw, 0.11, &params);

	assert(markers != NULL);
	for (i=0; i<markers->len; i++){

		koki_marker_t *marker;
		marker = g_ptr_array_index(markers, i);

		printf("\n(%d) Marker #%d:\n", i, marker->code);
    }
    cvRelease ((void**)&bw);

    cvShowImage ("Source", color);
    cvWaitKey (0);
    cvRelease ((void**)&color);
    cvRelease ((void**)&m);

}
Beispiel #12
0
 void convert8UC3To32FC1Gray(const CvArr *src, CvArr *dst, CvArr *tmpRGBF)
 {
     bool inTmpRGBF = tmpRGBF == NULL;
     if ( inTmpRGBF )
     {
         CvSize sz(cvGetSize(src));
         tmpRGBF = cvCreateMat(sz.height, sz.width, CV_32FC3);
     }        
     
     cvConvertScale(src, tmpRGBF, 1.0/255.0);        
     cvCvtColor(tmpRGBF, dst, CV_RGB2GRAY);
     
     if ( inTmpRGBF )
         cvRelease(&tmpRGBF);
 }
void CvArrTest::clear()
{
    if( test_array )
    {
        int i, j, n;

        for( i = 0; i < max_arr; i++ )
        {
            n = test_array[i].size();
            for( j = 0; j < n; j++ )
                cvRelease( &test_array[i][j] );
        }
    }
    delete[] hdr;
    hdr = 0;
    max_hdr = 0;
    CvTest::clear();
}
Beispiel #14
0
void
kinect_video_handler (carmen_kinect_video_message *kinect_video_message)
{
	char *video_img_filename;
	char *video_img_composed_path;
	IplImage *video_img;

	create_kinect_video_img_filename_from_timestamp(message_index, &video_img_filename);
	compose_output_path(output_dir_name, video_img_filename, &video_img_composed_path);

	create_image_from_rgb_buffer(kinect_video_message->video, &video_img, kinect_video_message->width, kinect_video_message->height);

	cvSaveImage(video_img_composed_path, video_img, NULL);

	printf("video image saved: %s\n", video_img_composed_path);

	free(video_img_filename);
	free(video_img_composed_path);

	cvRelease((void**) &video_img);
}
Beispiel #15
0
static CvMat*
icvRetrieveMatrix( void* obj )
{
    CvMat* m = 0;

    if( CV_IS_MAT(obj) )
        m = (CvMat*)obj;
    else if( CV_IS_IMAGE(obj) )
    {
        IplImage* img = (IplImage*)obj;
        CvMat hdr, *src = cvGetMat( img, &hdr );
        m = cvCreateMat( src->rows, src->cols, src->type );
        cvCopy( src, m );
        cvReleaseImage( &img );
    }
    else if( obj )
    {
        cvRelease( &obj );
        CV_Error( CV_StsUnsupportedFormat, "The object is neither an image, nor a matrix" );
    }

    return m;
}
Beispiel #16
0
CV_IMPL void*
cvLoad( const char* filename, CvMemStorage* memstorage,
        const char* name, const char** _real_name )
{
    void* ptr = 0;
    const char* real_name = 0;
    cv::FileStorage fs(cvOpenFileStorage(filename, memstorage, CV_STORAGE_READ));

    CvFileNode* node = 0;

    if( !fs.isOpened() )
        return 0;

    if( name )
    {
        node = cvGetFileNodeByName( *fs, 0, name );
    }
    else
    {
        int i, k;
        for( k = 0; k < (*fs)->roots->total; k++ )
        {
            CvSeq* seq;
            CvSeqReader reader;

            node = (CvFileNode*)cvGetSeqElem( (*fs)->roots, k );
            CV_Assert(node != NULL);
            if( !CV_NODE_IS_MAP( node->tag ))
                return 0;
            seq = node->data.seq;
            node = 0;

            cvStartReadSeq( seq, &reader, 0 );

            // find the first element in the map
            for( i = 0; i < seq->total; i++ )
            {
                if( CV_IS_SET_ELEM( reader.ptr ))
                {
                    node = (CvFileNode*)reader.ptr;
                    goto stop_search;
                }
                CV_NEXT_SEQ_ELEM( seq->elem_size, reader );
            }
        }

stop_search:
        ;
    }

    if( !node )
        CV_Error( CV_StsObjectNotFound, "Could not find the/an object in file storage" );

    real_name = cvGetFileNodeName( node );
    ptr = cvRead( *fs, node, 0 );

    // sanity check
    if( !memstorage && (CV_IS_SEQ( ptr ) || CV_IS_SET( ptr )) )
        CV_Error( CV_StsNullPtr,
        "NULL memory storage is passed - the loaded dynamic structure can not be stored" );

    if( cvGetErrStatus() < 0 )
    {
        cvRelease( (void**)&ptr );
        real_name = 0;
    }

    if( _real_name)
    {
    if (real_name)
    {
        *_real_name = (const char*)cvAlloc(strlen(real_name));
            memcpy((void*)*_real_name, real_name, strlen(real_name));
    } else {
        *_real_name = 0;
    }
    }

    return ptr;
}
Beispiel #17
0
int ArrayTest::prepare_test_case( int test_case_idx )
{
    int code = 1;
    size_t max_arr = test_array.size();
    vector<vector<Size> > sizes(max_arr);
    vector<vector<Size> > whole_sizes(max_arr);
    vector<vector<int> > types(max_arr);
    size_t i, j;
    RNG& rng = ts->get_rng();
    bool is_image = false;

    for( i = 0; i < max_arr; i++ )
    {
        size_t sizei = std::max(test_array[i].size(), (size_t)1);
        sizes[i].resize(sizei);
        types[i].resize(sizei);
        whole_sizes[i].resize(sizei);
    }

    get_test_array_types_and_sizes( test_case_idx, sizes, types );

    for( i = 0; i < max_arr; i++ )
    {
        size_t sizei = test_array[i].size();
        for( j = 0; j < sizei; j++ )
        {
            unsigned t = randInt(rng);
            bool create_mask = true, use_roi = false;
            CvSize size = cvSize(sizes[i][j]), whole_size = size;
            CvRect roi = CV_STRUCT_INITIALIZER;

            is_image = !cvmat_allowed ? true : iplimage_allowed ? (t & 1) != 0 : false;
            create_mask = (t & 6) == 0; // ~ each of 3 tests will use mask
            use_roi = (t & 8) != 0;
            if( use_roi )
            {
                whole_size.width += randInt(rng) % 10;
                whole_size.height += randInt(rng) % 10;
            }

            cvRelease( &test_array[i][j] );
            if( size.width > 0 && size.height > 0 &&
                types[i][j] >= 0 && (i != MASK || create_mask) )
            {
                if( use_roi )
                {
                    roi.width = size.width;
                    roi.height = size.height;
                    if( whole_size.width > size.width )
                        roi.x = randInt(rng) % (whole_size.width - size.width);

                    if( whole_size.height > size.height )
                        roi.y = randInt(rng) % (whole_size.height - size.height);
                }

                if( is_image )
                {
                    test_array[i][j] = cvCreateImage( whole_size,
                        icvTsTypeToDepth[CV_MAT_DEPTH(types[i][j])], CV_MAT_CN(types[i][j]) );
                    if( use_roi )
                        cvSetImageROI( (IplImage*)test_array[i][j], roi );
                }
                else
                {
                    test_array[i][j] = cvCreateMat( whole_size.height, whole_size.width, types[i][j] );
                    if( use_roi )
                    {
                        CvMat submat, *mat = (CvMat*)test_array[i][j];
                        cvGetSubRect( test_array[i][j], &submat, roi );
                        submat.refcount = mat->refcount;
                        *mat = submat;
                    }
                }
            }
        }
    }

    test_mat.resize(test_array.size());
    for( i = 0; i < max_arr; i++ )
    {
        size_t sizei = test_array[i].size();
        test_mat[i].resize(sizei);
        for( j = 0; j < sizei; j++ )
        {
            CvArr* arr = test_array[i][j];
            test_mat[i][j] = cv::cvarrToMat(arr);
            if( !test_mat[i][j].empty() )
                fill_array( test_case_idx, (int)i, (int)j, test_mat[i][j] );
        }
    }

    return code;
}
void THISCLASS::OnStep() {
	std::vector<Particle> rejectedparticles;

	// Get and check input image
	IplImage *inputimage = cvCloneImage(mCore->mDataStructureImageBinary.mImage);
	IplImage *outputImage = mCore->mDataStructureImageBinary.mImage;
	//mCore->mDataStructureImageBinary.mImage;
	if (! inputimage) {
		AddError(wxT("No input image."));
		return;
	}
	if (inputimage->nChannels != 1) {
		AddError(wxT("The input image is not a grayscale image."));
		return;
	}
	cvZero(outputImage);

	// We clear the ouput vector
	mParticles.clear();

	// Initialization
	Particle tmpParticle; // Used to put the calculated value in memory
	CvMoments moments; // Used to calculate the moments
	std::vector<Particle>::iterator j; // Iterator used to stock the particles by size

	// We allocate memory to extract the contours from the binary image
	CvMemStorage* storage = cvCreateMemStorage(0);
	CvSeq* contour = 0;


	// Init blob extraxtion
	CvContourScanner blobs = cvStartFindContours(inputimage, storage, sizeof(CvContour), CV_RETR_LIST, CV_CHAIN_APPROX_NONE);

	// This is used to correct the position in case of ROI
	CvRect rectROI;
	if (inputimage->roi != NULL) {
		rectROI = cvGetImageROI(inputimage);
	} else {
		rectROI.x = 0;
		rectROI.y = 0;
	}

	while ((contour = cvFindNextContour(blobs)) != NULL) {
		// Computing the moments
		cvMoments(contour, &moments);

		// Computing particle area
		tmpParticle.mArea = moments.m00;
		tmpParticle.mCenter.x = (float)(rectROI.x + (moments.m10 / moments.m00 + 0.5));  // moments using Green theorem
		tmpParticle.mCenter.y = (float)(rectROI.y + (moments.m01 / moments.m00 + 0.5));  // m10 = x direction, m01 = y direction, m00 = area as edicted in theorem

		// Selection based on area
		if ((mAreaSelection == false) || ((tmpParticle.mArea <= mMaxArea) && (tmpParticle.mArea >= mMinArea)))
		{
			tmpParticle.mCompactness = GetContourCompactness(contour);
			if ((mCompactnessSelection == false) || ((tmpParticle.mCompactness > mMinCompactness) && (tmpParticle.mCompactness < mMaxCompactness)))
			{
				double tempValue = cvGetCentralMoment(&moments, 2, 0) - cvGetCentralMoment(&moments, 0, 2);
				tmpParticle.mOrientation = atan(2 * cvGetCentralMoment(&moments, 1, 1) / (tempValue + sqrt(tempValue * tempValue + 4 * cvGetCentralMoment(&moments, 1, 1) * cvGetCentralMoment(&moments, 1, 1))));
				if ((mOrientationSelection == false) || (((tmpParticle.mOrientation > mMinOrientation) && (tmpParticle.mOrientation < mMaxOrientation)) || ((tmpParticle.mOrientation > mMinOrientation + PI) && (tmpParticle.mOrientation < mMaxOrientation + PI)) || ((tmpParticle.mOrientation > mMinOrientation - PI) && (tmpParticle.mOrientation < mMaxOrientation - PI))))
				{
					cvDrawContours(outputImage, contour, cvScalarAll(255), cvScalarAll(255), 0, CV_FILLED);
					// Check if we have already enough particles
					if (mParticles.size() == mMaxNumber)
					{
						// If the particle is bigger than the smallest stored particle, store it, else do nothing
						if (tmpParticle.mArea > mParticles.back().mArea)
						{
							// Find the place were it must be inserted, sorted by size
							for (j = mParticles.begin(); (j != mParticles.end()) && (tmpParticle.mArea < (*j).mArea); j++);

							// Fill unused values
							tmpParticle.mID = -1;
							tmpParticle.mIDCovariance = -1;

							// Insert the particle
							mParticles.insert(j, tmpParticle);
							// Remove the smallest one
							mParticles.pop_back();
						}
					}
					else
					{
						// The particle is added at the correct place
						// Find the place were it must be inserted, sorted by size
						for (j = mParticles.begin(); (j != mParticles.end()) && (tmpParticle.mArea < (*j).mArea); j++);

						// Fill unused values
						tmpParticle.mID = -1;
						tmpParticle.mIDCovariance = -1;

						// Insert the particle
						mParticles.insert(j, tmpParticle);
					}
				}
			}
		}
		else
		{
			rejectedparticles.push_back(tmpParticle);
		}
		cvRelease((void**)&contour);
	}
	contour = cvEndFindContours(&blobs);

	// If we need to display the particles
	/* if(trackingimg->GetDisplay())
	{
		for(j=rejectedparticles.begin();j!=rejectedparticles.end();j++)
		{
			trackingimg->DrawCircle(cvPoint((int)(((*j).p).x),(int)(((*j).p).y)),CV_RGB(255,0,0));
		}
		for(j=particles.begin();j!=particles.end();j++)
		{
			trackingimg->DrawCircle(cvPoint((int)(((*j).p).x),(int)(((*j).p).y)),CV_RGB(0,255,0));
			trackingimg->Cover(cvPoint((int)(((*j).p).x),(int)(((*j).p).y)),CV_RGB(255,0,0),2);
		}
	} */

	cvReleaseImage(&inputimage);
	cvRelease((void**)&contour);
	cvReleaseMemStorage(&storage);

	// Set these particles
	mCore->mDataStructureParticles.mParticles = &mParticles;

	// Let the DisplayImage know about our image
	DisplayEditor de(&mDisplayOutput);
	if (de.IsActive()) {
		de.SetParticles(&mParticles);
		de.SetMainImage(mCore->mDataStructureImageBinary.mImage);
	}
}
/**
 *  deconstructor
 */
adaBoostBinary::~adaBoostBinary()
{
	cvRelease((void **)&weight);
	free(labelsign);
	free(iter_res);
}
/**
 *Choose the weak classifier using the fast method just based on the distribution of the weight
 *@param data The positive and negative training samples
 *@param label the ground truth label of the training samples
 *@param current_best_classifier The current weak classifier for selection.
 *@param bindexlabel The BOOL value to ensure that each feature can only be choose once
 *@param imith To control the shape of the sign function
 *@param curIteration The current iteration number of strong classifier
 */
int adaBoostBinary::choosefeature_fast(CvMat *data, CvMat *label, lda_classifier *current_best_classifier,bool *bindexlabel, float imith, int curIteration)
{
	int sample_num=pos_sample_num+neg_sample_num;
	int size_dim=data->cols;
	int paraNum=1;
	int numInpara=size_dim/paraNum;
	lda_classifier *para_best_classifier = (lda_classifier*)malloc(sizeof(lda_classifier)*paraNum);
	CvMat *labelneg=cvCreateMat(sample_num, 1, CV_8UC1);
	for(int i=0; i<sample_num; i++){
		if(label->data.ptr[i]>0){
			labelneg->data.ptr[i]=0;
		}
		else{
			labelneg->data.ptr[i]=1;
		}
	}
	float *para_res=(float*)malloc(sizeof(float)*sample_num*paraNum);
	//#pragma omp parallel for
	for(int j1=0; j1<paraNum; j1++)
	{
		para_best_classifier[j1].minerror=-10;
		for(int j2=0; j2<numInpara; j2++)
		{
			int j=j1*numInpara+j2;
			// if((j+1)%8<=1) continue;
			CvMat *score=cvCreateMat(sample_num,1,CV_32FC1);
			///find the current best error and threshold
			CvScalar meanpos, meanneg, stdpos, stdneg;
			for(int t=0; t<sample_num; t++) score->data.fl[t] = cvmGet(data, t, j);
			//printf("arow=%d, acol=%d, brow=%d, bcol=%d\n",score->rows,score->cols,label->rows, label->cols);
			cvAvgSdv(score, &meanpos, &stdpos, label);
			cvAvgSdv(score, &meanneg, &stdneg, labelneg);

			float threshold=0.0;
			if(stdpos.val[0]+stdneg.val[0]>0.0) threshold = (meanpos.val[0]*stdneg.val[0]+meanneg.val[0]*stdpos.val[0])/(stdpos.val[0]+stdneg.val[0]);
			else threshold = (meanpos.val[0]+meanneg.val[0])/2;
			if(threshold==0.0) continue;
			float cur_error=0.0;
			int thr_sign=1;
			if(meanpos.val[0]<meanneg.val[0])
			{
				thr_sign=-1;
				threshold=-threshold;
			}
			for(int t=0; t<sample_num; t++)
			{
				float curscore=score->data.fl[t]*thr_sign-threshold;
				float htx=curscore/sqrt(curscore*curscore+imith*imith);
				cur_error+=weight->data.fl[t]*htx*labelsign[t];

			}
			if (cur_error> para_best_classifier[j1].minerror&&bindexlabel[j]==false)
			{
				para_best_classifier[j1].minerror = cur_error;
				printf("*%f ",cur_error);
				para_best_classifier[j1].bindex = j;
				para_best_classifier[j1].pro_thresh = threshold;
				para_best_classifier[j1].thr_sign = thr_sign;

				// float check_error=0.0f;
				for(int t=0;t<sample_num; t++)
				{
					float curscore=score->data.fl[t]*thr_sign-threshold;
					float htx=curscore/sqrt(curscore*curscore+imith*imith);
					//para_res[j1*sample_num+t]=curscore/sqrt(curscore*curscore+imith*imith);
					para_res[j1*sample_num+t]=htx;
				}
			}
			cvRelease((void **)&score);

		}//for para inter pixle j2
	}//for para outer pixel j1
	for(int i=0; i<paraNum; i++)
	{
		if(current_best_classifier->minerror>para_best_classifier[i].minerror)
		{
			current_best_classifier->minerror=para_best_classifier[i].minerror;
			current_best_classifier->bindex=para_best_classifier[i].bindex;
			current_best_classifier->pro_thresh=para_best_classifier[i].pro_thresh;
			current_best_classifier->thr_sign=para_best_classifier[i].thr_sign;

			for(int t=0; t<sample_num; t++) iter_res[curIteration*sample_num+t]=para_res[i*sample_num+t];
		}
	}
	bindexlabel[current_best_classifier->bindex]=true;
	cvRelease((void **)&labelneg);
	free(para_res);
	free(para_best_classifier);
	return 1;
}
int CvArrTest::prepare_test_case( int test_case_idx )
{
    int code = 1;
    CvSize** sizes = (CvSize**)malloc( max_arr*sizeof(sizes[0]) );
    CvSize** whole_sizes = (CvSize**)malloc( max_arr*sizeof(whole_sizes[0]) );
    int** types = (int**)malloc( max_arr*sizeof(types[0]) );
    int i, j, total = 0;
    CvRNG* rng = ts->get_rng();
    bool is_image = false;
    bool is_timing_test = false;

    CV_FUNCNAME( "CvArrTest::prepare_test_case" );

    __BEGIN__;

    is_timing_test = ts->get_testing_mode() == CvTS::TIMING_MODE;

    if( is_timing_test )
    {
        if( !get_next_timing_param_tuple() )
        {
            code = -1;
            EXIT;
        }
    }

    for( i = 0; i < max_arr; i++ )
    {
        int count = test_array[i].size();
        count = MAX(count, 1);
        sizes[i] = (CvSize*)malloc( count*sizeof(sizes[i][0]) );
        types[i] = (int*)malloc( count*sizeof(types[i][0]) );
        whole_sizes[i] = (CvSize*)malloc( count*sizeof(whole_sizes[i][0]) );
    }

    if( !is_timing_test )
        get_test_array_types_and_sizes( test_case_idx, sizes, types );
    else
    {
        get_timing_test_array_types_and_sizes( test_case_idx, sizes, types,
                                               whole_sizes, &is_image );
    }

    for( i = 0; i < max_arr; i++ )
    {
        int count = test_array[i].size();
        total += count;
        for( j = 0; j < count; j++ )
        {
            unsigned t = cvRandInt(rng);
            bool create_mask = true, use_roi = false;
            CvSize size = sizes[i][j], whole_size = size;
            CvRect roi = {0,0,0,0};

            if( !is_timing_test )
            {
                is_image = !cvmat_allowed ? true : iplimage_allowed ? (t & 1) != 0 : false;
                create_mask = (t & 6) == 0; // ~ each of 3 tests will use mask
                use_roi = (t & 8) != 0;
                if( use_roi )
                {
                    whole_size.width += cvRandInt(rng) % 10;
                    whole_size.height += cvRandInt(rng) % 10;
                }
            }
            else
            {
                whole_size = whole_sizes[i][j];
                use_roi = whole_size.width != size.width || whole_size.height != size.height;
                create_mask = cvReadInt(find_timing_param( "use_mask" ),0) != 0;
            }

            cvRelease( &test_array[i][j] );
            if( size.width > 0 && size.height > 0 &&
                types[i][j] >= 0 && (i != MASK || create_mask) )
            {
                if( use_roi )
                {
                    roi.width = size.width;
                    roi.height = size.height;
                    if( whole_size.width > size.width )
                    {
                        if( !is_timing_test )
                            roi.x = cvRandInt(rng) % (whole_size.width - size.width);
                        else
                            roi.x = 1;
                    }

                    if( whole_size.height > size.height )
                    {
                        if( !is_timing_test )
                            roi.y = cvRandInt(rng) % (whole_size.height - size.height);
                        else
                            roi.y = 1;
                    }
                }

                if( is_image )
                {
                    CV_CALL( test_array[i][j] = cvCreateImage( whole_size,
                        icvTsTypeToDepth[CV_MAT_DEPTH(types[i][j])],
                        CV_MAT_CN(types[i][j]) ));
                    if( use_roi )
                        cvSetImageROI( (IplImage*)test_array[i][j], roi );
                }
                else
                {
                    CV_CALL( test_array[i][j] = cvCreateMat( whole_size.height,
                                                whole_size.width, types[i][j] ));
                    if( use_roi )
                    {
                        CvMat submat, *mat = (CvMat*)test_array[i][j];
                        cvGetSubRect( test_array[i][j], &submat, roi );
                        submat.refcount = mat->refcount;
                        *mat = submat;
                    }
                }
            }
        }
    }

    if( total > max_hdr )
    {
        delete hdr;
        max_hdr = total;
        hdr = new CvMat[max_hdr];
    }

    total = 0;
    for( i = 0; i < max_arr; i++ )
    {
        int count = test_array[i].size();
        test_mat[i] = count > 0 ? hdr + total : 0;
        for( j = 0; j < count; j++ )
        {
            CvArr* arr = test_array[i][j];
            CvMat* mat = &test_mat[i][j];
            if( !arr )
                memset( mat, 0, sizeof(*mat) );
            else if( CV_IS_MAT( arr ))
            {
                *mat = *(CvMat*)arr;
                mat->refcount = 0;
            }
            else
                cvGetMat( arr, mat, 0, 0 );
            if( mat->data.ptr )
                fill_array( test_case_idx, i, j, mat );
        }
        total += count;
    }

    __END__;

    for( i = 0; i < max_arr; i++ )
    {
        if( sizes )
            free( sizes[i] );
        if( whole_sizes )
            free( whole_sizes[i] );
        if( types )
            free( types[i] );
    }

    free( sizes );
    free( whole_sizes );
    free( types );

    return code;
}
//--------------------------------------------------------------
void eyeTracker::update(ofxCvGrayscaleImage & grayImgFromCam, float threshold, float minSize, float maxSize,  float minSquareness) {

    //threshold?
    //threshold = thresh;

    grayImgPreWarp.setFromPixels(grayImgFromCam.getPixels(), grayImgFromCam.width, grayImgFromCam.height);		// TODO: there's maybe an unnecessary grayscale image (and copy) here...

    if( flipX || flipY ) {
        grayImgPreWarp.mirror(flipY, flipX);
    }

    /*  // before we were scaling and translating, but this is removed for now

     if (fabs(xoffset-1) > 0.1f || fabs(yoffset-1) > 0.1f){
    	grayImgPreWarp.translate(xoffset, yoffset);
    }

    if (fabs(scalef-1) > 0.1f){
    	grayImgPreWarp.scale(scalef, scalef);
    }*/

    grayImg = grayImgPreWarp;



    grayImgPreModification = grayImg;
    grayImg.blur(5);

    if (bUseContrast == true) {
        grayImg.applyBrightnessContrast(brightness,contrast);
    }

    if (bUseGamma == true) {
        grayImg.applyMinMaxGamma(gamma);
    }

    grayImg += edgeMask;

    threshImg = grayImg;


    threshImg.contrastStretch();
    threshImg.threshold(threshold, true);


    // the dilation of a 640 x 480 image is very slow, so let's just do a ROI near the thing we like:

    threshImg.setROI(currentEyePoint.x-50, currentEyePoint.y-50, 100,100);	// 200 pix ok?
    if (bUseDilate == true) {
        for (int i = 0; i < nDilations; i++) {
            threshImg.dilate();
        }
    }
    threshImg.resetROI();



    bFoundOne = false;

    int		whoFound = -1;

    int num = contourFinder.findContours(threshImg, minSize, maxSize, 100, false, true);
    if( num ) {

        for(int k = 0; k < num; k++) {



            float ratio =	contourFinder.blobs[k].boundingRect.width < contourFinder.blobs[k].boundingRect.height ?
                            contourFinder.blobs[k].boundingRect.width / contourFinder.blobs[k].boundingRect.height :
                            contourFinder.blobs[k].boundingRect.height / contourFinder.blobs[k].boundingRect.width;

            float arcl = contourFinder.blobs[k].length;
            float area = contourFinder.blobs[k].area;
            float compactness = (float)((arcl*arcl/area)/FOUR_PI);

            if (bUseCompactnessTest	== true && compactness > maxCompactness) {
                continue;
            }


            //printf("compactness %f \n", compactness);

            //lets ignore rectangular blobs
            if( ratio > minSquareness) {
                currentEyePoint = contourFinder.blobs[k].centroid;
                currentNormPoint.x = currentEyePoint.x;
                currentNormPoint.y = currentEyePoint.y;

                currentNormPoint.x /= w;
                currentNormPoint.y /= h;


                bFoundOne = true;
                whoFound = k;

                break;
            }
        }
    }

    if (bFoundOne && whoFound != -1) {



        // do some convex hull stuff:
        CvSeq* ptseq = cvCreateSeq( CV_SEQ_KIND_GENERIC|CV_32SC2, sizeof(CvContour),sizeof(CvPoint), storage );
        CvSeq* hull;
        CvPoint pt0;

        for(int i = 0; i < contourFinder.blobs[whoFound].nPts; i++ ) {

            pt0.x = contourFinder.blobs[whoFound].pts[i].x;
            pt0.y = contourFinder.blobs[whoFound].pts[i].y;
            cvSeqPush( ptseq, &pt0 );

        }
        hull = cvConvexHull2( ptseq, 0, CV_CLOCKWISE, 0 );
        int hullcount = hull->total;



        // -------------------------------- TRY TO GET A GOOD ELLIPSE HELLS YEAH !!

        int MYN = hullcount;
        float x[MYN], y[MYN];
        double p[6];
        double ellipseParam[5];
        float theta;
        FitEllipse fitter;
        for (int i=0; i<MYN; i++) {
            CvPoint pt = **CV_GET_SEQ_ELEM( CvPoint*, hull, i);
            x[i] = pt.x;
            y[i] =  pt.y;
        }
        double xc, yc;
        double xa, ya;
        double la, lb;
        fitter.apply(x,y,MYN);
        p[0] = fitter.Axx;
        p[1] = fitter.Axy;
        p[2] = fitter.Ayy;
        p[3] = fitter.Ax;
        p[4] = fitter.Ay;
        p[5] = fitter.Ao;

        bool bOk = solve_ellipse(p,ellipseParam);

        ofxCvBlob temp;


        if (bOk == true) {

            //float *params_ellipse = pupilGeometries[whichEye].params_ellipse;
            float axis_a = ellipseParam[0];
            float axis_b = ellipseParam[1];
            float cx 	 = ellipseParam[2];
            float cy 	 = ellipseParam[3];
            theta	 = ellipseParam[4];
            float aspect = axis_b/axis_a;

            for (int i = 0; i < 5; i++) {
                eyeTrackedEllipse.ellipseParam[i] = ellipseParam[i];
            }

            //theta = ofRandom(0,TWO_PI);


            int resolution = 24;

            ofxPoint2f ptsForRotation[resolution];

            for (int i=0; i<resolution; i++) {
                float t = TWO_PI * (float)i/(float)resolution;
                float ex = cx + (axis_a * cos(t ));
                float ey = cy + (axis_b * sin(t ));
                ptsForRotation[i].set(ex,ey);
            }

            for (int i=0; i<resolution; i++) {
                ptsForRotation[i].rotate(theta * RAD_TO_DEG, ofxPoint2f(cx, cy));
            }

            currentEyePoint.set(cx, cy);
            currentNormPoint.x = currentEyePoint.x;
            currentNormPoint.y = currentEyePoint.y;
            currentNormPoint.x /= w;
            currentNormPoint.y /= h;


        } else {


            bFoundOne = false;

        }

        cvRelease((void **)&hull);

    }