hello evryone, im new in C++ programing.

currently i working on my final year project. at the first place, im study in INFO COMM. ,more specific in network management area but since my project is assigned by my lecturer and the project itself involved some programming skill, i gt to study in c++.

i has been learnt c++ basic function. my project is some sort of speech recognition system which integrated with vision part, and im currently working in this vision part too.

the vision involved the OPENCV source file in order for human face tracking.

i gt a open source code from opencvsite suit my project requirment, and i had try very hard to understand what is the function of each part.

i able to track a human face, and printf "sucessful" msg for each successful detection, and sofore the "failure" msg for when no detection, after this, send the result to another machine via tcp socket connection.

now my problem is , i have to write in a function to set a threshold for detection. mean, when detection successful, i would not send a msg (success/failure) immediately but wait for maybe 2secs, if there is still detection occurs/ no more detection, den send a final msg to another machine.

[ to summarize, the purpose is to send single result for all the detections within 2sec, such that can prevent the traffic being hoged by keep on sending result]

i had read thru many posts and also c++ cookbook guide , but i still cannot find my need. can anyone please give me some clue mayb what function can implement or other better suggestion way to get the same result i want ?

this is my current outcomes for testing result:
<tracking part> <result>
elapsed time 192ms detected //send "successful" to another host
elapsed time 176ms no object //send "successful" to another host
. . . //send " " to another host
. . . //send " l" to another host
elapsed time 176ms detected //send "successful" to another host
elapsed time 219ms detected //send "successful" to another host

my expected outcome
<tracking part> <result>
elapsed time 192ms detected // hold
elapsed time 176ms no object //hold
. . . //hold
. . . //hold
elapsed time 176ms detected //hold
elapsed time 219ms detected // finalise result ( successful>failure)
// send final result "succcessful" to another host

below is part of opencv source code involve tracking, can anyone point to me how to implement the above expexted function i need ? your opinion and guide i willbe greatly appreciated. thank you!

if( cascade )
   
	{ double t = (double)cvGetTickCount();
        CvSeq* faces = cvHaarDetectObjects( small_img, cascade, storage,
                                            1.1, /*increase search scale by 10% each pass*/
											6, /*drop group of fewer than 2 detection*/
											0/*CV_HAAR_DO_CANNY_PRUNING*/,
                                            cvSize(25, 15) );/*use xml default for smallest search scale*/
        t = (double)cvGetTickCount() - t;
        printf( "detection time = %gms\n", t/((double)cvGetTickFrequency()*1000.) );
		
	
        for( i = 0; i < (faces ? faces->total : 0); i++ ) /* draw circle*/

		{
			
            CvRect* r = (CvRect*)cvGetSeqElem( faces, i );
            CvPoint center;/*CvPoint is a structure which has just two members they store x coordinate and the y coordinate*/
            int radius;
            center.x = cvRound((r->x + r->width*0.5)*scale);
            center.y = cvRound((r->y + r->height*0.5)*scale);
            radius = cvRound((r->width + r->height)*0.25*scale);
            cvCircle( img, center, radius, colors[i%8], 3, 8, 0 );

			printf("detection_successful\n");
			 /* print msg when object is detected*/
			
		}
		 	
     printf("no_object\n"); /* print msg2 when no object is detected */
    }

	//testing
	
	//testing
    cvShowImage( "result", img );
    cvReleaseImage( &gray );
    cvReleaseImage( &small_img );

}

Since this isn't you whole code, I can't tell what goes where. But I can give you a snippet:

std::clock_t start = std::clock();;
int detected = 1;
while(1) // this would be your detection loop
{
    if ( /* face detection failed */  )
        detected = 0;

    if ( std::clock() - start >= 200) // 200 ms
    {
        //Send "detected" over the socket
        // if detected == 0, one or more frames failed
        // if it's still '1', all frames passed the test
        start = std::clock(); //reset clock
        detected = 1; // reset detection
    }
}

That should give you an idea on how I would solve the problem. Don't forget to #include <ctime> Just out of curiosity: Did you come up with this detection code yourself, or did you just use the OpenCV-haar example?

thx! niek_e.
im get the code from opencv sample file, i juz add in some of simple code adjust it as my need ^^. now i try to work with this part. do u nid me to attach full code on here ?

sorry, im really dumb...

i put in the code inside but some part still not sure how to implement, right before your code, should i add in any thing? cuz one of the compile error is state that "missing ';' before ':' . and at the middle part i add like this

std::clock_t start = std::clock();;
	int detected = 1;
	while(1) // this would be your detection loop
 	{   
                     if ( printf("no_object\n") ) /* face detection failed */      
	     detected = 0; 
                     if ( std::clock() - start >= 200) // 200 ms 
	         {     printf("detected") //Send "detected" over the socket  

            /* here i not yet implement tcp socket, so i put printf to see  the output to test */

	        if (detected == 0) // if detected == 0, one or more frames failed    
  
            /* sorry, this part i dunnoe how to add,as well as below */			                        
                     else printf("detected" // if it's still '1', all frames passed the test   
 
	start = std::clock(); //reset clock     
               detected = 1; // reset detection  
		}
	}

this is the full code for facedect.c

sorry, i really dun understand.

Attachments
#include "cv.h"
#include "highgui.h"
#include <ctime>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <math.h>
#include <float.h>
#include <limits.h>
#include <time.h>
#include <ctype.h>
#ifdef _EiC
#define WIN32
#endif

/*There are three parts in which first of all the program is divided ..

In the first part the program checks whether the Camera is connected and is it able to return frames to the program

If yes it detects the face from the camera/video file (or it also loads from a video file if you have specified) ...

If no

Then it checks for Lena.jpg if found it detects the face in the same....

If no

It checks for a file a text file where it can find the file names of each and every picture in which

The faces are to be detected..The text file should have the names of the pictures along with the extensions */

/*about CvMemStorage==>


typedef struct CvMemStorage

{

struct CvMemBlock* bottom;/* first allocated block */

/* struct CvMemBlock* top; /* the current memory block - top of the stack */

/* struct CvMemStorage* parent; /* borrows new blocks from */

/*int block_size; /* block size */

/*int free_space; /* free space in the top block (in bytes) */

/*} CvMemStorage;*/


/*CvMemStorage is a dynamic data structure used to store dynamically growing

data structures such as sequences contours Graphs..*/



static CvMemStorage* storage = 0;
static CvHaarClassifierCascade* cascade = 0;

/*This is the function which is going detect and draw the circle round the face..*/
void detect_and_draw( IplImage* image );

/*WE assign the .xml file name which is the main basic thing which allows us to detect objects

and depending upon this file the object is realized.*/
const char* cascade_name =
    "Mouth.xml";
/*    "haarcascade_profileface.xml";This .xml file is available by default in the \root..\openCV\data folder and you may verify the same..*/

int main( int argc, char** argv )
{
    CvCapture* capture = 0;
    IplImage *frame, *frame_copy = 0;/*Another frame for Operations..frame_copy*/

/*Explanation of strncmp

int strncmp ( const char * str1, const char * str2, size_t num );

str1

C string to be compared.

str2

C string to be compared.

num

Maximim number of characters to compare.

*/
    int optlen = strlen("--cascade=");
    const char* input_name;

    if( argc > 1 && strncmp( argv[1], "--cascade=", optlen ) == 0 )
    {
        cascade_name = argv[1] + optlen;
        input_name = argc > 2 ? argv[2] : 0;
    }
    else
		/*If you are running the program elsewhere other than the folder in which the program facedetect.c is

present by default then put the full path to the .xml file in the inverted commmas"

and replace "forward slash by a backslash" in the below line*/


/* try to comment this below line and then please use the command line for this program because the program does not

terminate after the execution and follow the same trick for many things*/


    {
        cascade_name = "../../data/haarcascades/Mouth.xml";
        input_name = argc > 1 ? argv[1] : 0;
		/*Use of this line comes down..

If input name not given in the command line then load Zero

Ponder about this above line for sometime

Give some time to this program,..Once again if you have read about arguments the main function has then

you should be able to get this line*/


    }

    cascade = (CvHaarClassifierCascade*)cvLoad( cascade_name, 0, 0, 0 );
    
    if( !cascade )
    {
        fprintf( stderr, "ERROR: Could not load classifier cascade\n" );
        fprintf( stderr,
        "Usage: facedetect --cascade=\"<cascade_path>\" [filename|camera_index]\n" );
        return -1;
    }
    storage = cvCreateMemStorage(0);
    
    if( !input_name || (isdigit(input_name[0]) && input_name[1] == '\0') )
		/*If input name is zero then capture from cam else it must be a

video file and load it with the help of capture from cam*/


        capture = cvCaptureFromCAM( !input_name ? 0 : input_name[0] - '0' );
    else
        capture = cvCaptureFromAVI( input_name ); 
	/*The part where the capture from the camera starts */

    cvNamedWindow( "result", 1 );

    if( capture )

    {  

        for(;;)/*Infinite loop until we hit the escape buttom*/

        {
            if( !cvGrabFrame( capture ))/*If no frame break off just from this loop*/
                break;
            frame = cvRetrieveFrame( capture );/*If no frame break off just from this loop*/
            if( !frame )
			
                break;
            if( !frame_copy )/*here frame copy =0 ==> !0=1 and hence it enters the loop*/

                frame_copy = cvCreateImage( cvSize(frame->width,frame->height),
                                            IPL_DEPTH_8U, frame->nChannels ); /*Copy the frame*/


            if( frame->origin == IPL_ORIGIN_TL )
			/*if the origin is top left then procees else flip the frame and then copy by using cvFlip*/

                cvCopy( frame, frame_copy, 0 );
            else
                cvFlip( frame, frame_copy, 0 );
	
		detect_and_draw( frame_copy );
				/*Send this frame to the function which wil detect and dram the circle*/



		
          



            if( cvWaitKey( 10 ) >= 0 )/*If you hit the escape key you will exit*/
                break;
        }

        cvReleaseImage( &frame_copy );
        cvReleaseCapture( &capture );
    }

	/*This part loads the image from the command line if image not found in the command line it loads the lena.jpg ..*/
    else
    {
        const char* filename = input_name ? input_name : (char*)"neg-0009.jpg";
        IplImage* image = cvLoadImage( filename, 1 );

        if( image )
        {
            detect_and_draw( image );
            cvWaitKey(0);
            cvReleaseImage( &image );
        }
        else
        {
            /* assume it is a text file containing the
               list of the image filenames to be processed - one per line */
            FILE* f = fopen( filename, "rt" );
            if( f )
            {
                char buf[1000+1];
                while( fgets( buf, 1000, f ) )
                {
                    int len = (int)strlen(buf);
                    while( len > 0 && isspace(buf[len-1]) )
                        len--;
                    buf[len] = '\0';
                    image = cvLoadImage( buf, 1 );
                    if( image )
                    {
                        detect_and_draw( image );
                        cvWaitKey(0);
                        cvReleaseImage( &image );
                    }
                }
                fclose(f);
            }
        }

    }
    
    cvDestroyWindow("result");

    return 0;
}

void detect_and_draw( IplImage* img )
{
    static CvScalar colors[] = 
    {
        {{0,0,255}},
        {{0,128,255}},
        {{0,255,255}},
        {{0,255,0}},
        {{255,128,0}},
        {{255,255,0}},
        {{255,0,0}},
        {{255,0,255}}
    };

    double scale = 1.3;
    IplImage* gray = cvCreateImage( cvSize(img->width,img->height), 8, 1 );
    IplImage* small_img = cvCreateImage( cvSize( cvRound (img->width/scale),
                         cvRound (img->height/scale)),
						 /* here cvRound is just rounding off the double to an integer so that we have a perfect integer valueswith good accuracy*/

                     8, 1 );
    int i;


    cvCvtColor( img, gray, CV_BGR2GRAY );
    cvResize( gray, small_img, CV_INTER_LINEAR );
    cvEqualizeHist( small_img, small_img );
    cvClearMemStorage( storage );






    if( cascade )
   
	{ double t = (double)cvGetTickCount();
        CvSeq* faces = cvHaarDetectObjects( small_img, cascade, storage,
                                            1.1, /*increase search scale by 10% each pass*/
											6, /*drop group of fewer than 2 detection*/
											0/*CV_HAAR_DO_CANNY_PRUNING*/,
                                            cvSize(25, 15) );/*use xml default for smallest search scale*/
        t = (double)cvGetTickCount() - t;
        printf( "detection time = %gms\n", t/((double)cvGetTickFrequency()*1000.) );
		
	
        for( i = 0; i < (faces ? faces->total : 0); i++ ) /* draw circle*/

		{
			
            CvRect* r = (CvRect*)cvGetSeqElem( faces, i );
            CvPoint center;/*CvPoint is a structure which has just two members they store x coordinate and the y coordinate*/
            int radius;
            center.x = cvRound((r->x + r->width*0.5)*scale);
            center.y = cvRound((r->y + r->height*0.5)*scale);
            radius = cvRound((r->width + r->height)*0.25*scale);
            cvCircle( img, center, radius, colors[i%8], 3, 8, 0 );

			printf("detection_successful\n");
			 /* print msg when object is detected*/
			
		}
		 	
     printf("no_object\n"); /* print msg2 when no object is detected */
    }

	//testing
	std::clock_t start = std::clock();;
	int detected = 1;
	while(1) // this would be your detection loop
	{   
		if ( printf("no_object\n") ) /* face detection failed */      
			detected = 0;  

		if ( std::clock() - start >= 200) // 200 ms 
		{        printf("detected")//Send "detected" over the socket      

			  if (detected == 0)	// if detected == 0, one or more frames failed      
			                        
			else printf("detected")	// if it's still '1', all frames passed the test    
			start = std::clock(); //reset clock     
			detected = 1; // reset detection  
		}
	}
	//testing
    cvShowImage( "result", img );
    cvReleaseImage( &gray );
    cvReleaseImage( &small_img );

}

No. Not even close, sorry

There's a loop somewhere in your program right? One that keeps sampling and detecting?
The while(1) loop in my example represents that loop. So you don't need my while(1) anywhere in your code, I just thought I'd put it there to clarify thing. (which failed)

I'll try to put it differently:

Start clock
Main loop in your program
    Get an image
    Check if detection was succesfull, if not: detected = 0
    Check if 200 ms have passed since 'start', if yes:
        Send the detected  flag (indicates succes of detection)
        Reset detection flag, detected = 1;
        Reset Timer, start = std::clock();
end loop

[edit]
Ah, you reposted...

Anyway. The main loop in your program is this:

for(;;)/*Infinite loop until we hit the escape buttom*/

        {

hmmm ,sorry. mayb the this part is not the main loop for detection result

for(;;)/*Infinite loop until we hit the escape buttom*/

this part is for checking whether the camera successful to grab a image or not ( or shld say camera is set or not )

at the bottom part, (as shown at below) this part is when camera grabed an image, it will circle it if detection, else do nothing. so , is it i shld add in your code in this part instead 1st part?

if( cascade )
   
	{ double t = (double)cvGetTickCount();
        CvSeq* faces = cvHaarDetectObjects( small_img, cascade, storage,
                                            1.1, /*increase search scale by 10% each pass*/
											6, /*drop group of fewer than 2 detection*/
											0/*CV_HAAR_DO_CANNY_PRUNING*/,
                                            cvSize(25, 15) );/*use xml default for smallest search scale*/
        t = (double)cvGetTickCount() - t;
        printf( "detection time = %gms\n", t/((double)cvGetTickFrequency()*1000.) );
		
	
        for( i = 0; i < (faces ? faces->total : 0); i++ ) /* draw circle*/

		{
			
            CvRect* r = (CvRect*)cvGetSeqElem( faces, i );
            CvPoint center;/*CvPoint is a structure which has just two members they store x coordinate and the y coordinate*/
            int radius;
            center.x = cvRound((r->x + r->width*0.5)*scale);
            center.y = cvRound((r->y + r->height*0.5)*scale);
            radius = cvRound((r->width + r->height)*0.25*scale);
            cvCircle( img, center, radius, colors[i%8], 3, 8, 0 );

			printf("detection_successful\n");
			 /* print msg when object is detected*/
			
		}
		 	
     printf("no_object\n"); /* print msg2 when no object is detected */
    }


    cvShowImage( "result", img );
    cvReleaseImage( &gray );
    cvReleaseImage( &small_img );

hmmm ,sorry. mayb the this part is not the main loop for detection result

Yes it is. detect_and_draw() is called from the main-loop.

sorry for troubling again, i tried input all the neccessary info, but there are compile error ,
can u check for me wad problem with it? i add it in like this

if( capture )

    {  
			std::clock_t start = std::clock();;
	                	int detected = 1;

        for(;;)/*Infinite loop until we hit the escape buttom*/

        {   
              if ( printf("no_object\n") ) /* face detection failed */
				  detected = 0;  

              if (( std::clock() - start >= 200) && detected ==1)// 200 ms 

				  printf("detected_confirm");

			  else   printf("no object_confirm");

			  start = std::clock(); //reset clock     
              detected = 1; // reset detection

but there are compile error

Tell me the compiler error, I left my crystal ball at by friends house, so I don't know what you're talking about.

[edit]
On second thought, I might be physic after all: Did you forget to #include <ctime> ?

below are the msg :

facedetect.c
C:\Program Files\OpenCV\samples\Copy of c1\facedetect.c(158) : error C2143: syntax error : missing ';' before ':'
C:\Program Files\OpenCV\samples\Copy of c1\facedetect.c(159) : error C2143: syntax error : missing ';' before 'type'
C:\Program Files\OpenCV\samples\Copy of c1\facedetect.c(191) : error C2065: 'detected' : undeclared identifier
C:\Program Files\OpenCV\samples\Copy of c1\facedetect.c(193) : error C2065: 'std' : undeclared identifier
C:\Program Files\OpenCV\samples\Copy of c1\facedetect.c(193) : error C2143: syntax error : missing ')' before ':'
C:\Program Files\OpenCV\samples\Copy of c1\facedetect.c(197) : error C2181: illegal else without matching if
C:\Program Files\OpenCV\samples\Copy of c1\facedetect.c(199) : error C2065: 'start' : undeclared identifier
C:\Program Files\OpenCV\samples\Copy of c1\facedetect.c(199) : error C2143: syntax error : missing ';' before ':'
Error executing cl.exe.

facedetect.exe - 8 error(s), 0 warning(s)

yea, i try to adjust some way , but still as follows :

if( capture )

    {         using namespace std;
			std::clock_t start = std::clock();;
	                	int detected = 1;

        for(;;)/*Infinite loop until we hit the escape buttom*/

        {   
           if ( printf("no_object\n") ) /* face detection failed */
				  detected = 0;  
               
              if (( std::clock() - start >= 200) && detected ==1)// 200 ms 

				  printf("detected_confirm");

			  else   printf("no object_confirm");

			  start = std::clock(); //reset clock     
              detected = 1; // reset detection
     
		
          }

Compiling...
facedetect.c
C:\Program Files\OpenCV\samples\Copy of c1\facedetect.c(157) : error C2065: 'using' : undeclared identifier
C:\Program Files\OpenCV\samples\Copy of c1\facedetect.c(157) : error C2146: syntax error : missing ';' before identifier 'namespace'
C:\Program Files\OpenCV\samples\Copy of c1\facedetect.c(157) : error C2065: 'namespace' : undeclared identifier
C:\Program Files\OpenCV\samples\Copy of c1\facedetect.c(157) : error C2146: syntax error : missing ';' before identifier 'std'
C:\Program Files\OpenCV\samples\Copy of c1\facedetect.c(157) : error C2065: 'std' : undeclared identifier
C:\Program Files\OpenCV\samples\Copy of c1\facedetect.c(158) : error C2143: syntax error : missing ';' before ':'
C:\Program Files\OpenCV\samples\Copy of c1\facedetect.c(159) : error C2143: syntax error : missing ';' before 'type'
C:\Program Files\OpenCV\samples\Copy of c1\facedetect.c(191) : error C2065: 'detected' : undeclared identifier
C:\Program Files\OpenCV\samples\Copy of c1\facedetect.c(193) : error C2143: syntax error : missing ')' before ':'
C:\Program Files\OpenCV\samples\Copy of c1\facedetect.c(197) : error C2181: illegal else without matching if
C:\Program Files\OpenCV\samples\Copy of c1\facedetect.c(199) : error C2065: 'start' : undeclared identifier
C:\Program Files\OpenCV\samples\Copy of c1\facedetect.c(199) : error C2143: syntax error : missing ';' before ':'
Error executing cl.exe.

facedetect.exe - 12 error(s), 0 warning(s)

ok... that's strange Anyway, delete the namespace line and add #include <iostream> to your code (on top).

Adding one of the STL header should make the std::namespace visible

haha, yes it solved! ,but , now comes up with a error

facedetect.c
C:\Program Files\Microsoft Visual Studio\VC98\INCLUDE\eh.h(32) : fatal error C1189: #error : "eh.h is only for C++!"
Error executing cl.exe.

facedetect.exe - 1 error(s), 0 warning(s)


i had checked this is a include file but even i deleted tat line it still unresolved .
any idea to solvethis ?

the file path is at [ ..\VC98\INCLUDE\EH.H]
now i checking the error msg on internet
this is the include file content:
<snip copyright code>

I've never heard of this problem, but it looks to me that if you add #define __cplusplus 199711L To your code (just below the includes) it should compile.

Did you get this error after adding the clock code, or did you get it with the original program?

nope, befor add in the iostream include and codes, this error doesnot occurs.

i tried add in the code u said, it 's still remain the same.

im working at vc++6.0, is it the issues for this error?
i get from msdn lib, it state it might sth call /robust option related but i try it now aredy still unresolved

sorry for troubling u so long, right now i gt some work need to go out, i still cant find out the solution yet, by tmr will you still around ? or if u hav any solution could you inform me? sorry for inconvenience matters, thank you !

im feel really sorry to had offenced danniweb posting rule without noticing it.

regarding the question again, i will now continue to find the solution, so, instead of using namespace, can anyone give me some clue how to implement the clocking code in .c files? thanks1

regarding the question again, i will now continue to find the solution, so, instead of using namespace, can anyone give me some clue how to implement the clocking code in .c files? thanks1

Use #include <time.h> , and use clock_t and clock() instead of std::clock_t and std::clock() .

yea, thanks for your advice. mitrmkar. i just solved this part.

This question has already been answered. Start a new discussion instead.