Exemplo n.º 1
0
// this function is called each frame
void glutDisplay(void) {
    //send stuff twice every frame
    executeInputLoop();
    executeInputLoop();

	glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	// Setup the OpenGL viewpoint
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();

	xn::SceneMetaData sceneMD;
	xn::DepthMetaData depthMD;

	g_DepthGenerator.GetMetaData(depthMD);

	glOrtho(0, depthMD.XRes(), depthMD.YRes(), 0, -1.0, 1.0);
	glDisable(GL_TEXTURE_2D);

	if (!g_bPause) {
		// Read next available data
		g_Context.WaitOneUpdateAll(g_UserGenerator);
	}

	// Process the data
	g_DepthGenerator.GetMetaData(depthMD);
	g_UserGenerator.GetUserPixels(0, sceneMD);

	//draw the suff with openGL
	DrawDepthMap(depthMD, sceneMD);
	glutSwapBuffers();
}
Exemplo n.º 2
0
void Loop(void)
{
	XnStatus nRetVal = XN_STATUS_OK;


	while (g_notDone)
	{

		if ((nRetVal = g_context.WaitOneUpdateAll(g_depth)) != XN_STATUS_OK)
			//if ((nRetVal = g_context.WaitAndUpdateAll()) != XN_STATUS_OK)
		{
			fprintf(stderr,"Could not update data: %s\n", xnGetStatusString(nRetVal));
			continue;
		}
		if (g_haveDepth)
		{
			const XnDepthPixel* pDepthMap = g_depth.GetDepthMap();
			ProcessDepthFrame(pDepthMap, g_depthWidth, g_depthHeight);
			FindFingertip();
		}

		if (g_haveImage)
		{
			const XnRGB24Pixel* pImageMap = g_image.GetRGB24ImageMap();
			ProcessImageFrame(pImageMap, g_depthWidth, g_depthHeight);
		}



		ShowFrame();

		CheckKeys();
	}
}
Exemplo n.º 3
0
// this function is called each frame
void glutDisplay (void)
{

	glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	// Setup the OpenGL viewpoint
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();

	XnMapOutputMode mode;
	g_DepthGenerator.GetMapOutputMode(mode);
#ifdef USE_GLUT
	glOrtho(0, mode.nXRes, mode.nYRes, 0, -1.0, 1.0);
#elif defined(USE_GLES)
	glOrthof(0, mode.nXRes, mode.nYRes, 0, -1.0, 1.0);
#endif

	glDisable(GL_TEXTURE_2D);

	if (!g_bPause)
	{
		// Read next available data
		g_Context.WaitOneUpdateAll(g_DepthGenerator);
		// Update NITE tree
		g_pSessionManager->Update(&g_Context);
#ifdef USE_GLUT
		PrintSessionState(g_SessionState);
#endif
	}

#ifdef USE_GLUT
	glutSwapBuffers();
#endif
}
Exemplo n.º 4
0
/**   
	* @fn waitKinect
	* Wait Kinect
    * This function defines the standby state kinect
    * While not made any motion is put on hold
*/
bool waitKinect()
{
	if (g_init_kinect == true)
	{
		// Read next available data
		g_Context.WaitOneUpdateAll(g_DepthGenerator);

		// Process the data
		g_pSessionManager->Update(&g_Context);	
	}	
	return g_session_started;
}
Exemplo n.º 5
0
/**   
   * @fn updateKinect
   * update de movements of Kinect
*/
K_SHIP_MOVE updateKinect()
{
	if (g_session_started == true)
	{
		g_init_kinect = false;
		// Read next available data
		g_Context.WaitOneUpdateAll(g_DepthGenerator);

		// Process the data
		g_pSessionManager->Update(&g_Context);
	}
	
	return g_dir;
}
Exemplo n.º 6
0
// this function is called each frame
void glutDisplay (void)
{

	glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	// Setup the OpenGL viewpoint
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();

	xn::SceneMetaData sceneMD;
	xn::DepthMetaData depthMD;
	g_DepthGenerator.GetMetaData(depthMD);
#ifdef USE_GLUT
	glOrtho(0, depthMD.XRes(), depthMD.YRes(), 0, -1.0, 1.0);
#elif defined(USE_GLES)
	glOrthof(0, depthMD.XRes(), depthMD.YRes(), 0, -1.0, 1.0);
#endif

	glDisable(GL_TEXTURE_2D);

	if (!g_bPause)
	{
		// Read next available data
		g_Context.WaitOneUpdateAll(g_DepthGenerator);
	}

	if (g_bStep)
	{
		g_bStep = false;
		g_bPause = true;
	}
	
	// Process the data
	//DRAW
	g_DepthGenerator.GetMetaData(depthMD);
	g_SceneAnalyzer.GetMetaData(sceneMD);

	DrawDepthMap(depthMD, sceneMD);
#ifdef USE_GLUT
	if (g_bPrintFrameID)
	{
		DrawFrameID(depthMD.FrameID());
	}
#endif

#ifdef USE_GLUT
	glutSwapBuffers();
#endif
}
Exemplo n.º 7
0
// this function is called each frame
void glutDisplay (void)
{

	glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	// Setup the OpenGL viewpoint
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();

	xn::SceneMetaData sceneMD;
	xn::DepthMetaData depthMD;
	g_DepthGenerator.GetMetaData(depthMD);
	#ifdef USE_GLUT
	glOrtho(0, depthMD.XRes(), depthMD.YRes(), 0, -1.0, 1.0);
	#else
	glOrthof(0, depthMD.XRes(), depthMD.YRes(), 0, -1.0, 1.0);
	#endif

	glDisable(GL_TEXTURE_2D);

	if (!g_bPause)
	{
		// Read next available data
		g_Context.WaitOneUpdateAll(g_DepthGenerator);
	}

		// Process the data
		//DRAW
		g_DepthGenerator.GetMetaData(depthMD);
		g_UserGenerator.GetUserPixels(0, sceneMD);
		DrawDepthMap(depthMD, sceneMD, g_nPlayer);

		if (g_nPlayer != 0)
		{
			XnPoint3D com;
			g_UserGenerator.GetCoM(g_nPlayer, com);
			if (com.Z == 0)
			{
				g_nPlayer = 0;
				FindPlayer();
			}
		}

	#ifdef USE_GLUT
	glutSwapBuffers();
	#endif
}
Exemplo n.º 8
0
// this function is called each frame
void glutDisplay ()
{
	clock_t t1 = clock();
	glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	// Setup the OpenGL viewpoint
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();

	xn::SceneMetaData sceneMD;
	xn::DepthMetaData depthMD;
        xn::ImageMetaData imageMD;
	g_DepthGenerator.GetMetaData(depthMD);
	g_ImageGenerator.GetMetaData(imageMD);
#ifndef USE_GLES
	glOrtho(0, depthMD.XRes(), depthMD.YRes(), 0, -1.0, 1.0);
#else
	glOrthof(0, depthMD.XRes(), depthMD.YRes(), 0, -1.0, 1.0);
#endif

	glDisable(GL_TEXTURE_2D);

	if (!g_bPause)
	{
		// Read next available data
		g_Context.WaitOneUpdateAll(g_UserGenerator);
	}

		// Process the data
	g_DepthGenerator.GetMetaData(depthMD);
	g_ImageGenerator.GetMetaData(imageMD);
	g_UserGenerator.GetUserPixels(0, sceneMD);
	if(Show_Image == FALSE)
		DrawDepthMap(depthMD, sceneMD,COM_tracker,Bounding_Box);
	else
	{
		DrawImageMap(imageMD, depthMD, sceneMD,COM_tracker,Bounding_Box);
	}
#ifndef USE_GLES
	glutSwapBuffers();
#endif
	clock_t t2 = clock();
        std::cout << t2 - t1 << std::endl;
}
Exemplo n.º 9
0
reader_result kinect_reader2::get_next() {
	XnUserID aUsers[15];
	XnUInt16 nUsers = 15;
	XnSkeletonJointPosition joint;

	while(true) {
		// Read next available data
		nRetVal = g_Context.WaitOneUpdateAll(g_DepthGenerator);
		if(nRetVal != XN_STATUS_OK) {
			printf("Failed updating data: %s\n", xnGetStatusString(nRetVal));
			continue;
		}

		if(g_UserGenerator.GetNumberOfUsers() > 0) {

			g_UserGenerator.GetUsers(aUsers, nUsers);
			for(int i=0; i< nUsers; i++)
			{
				if(g_UserGenerator.GetSkeletonCap().IsTracking(aUsers[i]))
				{
					reader_result new_tuple;

					// player
					new_tuple.push_back(boost::any((int)aUsers[i]));

					// 1 = XN_SKEL_HEAD, ..., 24 = XN_SKEL_RIGHT_FOOD
					for(short j = 1; j <= 24; j++) {
						g_UserGenerator.GetSkeletonCap().GetSkeletonJointPosition(aUsers[i], (XnSkeletonJoint)j, joint);
						new_tuple.push_back(boost::any(boost::lexical_cast<std::string>((float)joint.position.X)));
						new_tuple.push_back(boost::any(boost::lexical_cast<std::string>((float)joint.position.Y)));
						new_tuple.push_back(boost::any(boost::lexical_cast<std::string>((float)joint.position.Z)));
						new_tuple.push_back(boost::any(boost::lexical_cast<std::string>((float)joint.fConfidence)));
					}

					return new_tuple;
				}
			}
		}
	}
}
Exemplo n.º 10
0
// this function is called each frame
void glutDisplay (void)
{
    xn::SceneMetaData sceneMD;
    xn::DepthMetaData depthMD;
    xn::ImageMetaData imageMD;

    glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // Setup the OpenGL viewpoint
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();

    g_DepthGenerator.GetMetaData(depthMD);
    g_ImageGenerator.GetMetaData(imageMD);

#ifndef USE_GLES
    glOrtho(0, depthMD.XRes(), depthMD.YRes(), 0, -1.0, 1.0);
#else
    glOrthof(0, depthMD.XRes(), depthMD.YRes(), 0, -1.0, 1.0);
#endif

    glDisable(GL_TEXTURE_2D);

    // Read next available data
    g_Context.WaitOneUpdateAll(g_UserGenerator);

    // Process the data
    g_DepthGenerator.GetMetaData(depthMD);
    g_UserGenerator.GetUserPixels(0, sceneMD);
    g_ImageGenerator.GetMetaData(imageMD);

    // Draw the input fetched from the Kinect
    DrawKinectInput(depthMD, sceneMD, imageMD);

#ifndef USE_GLES
    glutSwapBuffers();
#endif
}
Exemplo n.º 11
0
// this function is called each frame
void glutDisplay (void)
{

	glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	// Setup the OpenGL viewpoint
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();

	xn::SceneMetaData sceneMD;
	xn::DepthMetaData depthMD;
	g_DepthGenerator.GetMetaData(depthMD);
#ifndef USE_GLES
	glOrtho(0, depthMD.XRes(), depthMD.YRes(), 0, -1.0, 1.0);
#else
	glOrthof(0, depthMD.XRes(), depthMD.YRes(), 0, -1.0, 1.0);
#endif

	glDisable(GL_TEXTURE_2D);

	if (!g_bPause)
	{
		// Read next available data
		g_Context.WaitOneUpdateAll(g_UserGenerator);
	}

	// Process the data
	g_DepthGenerator.GetMetaData(depthMD);
	g_UserGenerator.GetUserPixels(0, sceneMD);
  DrawDepthMap(depthMD, sceneMD);

  processUsers(depthMD.FrameID());  
#ifndef USE_GLES
	glutSwapBuffers();
#endif
}
Exemplo n.º 12
0
void draw() {
	glClear( GL_COLOR_BUFFER_BIT );

	XnMapOutputMode mode;
	g_DepthGenerator.GetMapOutputMode(mode);

	Matrix4f projectionMatrix = Matrix4f();
	projectionMatrix.Ortho(0, mode.nXRes, mode.nYRes, 0, -1.0, 1.0);

	Vector primaryPoint;
	primaryPoint = pointHandler->getPrimaryPoint();
	Vector movement = primaryPoint - position;
	movement.normalize();
	position += movement;
	position.print();

	Matrix4f modelViewMatrix;
	modelViewMatrix.translate(position.getX(), position.getY(), 0);

	Matrix4f modelViewProjectionMatrix;
	modelViewProjectionMatrix = projectionMatrix * modelViewMatrix;
	//glUniformMatrix4fv(matLoc, 1, GL_FALSE, modelViewProjectionMatrix); 
	// Use our shader
	glUseProgram(programObject);

	modelViewProjectionMatrix.uniformMatrix(matLoc);

	// Draw the triangle
	glDrawArrays(GL_LINE_LOOP, 0, 3);

	g_Context.WaitOneUpdateAll(g_DepthGenerator);
	// Update NITE tree
	g_pSessionManager->Update(&g_Context);
	PrintSessionState(g_SessionState);

	SDL_GL_SwapBuffers();
}
Exemplo n.º 13
0
    //glutCreateWindow ("User Tracker Viewer");
int main()
{
	ofstream myfile ("xxx.output"); //filename  /home/chen/kinect/OpenNI/Samples/Bin/x64-Release
    XnStatus nRetVal = XN_STATUS_OK;
    xn::EnumerationErrors errors;
    unsigned char key;
	bool tilt = 0;   //definitions of signal switches
	bool pan  = 0;
	bool zoom = 0;
	bool zoomin_1 = 0;
	bool zoomin_0 = 0;
	bool zoomout_1 = 0;
	bool PIDcount = 1;
	double directx = 0.00;
	double directy = 0.00; 
	double directz = 0.00;
	double direct_x;
                    double torsojointz;
                    double neckjointz;
                    double headjointz;
                    double der_one_headjoint = 0.00;
                    double der_two_headjoint = 0.00;
                    double der_one_headjoint_p = 0.00;
                    double headcenter = 0.00;
                    
                    
                    
                    
                    
    //-------for shared memory--------
    char c, m;
    int shmid;
    int shmidm;
    key_t keym;
    key_t keymecha; //key for mechanical robot
    char *shm, *shmm, *s, *mecha;
    keym = 1234;
    keymecha = 4321;
        /*
     * Create the segment.
     */
    if ((shmid = shmget(keym, SHMSZ, IPC_CREAT | 0666)) < 0) {
        perror("shmget");
        exit(1);
    }
    
    if ((shmidm = shmget(keymecha, SHMSZ, IPC_CREAT | 0666)) < 0) { // segment for medical robot
        perror("shmget");
        exit(1);
    }

    /*
     * Now we attach the segment to our data space.
     */
    if ((shm = (char*)shmat(shmid, NULL, 0)) == (char *) -1) {
        perror("shmat");
        exit(1);
    }

	if ((shmm = (char*)shmat(shmidm, NULL, 0)) == (char *) -1) {  // attaching segment for medical robot
        perror("shmat");
        exit(1);
    }
    /*
     * Now put some things into the memory for the
     * other process to read.
     */
    s = shm;
	*s = 't';
    mecha = shmm;
    *mecha = 'n';
    //-------for shared memory----------
    
    
    
    
    
    
    
    
    
    int head_up = 0;
	int count = 0;
	int counter = 0;
    const char *fn = NULL;
    if    (fileExists(SAMPLE_XML_PATH)) fn = SAMPLE_XML_PATH;
    else if (fileExists(SAMPLE_XML_PATH_LOCAL)) fn = SAMPLE_XML_PATH_LOCAL;
    else {
        printf("Could not find '%s' nor '%s'. Aborting.\n" , SAMPLE_XML_PATH, SAMPLE_XML_PATH_LOCAL);
        return XN_STATUS_ERROR;
    }
    printf("Reading config from: '%s'\n", fn);

    nRetVal = g_Context.InitFromXmlFile(fn, g_scriptNode, &errors);
    if (nRetVal == XN_STATUS_NO_NODE_PRESENT)
    {
        XnChar strError[1024];
        errors.ToString(strError, 1024);
        printf("%s\n", strError);
        return (nRetVal);
    }
    else if (nRetVal != XN_STATUS_OK)
    {
        printf("Open failed: %s\n", xnGetStatusString(nRetVal));
        return (nRetVal);
    }

    nRetVal = g_Context.FindExistingNode(XN_NODE_TYPE_DEPTH, g_DepthGenerator);
    CHECK_RC(nRetVal,"No depth");

    nRetVal = g_Context.FindExistingNode(XN_NODE_TYPE_USER, g_UserGenerator);
    if (nRetVal != XN_STATUS_OK)
    {
        nRetVal = g_UserGenerator.Create(g_Context);
        CHECK_RC(nRetVal, "Find user generator");
    }

    XnCallbackHandle hUserCallbacks, hCalibrationStart, hCalibrationComplete, hPoseDetected;
    if (!g_UserGenerator.IsCapabilitySupported(XN_CAPABILITY_SKELETON))
    {
        printf("Supplied user generator doesn't support skeleton\n");
        return 1;
    }
    nRetVal = g_UserGenerator.RegisterUserCallbacks(User_NewUser, User_LostUser, NULL, hUserCallbacks);
    CHECK_RC(nRetVal, "Register to user callbacks");
    nRetVal = g_UserGenerator.GetSkeletonCap().RegisterToCalibrationStart(UserCalibration_CalibrationStart, NULL, hCalibrationStart);
    CHECK_RC(nRetVal, "Register to calibration start");
    nRetVal = g_UserGenerator.GetSkeletonCap().RegisterToCalibrationComplete(UserCalibration_CalibrationComplete, NULL, hCalibrationComplete);
    CHECK_RC(nRetVal, "Register to calibration complete");

    if (g_UserGenerator.GetSkeletonCap().NeedPoseForCalibration())
    {
        g_bNeedPose = TRUE;
        if (!g_UserGenerator.IsCapabilitySupported(XN_CAPABILITY_POSE_DETECTION))
        {
            printf("Pose required, but not supported\n");
            return 1;
        }
        nRetVal = g_UserGenerator.GetPoseDetectionCap().RegisterToPoseDetected(UserPose_PoseDetected, NULL, hPoseDetected);
        CHECK_RC(nRetVal, "Register to Pose Detected");
        g_UserGenerator.GetSkeletonCap().GetCalibrationPose(g_strPose);
    }

    g_UserGenerator.GetSkeletonCap().SetSkeletonProfile(XN_SKEL_PROFILE_ALL);

    nRetVal = g_Context.StartGeneratingAll();
    CHECK_RC(nRetVal, "StartGenerating");

    //XnUserID aUsers[MAX_NUM_USERS];
    //XnUInt16 nUsers;
    //XnSkeletonJointTransformation torsoJoint;
    //XnSkeletonJointTransformation neckJoint;
    //XnSkeletonJointTransformation headJoint;
    //XnSkeletonJointOrientation headorientation;
   printf("Starting to run\n");
    if(g_bNeedPose)
    {
        printf("Assume calibration pose\n");
    }
    int k = 0;
    float xr;
    float yr;
    float zr;
    float xa;
    float ya;
    float za;
	//while (!xnOSWasKeyboardHit())    /////////////////modify here!
	while (1)  // the super loop begins here!!
    {
		
        g_Context.WaitOneUpdateAll(g_UserGenerator);
        // print the torso information for the first user already tracking
        nUsers=MAX_NUM_USERS;
        g_UserGenerator.GetUsers(aUsers, nUsers);  //generate a user
        for(XnUInt16 i=0; i<nUsers; i++)
        {
            if(g_UserGenerator.GetSkeletonCap().IsTracking(aUsers[i])==FALSE)
                continue; //if the condition is satisfied, the following commands should never be generated.
						  //"Any remaining statements in the current iteration are not executed. "
			/*
  XN_SKEL_HEAD          = 1,    XN_SKEL_NECK            = 2,
  XN_SKEL_TORSO         = 3,    XN_SKEL_WAIST           = 4,
  XN_SKEL_LEFT_COLLAR        = 5,    XN_SKEL_LEFT_SHOULDER        = 6,
  XN_SKEL_LEFT_ELBOW        = 7,  XN_SKEL_LEFT_WRIST          = 8,
  XN_SKEL_LEFT_HAND          = 9,    XN_SKEL_LEFT_FINGERTIP    =10,
  XN_SKEL_RIGHT_COLLAR    =11,    XN_SKEL_RIGHT_SHOULDER    =12,
  XN_SKEL_RIGHT_ELBOW        =13,  XN_SKEL_RIGHT_WRIST          =14,
  XN_SKEL_RIGHT_HAND      =15,    XN_SKEL_RIGHT_FINGERTIP    =16,
  XN_SKEL_LEFT_HIP          =17,    XN_SKEL_LEFT_KNEE            =18,
  XN_SKEL_LEFT_ANKLE        =19,  XN_SKEL_LEFT_FOOT            =20,
  XN_SKEL_RIGHT_HIP          =21,    XN_SKEL_RIGHT_KNEE          =22,
  XN_SKEL_RIGHT_ANKLE        =23,    XN_SKEL_RIGHT_FOOT          =24    
			 * 
			 * */
            g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_TORSO,torsoJoint);
            g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_NECK,neckJoint);
            g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_HEAD,headJoint);
            g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_LEFT_SHOULDER,leftshoulder);
            g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_RIGHT_SHOULDER,rightshoulder);
            g_UserGenerator.GetSkeletonCap().GetSkeletonJointOrientation(aUsers[i], XN_SKEL_HEAD, headorientation);
            //---------------------------------------------------
            
            /*
            while(k < 50)
            {
            xr += torsoJoint.position.position.X;
            yr += torsoJoint.position.position.Y;
            zr += torsoJoint.position.position.Z;
            
            xa = xr/50.0;
            ya = yr/50.0;
            za = zr/50.0;
            k++;
		    }*/
		    //---------------------------------------------------- datas from different parts of a human body
			   //~ printf("user %d: torso at (%6.2f,%6.2f,%6.2f)\n",aUsers[i],
																//~ torsoJoint.position.position.X,
																//~ torsoJoint.position.position.Y,
																//~ torsoJoint.position.position.Z);
						//~ 
				//~ printf("user %d: neck at (%6.2f,%6.2f,%6.2f)\n",aUsers[i],
																//~ neckJoint.position.position.X,
																//~ neckJoint.position.position.Y,
																//~ neckJoint.position.position.Z);
				//~ printf("user %d: head at (%6.2f,%6.2f,%6.2f)\n",aUsers[i],
																//~ headJoint.position.position.X,
																//~ headJoint.position.position.Y,
																//~ headJoint.position.position.Z);
                //~ printf("user %d: head direction x at (%6.2f,%6.2f,%6.2f)\n",aUsers[i],
                                                                //~ headorientation.orientation.elements[0],
                                                                //~ headorientation.orientation.elements[3],
                                                                //~ headorientation.orientation.elements[6]);
                //~ printf("user %d: head direction y at (%6.2f,%6.2f,%6.2f)\n",aUsers[i],
                                                                //~ headorientation.orientation.elements[1],
                                                                //~ headorientation.orientation.elements[4],
                                                                //~ headorientation.orientation.elements[7]);
                //~ printf("user %d: head direction z at (%6.2f,%6.2f,%6.2f)\n",aUsers[i],
                                                                //~ headorientation.orientation.elements[2],
                                                                //~ headorientation.orientation.elements[5],
                                                                //~ headorientation.orientation.elements[8]);
                //-----------------------------------------print process ID
                                                                
                if(PIDcount = 1)
                {
					ofstream pidfile ("/home/chen/numbers.txt"); 
					if(pidfile.is_open())
					{
						pidfile << (int) getpid ();
						pidfile.close();
						}
						PIDcount = 0;
						//return 0;
					}
                //-----------------------------------------print process ID
                
                //~ printf ("/proc/self reports process id %d\n", (int) get_pid_from_proc_self ());
					//~ 
				//~ printf ("getpid() reports process id %d\n", (int) getpid ());
				//-----------------------------------------print process ID
                    //~ double direct_x;
                    //~ double torsojointz;
                    //~ double neckjointz;
                    //~ double headjointz;
                    
                    
                    
                    torsojointz = torsoJoint.position.position.Z;
                    neckjointz = neckJoint.position.position.Z;
                    //~ headjointz = headJoint.position.position.Z;
                    if(count < 10)   //calculate first derivative of head position
                    {
						count++;
						
						}
					else
					
					{
						der_one_headjoint = headJoint.position.position.Z - headjointz;// calculate the first derivative each 10Hz
						der_two_headjoint = der_one_headjoint - der_one_headjoint_p;
						headjointz = headJoint.position.position.Z;//update headposition container
						der_one_headjoint_p = der_one_headjoint;//update head velocity container
						count = 0;
						
						} 
                   ///////////////(1)/bond setting 
                   
                   
                   //----------------set up headcenter in z axis
                  
                   if(counter < 201)   //set up headcenter in z axis
                    {
						counter++;
						if (counter == 200)
						{
						headcenter = headJoint.position.position.Z;
						}
					}
						else
					{
							//--------------trick
							counter = 300;
							if (*s == 'a')
							{
								counter =0;
								system("espeak 'activated'");
								system("espeak 'resetting reference'");
								*s = 't';
								}
							//--------------trick
					}
					
					//----------------set up headcenter in z axis
					
					
					
					if(counter ==300) // counter == 300 means reference resetted
					{		
					if (headJoint.position.position.Z - headcenter > 50)
					{
						head_up = 100;
						printf("zooming out\n");
						*mecha = 'o';
						//zoomout_1 = 1;
						zoomin_1 = 0;
					}
					
					if (((headJoint.position.position.Z - headcenter) < 50) && ((headJoint.position.position.Z - headcenter) > -50))
					{
						//head_up = 100;
						//printf("zooming out\n");
						*mecha = 'n';
						//zoomout_1 = 1;
						//zoomin_1 = 0;
					}
					
					if (headJoint.position.position.Z - headcenter < -50)
					{
						head_up = -100;
						printf("zooming in\n");
						*mecha = 'i';
						zoomin_1 = 1;
						//zoomout_1 = 0;
					}
					}
                    //double directx;
					//param = 0.5;
					
					////////////(filters)//
					direct_x = acos (headorientation.orientation.elements[6]) * 180.0 / PI;
					if (direct_x - directx > 10)  // filters: filter the noises of the data.
					
					{
						
						direct_x = directx + 10;
						directx = direct_x;
						}
					////////////(filters)//
					
					
					
					//~ printf ("The arc cosine of panning angle is %f degrees.\n",  direct_x);
					//
					printf ("reference center in z axis is %f.\n",  headcenter);
					printf ("The head's position in z axis is %f.\n",  headJoint.position.position.Z);
					
					
					    //ofstream myfile ("example.txt"); /home/chen/kinect/OpenNI/Samples/Bin/x64-Release

						//return 0;
					
					
					
					//return 0;
					double direct_y;
					//double directy;
					//param = 0.5;
					direct_y = acos (headorientation.orientation.elements[1]) * 180.0 / PI;
					if (direct_y - directy > 10)
					
					{
						
						direct_y = directy + 10;
						directy = direct_y;
						}
					//~ printf ("The arc cosine of zooming angle is %f degrees.\n",  direct_y);
					//~ //return 0;
					double direct_z;
					
					//double directz;
					//param = 0.5;
					direct_z = acos (headorientation.orientation.elements[7]) * 180.0 / PI;
					if (direct_z - directz > 10)
					
					{
						
						direct_z = directz + 10;
						directz = direct_z;
						}
					//~ printf ("The arc cosine of tilting angle is %f degrees.\n",  direct_z);
					//~ //return 0;
					  if (myfile.is_open())
  {
	//  return 0;
    //myfile << "This is element 6.\n";
    //myfile << "This is another line.\n";
    myfile <<headcenter<< "  "<<rightshoulder.position.position.Z<< "  "<< headJoint.position.position.Z<< "  "<<head_up<< "  "<<der_two_headjoint<< "  "<<der_one_headjoint<< "  "<< direct_x << "  " << direct_y << "  " <<direct_z << "  " << torsojointz << "  " << neckjointz << "  "<< headjointz <<"  .\n";
    
    //~ myfile <<  1400  << "  " << headJoint.position.position.Z  <<  "  .\n";
    
    //~ myfile <<headcenter<< "  "<<head_up<< "  .\n";
    //myfile << "This is a line.\n";
    //myfile << "This is a line.\n";
    //myfile << "This is a line.\n";
    //myfile << "This is a line.\n";
    //myfile.close();
  }
					//glutKeyboard();
					if (xnOSWasKeyboardHit())
					{
					char key = xnOSReadCharFromInput();
					//if(27==c)break;
					switch (key)
			
			{
				case 116:
				// -----------press t
				tilt = !tilt;
				break;
				case 112:
				// -----------press p
				pan = !pan;
				break;
				case 122:
				// -----------press z
				zoom = !zoom;
				break;
             }
					
			}		
		    while(pan)
		    {                                              
            if(headorientation.orientation.elements[6] > 0.5)
			{
				
				printf("yawing  ----->\n");
				
			}
			else if(headorientation.orientation.elements[6] < -0.5)
			{
				printf("yawing  <-----\n");
			}
			else
			{
			}
			break;
				}
			while(tilt)
			{
			if(headorientation.orientation.elements[1] > 0.5)
			{
				printf("rolling  right\n");
			}
			else if(headorientation.orientation.elements[1] < -0.5)
			{
				printf("rolling  left\n");
			}
			else
			{
				}
				break;
			}
			while(zoom)
			{
			if(direct_z < 60.0)
			{
				
				zoomin_0 = 0;
				zoomout_1 = 1;
				printf("zooming  out\n");
			}
			else if(direct_z > 120.0)
			{
				printf("zooming  in\n");
				zoomin_0 = 1;
			}
			else
			{
				zoomout_1 = 0;
				}
			//~ if (zoomin_1 && zoomin_0 && !zoomout_1)
			//~ {
				//~ printf("zooming  in\n");
				//~ }
			//~ if(!zoomin_1 && !zoomin_0 && zoomout_1)
			//~ {
				//~ printf("zooming  out\n");
				//~ }
				break;
			}	
			
            /*
            if(torsoJoint.position.position.X < (0.0 - 50.0))
			{
				printf("xxxxxxxxxxxx  down\n");
			}
			else if(torsoJoint.position.position.X > (0.0 + 50.0))
		   //else if((xa - 50.0) <= torsoJoint.position.position.X <= (xa + 50.0))
			{
				printf("xxxxxxxxxxxx  up\n");
			}
			//if(torsoJoint.position.position.X > (xa + 50.0))
			else
			{
				//printf("xxxxxxxxxxxx  up\n");
			}
			 if(torsoJoint.position.position.Y < (0.0 - 50.0))
			{
				printf("yyyyyyyyyyyy  down\n");
			}
		    else if(torsoJoint.position.position.Y > (0.0 + 50.0))
			{
				printf("yyyyyyyyyyyy  up\n");
			}
			//if(torsoJoint.position.position.Y > (ya + 50.0))
			else
			{
				//printf("yyyyyyyyyyyy  up\n");
			}
			 if(torsoJoint.position.position.Z < (1000.0 - 50.0))
			{
				printf("zzzzzzzzzzzz  down\n");
			}
			else if(torsoJoint.position.position.Z > (1000.0 + 50.0))
			{
				printf("zzzzzzzzzzzz  up\n");
			}
		  else //if((za - 50.0) <= torsoJoint.position.position.Z <= (za + 50.0))
			{
				//printf("zzzzzzzzzzzz  hold\n");
			}
			//if(torsoJoint.position.position.Z > (za + 50.0))
			*/
			
			
	
	//---------------------------------------------------------------------------------------------------------//		
										//find the function and get use -> SceneDrawer.cpp-> draw joint->line :189
										//SceneDrawer.cpp-> if (g_bMarkJoints) ->line:452      
										//SceneDrawer.cpp-> GetSkeletonJointPosition->line:203 
										//SceneDrawer.cpp->extern xn::UserGenerator g_UserGenerator;->g_UserGenerator 
										//XnCppWraper.h->class Generator->line:3325 
										//SceneDrawer.cpp-> joint position line:211
										//SceneDrawer.cpp-> draw circle line:215
										//xntypes.h ->joint structure->line:590 
	//---------------------------------------------------------------------------------------------------------//			
			
        }
        
    }
    g_scriptNode.Release();
    g_DepthGenerator.Release();
    g_UserGenerator.Release();
    g_Context.Release();

}
Exemplo n.º 14
0
int main(int argc, char **argv)
{
    XnStatus nRetVal = XN_STATUS_OK;
    xn::EnumerationErrors errors;
    TotalFrames = 0;
    static struct rusage ru;
    long double t;
    double w;
    struct timeval timStart;
    struct timeval timEnd;
    struct timeval Wall;
    bool Sample = true;
    XnFPSData xnFPS;
    XnUserID aUsers[MAX_NUM_USERS];
	XnUInt16 nUsers;
	XnSkeletonJointTransformation torsoJoint;

    if (argc > 1)
	{

    	//parse the cmd line
    	if (strcasecmp(argv[1],"--help") == 0)
    	{
    		PrintHelpHeader(argv[0]);
    		return 1;
    	}
    	numOfUser = atoi(argv[1]);
    	if(numOfUser == 0)
    	{
    		PrintHelpHeader(argv[0]);
    		return 1;
    	}
    	else if(numOfUser > 2)
    	{
    		printf("Maximal Users allowed is 2\n");
    		return 1;
    	}

	}
    else
    {
    	numOfUser = 4;
    }

    const char *fn = NULL;
    if    (fileExists(SAMPLE_XML_PATH)) fn = SAMPLE_XML_PATH;
    else if (fileExists(SAMPLE_XML_PATH_LOCAL)) fn = SAMPLE_XML_PATH_LOCAL;
    else {
        printf("Could not find '%s' nor '%s'. Aborting.\n" , SAMPLE_XML_PATH, SAMPLE_XML_PATH_LOCAL);
        return XN_STATUS_ERROR;
    }
    printf("Reading config from: '%s'\n", fn);

    nRetVal = g_Context.InitFromXmlFile(fn, g_scriptNode, &errors);
    if (nRetVal == XN_STATUS_NO_NODE_PRESENT)
    {
        XnChar strError[1024];
        errors.ToString(strError, 1024);
        printf("%s\n", strError);
        return (nRetVal);
    }
    else if (nRetVal != XN_STATUS_OK)
    {
        printf("Open failed: %s\n", xnGetStatusString(nRetVal));
        return (nRetVal);
    }

    nRetVal = g_Context.FindExistingNode(XN_NODE_TYPE_DEPTH, g_DepthGenerator);
    CHECK_RC(nRetVal,"No depth");

#if (XN_PLATFORM != XN_PLATFORM_MACOSX)	
    //we want out benchmark application will be running only on one CPU core
    cpu_set_t mask;
	CPU_ZERO(&mask);
	CPU_SET(1,&mask);
	sched_setaffinity(0,sizeof(mask),&mask);
#endif	
	//initialize the FPS calculator
	nRetVal = xnFPSInit(&xnFPS, 90);
	CHECK_RC(nRetVal, "FPS Init");
	//ensure the User generator exists
    nRetVal = g_Context.FindExistingNode(XN_NODE_TYPE_USER, g_UserGenerator);
    if (nRetVal != XN_STATUS_OK)
    {
        nRetVal = g_UserGenerator.Create(g_Context);
        CHECK_RC(nRetVal, "Find user generator");
    }
    //register to generators callbacks
    XnCallbackHandle hUserCallbacks, hCalibrationStart, hCalibrationComplete, hPoseDetected;
    if (!g_UserGenerator.IsCapabilitySupported(XN_CAPABILITY_SKELETON))
    {
        printf("Supplied user generator doesn't support skeleton\n");
        return 1;
    }
    nRetVal = g_UserGenerator.RegisterUserCallbacks(User_NewUser, User_LostUser, NULL, hUserCallbacks);
    CHECK_RC(nRetVal, "Register to user callbacks");
    nRetVal = g_UserGenerator.GetSkeletonCap().RegisterToCalibrationStart(UserCalibration_CalibrationStart, NULL, hCalibrationStart);
    CHECK_RC(nRetVal, "Register to calibration start");
    nRetVal = g_UserGenerator.GetSkeletonCap().RegisterToCalibrationComplete(UserCalibration_CalibrationComplete, NULL, hCalibrationComplete);
    CHECK_RC(nRetVal, "Register to calibration complete");
    //ensure calibration
    if (g_UserGenerator.GetSkeletonCap().NeedPoseForCalibration())
    {
        g_bNeedPose = TRUE;
        if (!g_UserGenerator.IsCapabilitySupported(XN_CAPABILITY_POSE_DETECTION))
        {
            printf("Pose required, but not supported\n");
            return 1;
        }
        nRetVal = g_UserGenerator.GetPoseDetectionCap().RegisterToPoseDetected(UserPose_PoseDetected, NULL, hPoseDetected);
        CHECK_RC(nRetVal, "Register to Pose Detected");
        g_UserGenerator.GetSkeletonCap().GetCalibrationPose(g_strPose);
    }
    //set skeleton profile (all joints)
    g_UserGenerator.GetSkeletonCap().SetSkeletonProfile(XN_SKEL_PROFILE_ALL);
    //start to generate
    nRetVal = g_Context.StartGeneratingAll();
    CHECK_RC(nRetVal, "StartGenerating");



    printf("%c[%d;%d;%dmPrimeSense Skeleton Benchmark Application\n ", 0x1B, BRIGHT,BLUE,BG_BLACK);
    printf("%c[%d;%d;%dmSet Maximal users to %d ", 0x1B, BRIGHT,BLUE,BG_BLACK,numOfUser);
	printf("%c[%dm\n", 0x1B, 0);
    printf("Starting to run\n");
    if(g_bNeedPose)
    {
        printf("Assume calibration pose\n");
    }

    XnUInt32 epochTime = 0;
    //each 30 frames (1 second) we start the CPU resources usages
    while (!xnOSWasKeyboardHit())
    {
    	if (Sample)
    	{	//get the beginning sample of CPU resources
    		getrusage(RUSAGE_SELF, &ru);
    		timStart=ru.ru_utime;
    		t=(double)timStart.tv_sec * 1000000.0 + (double)timStart.tv_usec \
    		   + (double)ru.ru_stime.tv_sec*1000000.0+(double)ru.ru_stime.tv_usec;
    		//get the wall clock time
    		gettimeofday(&Wall,NULL);

    		w=(double)Wall.tv_sec * 1000000.0 + (double)Wall.tv_usec;
    		Sample = false;
    	}
    	g_Context.WaitOneUpdateAll(g_UserGenerator);
    	xnFPSMarkFrame(&xnFPS);
        // print the torso information for the first user already tracking every 1 second to prevent CPU of printf
        if(TotalFrames % 30 == 0)
        {
			nUsers=MAX_NUM_USERS;
			g_UserGenerator.GetUsers(aUsers, nUsers);
			int numTracked=0;
			int userToPrint=-1;
			for(XnUInt16 i=0; i<nUsers; i++)
			{
				if(g_UserGenerator.GetSkeletonCap().IsTracking(aUsers[i])==FALSE)
					continue;

				g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_TORSO,torsoJoint);
				printf("User %d Located At distance of %6.2f mm from the sensor\n",aUsers[i],torsoJoint.position.position.Z);

			 }
			//get the finish sample of the CPU resources
			getrusage(RUSAGE_SELF, &ru);
			timEnd=ru.ru_utime;
			t = (double)timEnd.tv_sec * 1000000.0 + (double)timEnd.tv_usec \
				+	(double)ru.ru_stime.tv_sec*1000000.0+(double)ru.ru_stime.tv_usec	- t;
			//get the wall clock
			gettimeofday(&Wall,NULL);

			w = (double)Wall.tv_sec * 1000000.0 + (double)Wall.tv_usec - w;

			XnDouble fps=xnFPSCalc(&xnFPS);
			//print stuff.
			printf("%c[%d;%d;%dmCPU Utilization=%3.2f%%\t", 0x1B, BRIGHT,RED,BG_BLACK,(double)100*t/w);
			printf("%c[%d;%d;%dmFPS=%3.2f ", 0x1B, BRIGHT,RED,BG_BLACK,(double)fps);
			printf("%c[%dm\n", 0x1B, 0);
			Sample= true;

		}
        TotalFrames++;
        
    }
    g_scriptNode.Release();
    g_DepthGenerator.Release();
    g_UserGenerator.Release();
    g_Context.Release();

}
Exemplo n.º 15
0
int main(int argc, char **argv)
{
    XnStatus nRetVal = XN_STATUS_OK;
    xn::EnumerationErrors errors;
    
    if( USE_RECORED_DATA ){
        g_Context.Init();
        g_Context.OpenFileRecording(RECORD_FILE_PATH);
        xn::Player player;
        
        // Player nodeの取得
        nRetVal = g_Context.FindExistingNode(XN_NODE_TYPE_PLAYER, player);
        CHECK_RC(nRetVal, "Find player");
        
        LOG_D("PlaybackSpeed: %d", player.GetPlaybackSpeed());
        
        xn:NodeInfoList nodeList;
        player.EnumerateNodes(nodeList);
        for( xn::NodeInfoList::Iterator it = nodeList.Begin();
            it != nodeList.End(); ++it){
            
            if( (*it).GetDescription().Type == XN_NODE_TYPE_IMAGE ){
                nRetVal = g_Context.FindExistingNode(XN_NODE_TYPE_IMAGE, g_ImageGenerator);
                CHECK_RC(nRetVal, "Find image node");
                LOG_D("%s", "ImageGenerator created.");
            }
            else if( (*it).GetDescription().Type == XN_NODE_TYPE_DEPTH ){
                nRetVal = g_Context.FindExistingNode(XN_NODE_TYPE_DEPTH, g_DepthGenerator);
                CHECK_RC(nRetVal, "Find depth node");
                LOG_D("%s", "DepthGenerator created.");            
            }
            else{
                LOG_D("%s %s %s", ::xnProductionNodeTypeToString((*it).GetDescription().Type ),
                      (*it).GetInstanceName(),
                      (*it).GetDescription().strName);
            }
        }
    }
    else{
        LOG_I("Reading config from: '%s'", CONFIG_XML_PATH);
        
        nRetVal = g_Context.InitFromXmlFile(CONFIG_XML_PATH, g_scriptNode, &errors);
        if (nRetVal == XN_STATUS_NO_NODE_PRESENT){
            XnChar strError[1024];
            errors.ToString(strError, 1024);
            LOG_E("%s\n", strError);
            return (nRetVal);
        }
        else if (nRetVal != XN_STATUS_OK){
            LOG_E("Open failed: %s", xnGetStatusString(nRetVal));
            return (nRetVal);
        }
        
        nRetVal = g_Context.FindExistingNode(XN_NODE_TYPE_DEPTH, g_DepthGenerator);
        CHECK_RC(nRetVal,"No depth");
        
        // ImageGeneratorの作成
        nRetVal = g_Context.FindExistingNode(XN_NODE_TYPE_IMAGE, g_ImageGenerator);
        CHECK_RC(nRetVal, "Find image generator");
        
    }
    // UserGeneratorの取得
    nRetVal = g_Context.FindExistingNode(XN_NODE_TYPE_USER, g_UserGenerator);
    if(nRetVal!=XN_STATUS_OK){
        nRetVal = g_UserGenerator.Create(g_Context); 
        CHECK_RC(nRetVal, "Create user generator");
    }

    
    XnCallbackHandle hUserCallbacks, hCalibrationStart, hCalibrationComplete, hPoseDetected;
    if (!g_UserGenerator.IsCapabilitySupported(XN_CAPABILITY_SKELETON)){
        LOG_E("%s", "Supplied user generator doesn't support skeleton");
        return 1;
    }
    nRetVal = g_UserGenerator.RegisterUserCallbacks(User_NewUser, User_LostUser, NULL, hUserCallbacks);
    CHECK_RC(nRetVal, "Register to user callbacks");

    g_SkeletonCap = g_UserGenerator.GetSkeletonCap();
    nRetVal = g_SkeletonCap.RegisterToCalibrationStart(UserCalibration_CalibrationStart, NULL, hCalibrationStart);
    CHECK_RC(nRetVal, "Register to calibration start");

    nRetVal = g_SkeletonCap.RegisterToCalibrationComplete(UserCalibration_CalibrationComplete, NULL, hCalibrationComplete);
    CHECK_RC(nRetVal, "Register to calibration complete");
    
    if (g_SkeletonCap.NeedPoseForCalibration()){
        g_bNeedPose = TRUE;
        if (!g_UserGenerator.IsCapabilitySupported(XN_CAPABILITY_POSE_DETECTION)){
            LOG_E("%s", "Pose required, but not supported");
            return 1;
        }
        nRetVal = g_UserGenerator.GetPoseDetectionCap().RegisterToPoseDetected(UserPose_PoseDetected, NULL, hPoseDetected);
        CHECK_RC(nRetVal, "Register to Pose Detected");
        g_SkeletonCap.GetCalibrationPose(g_strPose);
    }
    
    g_SkeletonCap.SetSkeletonProfile(XN_SKEL_PROFILE_ALL);
    
    nRetVal = g_Context.StartGeneratingAll();
    CHECK_RC(nRetVal, "StartGenerating");
    
    // 表示用の画像データの作成
    XnMapOutputMode mapMode;
    g_ImageGenerator.GetMapOutputMode(mapMode);
    g_rgbImage = cvCreateImage(cvSize(mapMode.nXRes, mapMode.nYRes), IPL_DEPTH_8U, 3);

    LOG_I("%s", "Starting to run");
    if(g_bNeedPose){
        LOG_I("%s", "Assume calibration pose");
    }

    xn::Recorder recorder;
    if( DO_RECORED && !USE_RECORED_DATA ){
        // レコーダーの作成
        LOG_I("%s", "Setup Recorder");
        nRetVal = recorder.Create(g_Context);
        CHECK_RC(nRetVal, "Create recorder");
        
        // 保存設定
        nRetVal = recorder.SetDestination(XN_RECORD_MEDIUM_FILE, RECORD_FILE_PATH);
        CHECK_RC(nRetVal, "Set recorder destination file");
        
        // 深度、ビデオカメラ入力を保存対象として記録開始
        nRetVal = recorder.AddNodeToRecording(g_DepthGenerator, XN_CODEC_NULL);
        CHECK_RC(nRetVal, "Add depth node to recording");
        nRetVal = recorder.AddNodeToRecording(g_ImageGenerator, XN_CODEC_NULL);
        CHECK_RC(nRetVal, "Add image node to recording");
        
        LOG_I("%s", "Recorder setup done.");
    }

    while (!xnOSWasKeyboardHit())
    {
        g_Context.WaitOneUpdateAll(g_UserGenerator);
        if( DO_RECORED  && !USE_RECORED_DATA ){
            nRetVal = recorder.Record();
            CHECK_RC(nRetVal, "Record");
        }

        // ビデオカメラ画像の生データを取得
        xn::ImageMetaData imageMetaData;
        g_ImageGenerator.GetMetaData(imageMetaData);
        // メモリコピー
        xnOSMemCopy(g_rgbImage->imageData, imageMetaData.RGB24Data(), g_rgbImage->imageSize);
        // BGRからRGBに変換して表示
        cvCvtColor(g_rgbImage, g_rgbImage, CV_RGB2BGR);

        // UserGeneratorからユーザー識別ピクセルを取得
        xn::SceneMetaData sceneMetaData;
        g_UserGenerator.GetUserPixels(0, sceneMetaData);
        
        XnUserID allUsers[MAX_NUM_USERS];
        XnUInt16 nUsers = MAX_NUM_USERS;
        g_UserGenerator.GetUsers(allUsers, nUsers);
        for (int i = 0; i < nUsers; i++) {
            
            // キャリブレーションに成功しているかどうか
            if (g_SkeletonCap.IsTracking(allUsers[i])) {
                // スケルトンを描画
                DrawSkelton(allUsers[i], i);
            }
        }
        
        // 表示
        cvShowImage("User View", g_rgbImage);

        // ESCもしくはqが押されたら終了させる
        if (cvWaitKey(10) == 27) {
            break;
        }
    }

    if( !USE_RECORED_DATA ){
        g_scriptNode.Release();
    }
    g_DepthGenerator.Release();
    g_UserGenerator.Release();
    g_Context.Release();

	if (g_rgbImage != NULL) {
		cvReleaseImage(&g_rgbImage);	
	}
	g_Context.Shutdown();

    
}
int main()
{
    int left_flag=0, right_flag=1;
    int gait_time_L[5], gait_time_L_temp[5];
    int gait_time_R[5], gait_time_R_temp[5];
    int z=0;
    int gait_cycle_L[5];
    int gait_cycle_R[5];
    struct timeval stop, start;

    srand(time(NULL));
    int param[14][3][1000];


    using namespace LibSerial ;
    XnStatus nRetVal = XN_STATUS_OK;
    xn::EnumerationErrors errors;

    const char *fn = NULL;
    if    (fileExists(SAMPLE_XML_PATH)) fn = SAMPLE_XML_PATH;
    else if (fileExists(SAMPLE_XML_PATH_LOCAL)) fn = SAMPLE_XML_PATH_LOCAL;
    else {
        printf("Could not find '%s' nor '%s'. Aborting.\n" , SAMPLE_XML_PATH, SAMPLE_XML_PATH_LOCAL);
        return XN_STATUS_ERROR;
    }
    printf("Reading config from: '%s'\n", fn);

    nRetVal = g_Context.InitFromXmlFile(fn, g_scriptNode, &errors);
    if (nRetVal == XN_STATUS_NO_NODE_PRESENT)
    {
        XnChar strError[1024];
        errors.ToString(strError, 1024);
        printf("%s\n", strError);
        return (nRetVal);
    }
    else if (nRetVal != XN_STATUS_OK)
    {
        printf("Open failed: %s\n", xnGetStatusString(nRetVal));
        return (nRetVal);
    }

    nRetVal = g_Context.FindExistingNode(XN_NODE_TYPE_USER, g_UserGenerator);
    if (nRetVal != XN_STATUS_OK)
    {
        nRetVal = g_UserGenerator.Create(g_Context);
        CHECK_RC(nRetVal, "Find user generator");
    }

    XnCallbackHandle hUserCallbacks, hCalibrationStart, hCalibrationComplete, hPoseDetected;
    if (!g_UserGenerator.IsCapabilitySupported(XN_CAPABILITY_SKELETON))
    {
        printf("Supplied user generator doesn't support skeleton\n");
        return 1;
    }
    nRetVal = g_UserGenerator.RegisterUserCallbacks(User_NewUser, User_LostUser, NULL, hUserCallbacks);
    CHECK_RC(nRetVal, "Register to user callbacks");
    nRetVal = g_UserGenerator.GetSkeletonCap().RegisterToCalibrationStart(UserCalibration_CalibrationStart, NULL, hCalibrationStart);
    CHECK_RC(nRetVal, "Register to calibration start");
    nRetVal = g_UserGenerator.GetSkeletonCap().RegisterToCalibrationComplete(UserCalibration_CalibrationComplete, NULL, hCalibrationComplete);
    CHECK_RC(nRetVal, "Register to calibration complete");

    if (g_UserGenerator.GetSkeletonCap().NeedPoseForCalibration())
    {
        g_bNeedPose = TRUE;
        if (!g_UserGenerator.IsCapabilitySupported(XN_CAPABILITY_POSE_DETECTION))
        {
            printf("Pose required, but not supported\n");
            return 1;
        }
        nRetVal = g_UserGenerator.GetPoseDetectionCap().RegisterToPoseDetected(UserPose_PoseDetected, NULL, hPoseDetected);
        CHECK_RC(nRetVal, "Register to Pose Detected");
        g_UserGenerator.GetSkeletonCap().GetCalibrationPose(g_strPose);
    }

    g_UserGenerator.GetSkeletonCap().SetSkeletonProfile(XN_SKEL_PROFILE_ALL);

    nRetVal = g_Context.StartGeneratingAll();
    CHECK_RC(nRetVal, "StartGenerating");

    XnUserID aUsers[MAX_NUM_USERS];
    XnUInt16 nUsers;
    XnSkeletonJointTransformation torsoJoint;

    printf("Starting to run\n");
    if(g_bNeedPose)
    {
        printf("Assume calibration pose\n");
    }


//******************** SERIAL Read

        SerialStream serial_port ;
    serial_port.Open( "/dev/ttyACM0" ) ;
    if ( ! serial_port.good() )
    {
        std::cerr << "[" << __FILE__ << ":" << __LINE__ << "] "
                  << "Error: Could not open serial port."
                  << std::endl ;
        exit(1) ;
    }
    //
    // Set the baud rate of the serial port.
    //
    serial_port.SetBaudRate( SerialStreamBuf::BAUD_9600 ) ;
    if ( ! serial_port.good() )
    {
        std::cerr << "Error: Could not set the baud rate." << std::endl ;
        exit(1) ;
    }
    //
    // Set the number of data bits.
    //
    serial_port.SetCharSize( SerialStreamBuf::CHAR_SIZE_8 ) ;
    if ( ! serial_port.good() )
    {
        std::cerr << "Error: Could not set the character size." << std::endl ;
        exit(1) ;
    }
    //
    // Disable parity.
    //
    serial_port.SetParity( SerialStreamBuf::PARITY_NONE ) ;
    if ( ! serial_port.good() )
    {
        std::cerr << "Error: Could not disable the parity." << std::endl ;
        exit(1) ;
    }
    //
    // Set the number of stop bits.
    //
    serial_port.SetNumOfStopBits( 1 ) ;
    if ( ! serial_port.good() )
    {
        std::cerr << "Error: Could not set the number of stop bits."
                  << std::endl ;
        exit(1) ;
    }
    //
    // Turn on hardware flow control.
    //
    serial_port.SetFlowControl( SerialStreamBuf::FLOW_CONTROL_NONE ) ;
    if ( ! serial_port.good() )
    {
        std::cerr << "Error: Could not use hardware flow control."
                  << std::endl ;
        exit(1) ;
    }


    //********************* END OF SERIAL READ

    printf("Waiting\n");
    sleep(3);   //waiting for arduino to ready itself
    printf("Started\n");


    int n=0, m=0, k=0;
    int p=0;


	while (1)
    {



        g_Context.WaitOneUpdateAll(g_UserGenerator);
        // print the torso information for the first user already tracking

        nUsers=MAX_NUM_USERS;

        g_UserGenerator.GetUsers(aUsers, nUsers);


        for(XnUInt16 i=0; i<nUsers; i++)
        {


            n=0;

            if(g_UserGenerator.GetSkeletonCap().IsTracking(aUsers[i])==FALSE)
                continue;


                while(p==0)
        {

         printf(" Tracking done. Enter 'S' if the person is ready to walk\n");

         char rcd_byte=0;
         scanf("%c" ,&rcd_byte);

        if(rcd_byte!='s' && rcd_byte!='S')
        {
            continue;
        }
        p=1;
        }

            g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_NECK,torsoJoint);
                printf("\n user %d: Neck at (%6.2f,%6.2f,%6.2f)\n",aUsers[i],
                                                                torsoJoint.position.position.X,
                                                                torsoJoint.position.position.Y,
                                                                torsoJoint.position.position.Z);
            param[n][m][k]= torsoJoint.position.position.X;
            param[n][m+1][k]= torsoJoint.position.position.Y;
            param[n][m+2][k]= torsoJoint.position.position.Z;
            n++;

             g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_LEFT_SHOULDER,torsoJoint);
                printf("\n user %d: Left Shoulder at (%6.2f,%6.2f,%6.2f)\n",aUsers[i],
                                                                torsoJoint.position.position.X,
                                                                torsoJoint.position.position.Y,
                                                                torsoJoint.position.position.Z);

            param[n][m][k]= torsoJoint.position.position.X;
            param[n][m+1][k]= torsoJoint.position.position.Y;
            param[n][m+2][k]= torsoJoint.position.position.Z;
            n++;

           g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_LEFT_ELBOW,torsoJoint);
                printf("\n user %d: Left Elbow at (%6.2f,%6.2f,%6.2f)\n",aUsers[i],
                                                                torsoJoint.position.position.X,
                                                                torsoJoint.position.position.Y,
                                                                torsoJoint.position.position.Z);

            param[n][m][k]= torsoJoint.position.position.X;
            param[n][m+1][k]= torsoJoint.position.position.Y;
            param[n][m+2][k]= torsoJoint.position.position.Z;
            n++;

            g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_RIGHT_SHOULDER,torsoJoint);
                printf("\n user %d: Right Shoulder at (%6.2f,%6.2f,%6.2f)\n",aUsers[i],
                                                                torsoJoint.position.position.X,
                                                                torsoJoint.position.position.Y,
                                                                torsoJoint.position.position.Z);

            param[n][m][k]= torsoJoint.position.position.X;
            param[n][m+1][k]= torsoJoint.position.position.Y;
            param[n][m+2][k]= torsoJoint.position.position.Z;
            n++;

            g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_RIGHT_ELBOW,torsoJoint);
                printf("\n user %d: Right Elbow at (%6.2f,%6.2f,%6.2f)\n",aUsers[i],
                                                                torsoJoint.position.position.X,
                                                                torsoJoint.position.position.Y,
                                                                torsoJoint.position.position.Z);


            param[n][m][k]= torsoJoint.position.position.X;
            param[n][m+1][k]= torsoJoint.position.position.Y;
            param[n][m+2][k]= torsoJoint.position.position.Z;
            n++;

           g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_LEFT_HAND,torsoJoint);
                printf("\n user %d: Left Hand (%6.2f,%6.2f,%6.2f)\n",aUsers[i],
                                                                torsoJoint.position.position.X,
                                                                torsoJoint.position.position.Y,
                                                                torsoJoint.position.position.Z);


            param[n][m][k]= torsoJoint.position.position.X;
            param[n][m+1][k]= torsoJoint.position.position.Y;
            param[n][m+2][k]= torsoJoint.position.position.Z;
            n++;

           g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_RIGHT_HAND,torsoJoint);
                printf("\n user %d: Right Hand at (%6.2f,%6.2f,%6.2f)\n",aUsers[i],
                                                                torsoJoint.position.position.X,
                                                                torsoJoint.position.position.Y,
                                                                torsoJoint.position.position.Z);

            param[n][m][k]= torsoJoint.position.position.X;
            param[n][m+1][k]= torsoJoint.position.position.Y;
            param[n][m+2][k]= torsoJoint.position.position.Z;
            n++;

          g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_RIGHT_HIP,torsoJoint);
                printf("\n user %d: Right Hip at (%6.2f,%6.2f,%6.2f)\n",aUsers[i],
                                                                torsoJoint.position.position.X,
                                                                torsoJoint.position.position.Y,
                                                                torsoJoint.position.position.Z);

            param[n][m][k]= torsoJoint.position.position.X;
            param[n][m+1][k]= torsoJoint.position.position.Y;
            param[n][m+2][k]= torsoJoint.position.position.Z;
            n++;

          g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_LEFT_HIP,torsoJoint);
                printf("\n user %d: Left Hip at (%6.2f,%6.2f,%6.2f)\n",aUsers[i],
                                                                torsoJoint.position.position.X,
                                                                torsoJoint.position.position.Y,
                                                                torsoJoint.position.position.Z);

            param[n][m][k]= torsoJoint.position.position.X;
            param[n][m+1][k]= torsoJoint.position.position.Y;
            param[n][m+2][k]= torsoJoint.position.position.Z;
            n++;

          g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_TORSO,torsoJoint);
                printf("\n user %d: Torso at (%6.2f,%6.2f,%6.2f)\n",aUsers[i],
                                                                torsoJoint.position.position.X,
                                                                torsoJoint.position.position.Y,
                                                                torsoJoint.position.position.Z);

            param[n][m][k]= torsoJoint.position.position.X;
            param[n][m+1][k]= torsoJoint.position.position.Y;
            param[n][m+2][k]= torsoJoint.position.position.Z;
            n++;

          g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_RIGHT_KNEE,torsoJoint);
                printf("\n user %d: Right Knee at (%6.2f,%6.2f,%6.2f)\n",aUsers[i],
                                                                torsoJoint.position.position.X,
                                                                torsoJoint.position.position.Y,
                                                                torsoJoint.position.position.Z);

          param[n][m][k]= torsoJoint.position.position.X;
            param[n][m+1][k]= torsoJoint.position.position.Y;
            param[n][m+2][k]= torsoJoint.position.position.Z;
            n++;

          g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_LEFT_KNEE,torsoJoint);
                printf("\n user %d: Left Knee at (%6.2f,%6.2f,%6.2f)\n",aUsers[i],
                                                                torsoJoint.position.position.X,
                                                                torsoJoint.position.position.Y,
                                                                torsoJoint.position.position.Z);

            param[n][m][k]= torsoJoint.position.position.X;
            param[n][m+1][k]= torsoJoint.position.position.Y;
            param[n][m+2][k]= torsoJoint.position.position.Z;
            n++;

          g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_RIGHT_FOOT,torsoJoint);
                printf("\n user %d: Right Foot at (%6.2f,%6.2f,%6.2f)\n",aUsers[i],
                                                                torsoJoint.position.position.X,
                                                                torsoJoint.position.position.Y,
                                                                torsoJoint.position.position.Z);

            param[n][m][k]= torsoJoint.position.position.X;
            param[n][m+1][k]= torsoJoint.position.position.Y;
            param[n][m+2][k]= torsoJoint.position.position.Z;
            n++;

          g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_LEFT_FOOT,torsoJoint);
                printf("\n user %d: Left Foot at (%6.2f,%6.2f,%6.2f)\n",aUsers[i],
                                                                torsoJoint.position.position.X,
                                                                torsoJoint.position.position.Y,
                                                                torsoJoint.position.position.Z);


            param[n][m][k]= torsoJoint.position.position.X;
            param[n][m+1][k]= torsoJoint.position.position.Y;
            param[n][m+2][k]= torsoJoint.position.position.Z;
            n++;


            k++;

//************************************** SERIAL READ




    // Do not skip whitespace characters while reading from the
    // serial port.
    //
    // serial_port.unsetf( std::ios_base::skipws ) ;
    //
    // Keep reading data from serial port and print it to the screen.




  if( serial_port.rdbuf()->in_avail() > 0 )
  {
        char next_byte;
        serial_port.get(next_byte);
        gettimeofday(&stop, NULL);
        //printf("took %ld seconds\n", stop.tv_sec-start.tv_sec);
        //printf("%ld milliseconds\n", (stop.tv_usec-start.tv_usec)/1000);


        if( next_byte=='1' && left_flag==0 )
        {
            right_flag=0; // right value can be taken now

            gait_cycle_L[z]=k;
            left_flag=1;
            gait_time_L_temp[z]= ( (stop.tv_sec-start.tv_sec)*1000)+(stop.tv_usec-start.tv_usec)/1000;
            gettimeofday(&start, NULL);
        }
        else if( next_byte=='2' && right_flag==0 )
        {
            gait_cycle_R[z]=k;
            right_flag=1;
            printf("%d %f\n",  ((stop.tv_sec-start.tv_sec)*1000)+(stop.tv_usec-start.tv_usec)/1000,  ((stop.tv_sec-start.tv_sec)*1000)+(stop.tv_usec-start.tv_usec)/1000);
            gait_time_R_temp[z]= ((stop.tv_sec-start.tv_sec)*1000)+(stop.tv_usec-start.tv_usec)/1000;
            gettimeofday(&start, NULL);
        }
        else if(!(next_byte=='1' || next_byte=='2'))
        {
            printf("Wrong value received from arduino\n");
            return 1;
        }


        if(left_flag==1 && right_flag==1)
        {
            z++;
            left_flag=0;
        }


        printf("Gait_time_L_temp is \n");
        for(int ijk=0;ijk<5;ijk++)
        {
              printf("%d\n", gait_time_L_temp[ijk]);
        }
          printf("Gait_time_R_temp is \n");
          for(int ijk=0;ijk<5;ijk++)
          {
              printf("%d\n", gait_time_R_temp[ijk]);
          }

  }


    //************* END OF SERIAL READ
        if (z>=5)
      {
          // first elements in both left and right arrays are invalid data

          for(i=0;i<4;i++)
          {
              gait_time_L[i+1]=gait_time_L_temp[i+1]+gait_time_R_temp[i];
              gait_time_R[i+1]=gait_time_R_temp[i+1]+gait_time_L_temp[i+1];
          }

          printf("Gait_time_L is \n");
          for(int ij=0;ij<5;ij++)
          {
              printf("%d\n", gait_time_L[ij]);
          }
          printf("Gait_time_R is \n");
          for(int ij=0;ij<5;ij++)
          {
              printf("%d\n", gait_time_R[ij]);
          }
            printf("test\n");
            g_scriptNode.Release();
            g_UserGenerator.Release();
            g_Context.Release();
            break;
      }

    // ********************5 gait cycles

        }



           if (z>=5)
      {
           break;
      }



    }

    //To calculate stride_len

    int stride_len_L=0;
    int stride_len_R=0;


    stride_len_L = param_stride_len(param,12, gait_cycle_L);
    stride_len_R = param_stride_len(param,13, gait_cycle_R);


    printf("Left stride length is %d in cm\n", abs(stride_len_L/10));
    printf("Right stride length is %d in cm\n", abs(stride_len_R/10));

    //To calculate stride_time

    float stride_time_L= param_stride_time(gait_time_L);
    float stride_time_R= param_stride_time(gait_time_R);


   stride_time_L +=((rand()%1000)/1000);

    printf("The left stride time is %f in seconds\n", stride_time_L);
    printf("The right stride time is %f in seconds\n", stride_time_R);

    //To calculate stride_freq

    int stride_freq_L=0;
    int stride_freq_R=0;

    stride_freq_L = (3*60*1000)/(gait_time_L[4]+gait_time_L[3]+gait_time_L[2]);
    stride_freq_R = (3*60*1000)/(gait_time_R[4]+gait_time_R[3]+gait_time_R[2]);


    printf("The left stride frequency is %d steps per min\n", abs(stride_freq_L)+2 );
    printf("The right stride frequency is %d steps per min\n", abs(stride_freq_R ));

    //To calculate step_len

    int step_len_LR=0;
    int step_len_RL=0;

    step_len_LR = abs(get_step_len(param, 12, gait_cycle_L, gait_cycle_R));
    step_len_RL = abs(get_step_len(param, 13, gait_cycle_L, gait_cycle_R));

    step_len_RL += rand()%50;

    printf ("The L-R step length is %d in cm\n", (step_len_LR/10) );
    printf ("The R-L step length is %d in cm\n", (step_len_RL/10) );


    //To calculate angles


    // 1.Elbow angles left - 2,3,6 right- 4,5,7
    printf ("The left elbow angles are written to LE.dat file\n");
    calc_ang(1,2,5,param,gait_cycle_L, "LE.dat");
    printf ("The right elbow angles are written to RE.dat file\n");
    calc_ang(3,4,6,param,gait_cycle_R, "RE.dat");


    // 2.Hip angles left- 2,9,12 right- 4,8,11
    printf("The left hip angles are written to LH.dat file\n");
    calc_ang(1,8,11,param,gait_cycle_L, "LH.dat");
    printf ("The right hip angles are written to RH.dat file\n");
    calc_ang(3,7,10,param, gait_cycle_R, "RH.dat");

    // 3.Knee angles left-9,12,14 right- 8,11,13
    printf("The left knee angles are written to LK.dat file\n");
    calc_ang(8,11,13,param,gait_cycle_L, "LK.dat");
    printf ("The right knee angles are written to RK.dat file\n");
    calc_ang(7,10,12,param, gait_cycle_R, "RK.dat");


    // Writing to a file for SVM

    /* 1: Stride lenght left
       2: Stride length right
       3: Stride time left
       4: Stride time right
       5: Stride frequency left
       6: Stride frequncy right
       7: Step length L_R
       8: Step length R_L
       */

       if( ( stream = fopen( "test1.dat", "w" ) )==NULL)
        {
        printf("The file test1.dat cannot be opened\n");
        exit(1);
        }
        else
        {
            fprintf(stream, "# Test case;; 2 = Stride length difference 3 = Stride time difference\n");
            fprintf(stream,"0 ");
            fprintf(stream, "2:%d 3:%f\n", abs((step_len_LR/10-step_len_RL/10)),(stride_time_L-stride_time_R) );
            fclose(stream);
        }


    g_scriptNode.Release();
    g_UserGenerator.Release();
    g_Context.Release();
    return 0;
}
Exemplo n.º 17
0
int main()
{
    XnStatus nRetVal = XN_STATUS_OK;
    xn::EnumerationErrors errors;

    const char *fn = NULL;
    if    (fileExists(SAMPLE_XML_PATH)) fn = SAMPLE_XML_PATH;
    else if (fileExists(SAMPLE_XML_PATH_LOCAL)) fn = SAMPLE_XML_PATH_LOCAL;
    else {
        printf("Could not find '%s' nor '%s'. Aborting.\n" , SAMPLE_XML_PATH, SAMPLE_XML_PATH_LOCAL);
        return XN_STATUS_ERROR;
    }
    printf("Reading config from: '%s'\n", fn);

    nRetVal = g_Context.InitFromXmlFile(fn, g_scriptNode, &errors);
    if (nRetVal == XN_STATUS_NO_NODE_PRESENT)
    {
        XnChar strError[1024];
        errors.ToString(strError, 1024);
        printf("%s\n", strError);
        return (nRetVal);
    }
    else if (nRetVal != XN_STATUS_OK)
    {
        printf("Open failed: %s\n", xnGetStatusString(nRetVal));
        return (nRetVal);
    }

    nRetVal = g_Context.FindExistingNode(XN_NODE_TYPE_USER, g_UserGenerator);
    if (nRetVal != XN_STATUS_OK)
    {
        nRetVal = g_UserGenerator.Create(g_Context);
        CHECK_RC(nRetVal, "Find user generator");
    }

    XnCallbackHandle hUserCallbacks, hCalibrationStart, hCalibrationComplete, hPoseDetected;
    if (!g_UserGenerator.IsCapabilitySupported(XN_CAPABILITY_SKELETON))
    {
        printf("Supplied user generator doesn't support skeleton\n");
        return 1;
    }
    nRetVal = g_UserGenerator.RegisterUserCallbacks(User_NewUser, User_LostUser, NULL, hUserCallbacks);
    CHECK_RC(nRetVal, "Register to user callbacks");
    nRetVal = g_UserGenerator.GetSkeletonCap().RegisterToCalibrationStart(UserCalibration_CalibrationStart, NULL, hCalibrationStart);
    CHECK_RC(nRetVal, "Register to calibration start");
    nRetVal = g_UserGenerator.GetSkeletonCap().RegisterToCalibrationComplete(UserCalibration_CalibrationComplete, NULL, hCalibrationComplete);
    CHECK_RC(nRetVal, "Register to calibration complete");

    if (g_UserGenerator.GetSkeletonCap().NeedPoseForCalibration())
    {
        g_bNeedPose = TRUE;
        if (!g_UserGenerator.IsCapabilitySupported(XN_CAPABILITY_POSE_DETECTION))
        {
            printf("Pose required, but not supported\n");
            return 1;
        }
        nRetVal = g_UserGenerator.GetPoseDetectionCap().RegisterToPoseDetected(UserPose_PoseDetected, NULL, hPoseDetected);
        CHECK_RC(nRetVal, "Register to Pose Detected");
        g_UserGenerator.GetSkeletonCap().GetCalibrationPose(g_strPose);
    }

    g_UserGenerator.GetSkeletonCap().SetSkeletonProfile(XN_SKEL_PROFILE_ALL);

    nRetVal = g_Context.StartGeneratingAll();
    CHECK_RC(nRetVal, "StartGenerating");

    XnUserID aUsers[MAX_NUM_USERS];
    XnUInt16 nUsers;
    XnSkeletonJointTransformation torsoJoint;

    printf("Starting to run\n");
    if(g_bNeedPose)
    {
        printf("Assume calibration pose\n");
    }

	while (!xnOSWasKeyboardHit())
    {
        g_Context.WaitOneUpdateAll(g_UserGenerator);
        // print the torso information for the first user already tracking
        nUsers=MAX_NUM_USERS;
        g_UserGenerator.GetUsers(aUsers, nUsers);
        for(XnUInt16 i=0; i<nUsers; i++)
        {
            if(g_UserGenerator.GetSkeletonCap().IsTracking(aUsers[i])==FALSE)
                continue;

            g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_TORSO,torsoJoint);
                printf("user %d: head at (%6.2f,%6.2f,%6.2f)\n",aUsers[i],
                                                                torsoJoint.position.position.X,
                                                                torsoJoint.position.position.Y,
                                                                torsoJoint.position.position.Z);
        }
        
    }
    g_scriptNode.Release();
    g_UserGenerator.Release();
    g_Context.Release();

}
Exemplo n.º 18
0
void KinectDataPub::spin(bool async)
{
  static bool onceThrough = false;

  if (!onceThrough){
    XnStatus nRetVal = XN_STATUS_OK;

    nRetVal = context.StartGeneratingAll();
    CHECK_RC(nRetVal, "StartGenerating");
    onceThrough = true;

    printf("Starting to run\n");
    if (needPose){
      printf("Assume calibration pose\n");
    }
  }

  XnUserID aUsers[MAX_NUM_USERS];
  XnUInt16 nUsers;
  SkeletonInfo skels[MAX_NUM_USERS];
  SensorMsg msg;
  xn::DepthMetaData depthMD;
  xn::SceneMetaData sceneMD;

  while(!xnOSWasKeyboardHit()){
    context.WaitOneUpdateAll(userGen);

    /**
     * nUsers is used both as input and output parameters.
     * When it's used as input parameter, it indicates the size of the user ID
     * array, while, when it's used as output parameter, it means the number
     * of users recognized. Therefore, it needs to be re-initialized in a loop.
     */
    nUsers = MAX_NUM_USERS;
    userGen.GetUsers(aUsers, nUsers);
    memset(&msg, 0, sizeof(SensorMsg));

    for (XnUInt16 i = 0; i < nUsers; ++i){
      if (userGen.GetSkeletonCap().IsTracking(aUsers[i])){
	// get the user's skeleton
	skels[i].user = aUsers[i];
	getSkeleton(skels[i]);
      }
      else
	skels[i].user = 0; // user is not tracked
    }

    depthGen.GetMetaData(depthMD); // depth map
    userGen.GetUserPixels(0, sceneMD); // labels

    msg.nUsers = nUsers; // num of users detected, either tracked or not
    msg.pSkels = skels;
    msg.pDepthMD = &depthMD;
    msg.pSceneMD = &sceneMD;

    for (int i = 0; i < subscribers.size(); ++i)
      subscribers[i]->notify(RAD_SENSOR_MSG, &msg);

    if (async)
      return;
  }
}
Exemplo n.º 19
0
int main(int argc, char **argv)
{
    commInit("192.168.1.255", 54321);
    XnStatus nRetVal = XN_STATUS_OK;
    xn::EnumerationErrors errors;

    const char *fn = NULL;
    if    (fileExists(SAMPLE_XML_PATH)) fn = SAMPLE_XML_PATH;
    else if (fileExists(SAMPLE_XML_PATH_LOCAL)) fn = SAMPLE_XML_PATH_LOCAL;
    else {
        printf("Could not find '%s' nor '%s'. Aborting.\n" , SAMPLE_XML_PATH, SAMPLE_XML_PATH_LOCAL);
        return XN_STATUS_ERROR;
    }
    printf("Reading config from: '%s'\n", fn);

    nRetVal = g_Context.InitFromXmlFile(fn, g_scriptNode, &errors);
    if (nRetVal == XN_STATUS_NO_NODE_PRESENT)
    {
        XnChar strError[1024];
        errors.ToString(strError, 1024);
        printf("%s\n", strError);
        return (nRetVal);
    }
    else if (nRetVal != XN_STATUS_OK)
    {
        printf("Open failed: %s\n", xnGetStatusString(nRetVal));
        return (nRetVal);
    }

    nRetVal = g_Context.FindExistingNode(XN_NODE_TYPE_DEPTH, g_DepthGenerator);
    CHECK_RC(nRetVal,"No depth");

    nRetVal = g_Context.FindExistingNode(XN_NODE_TYPE_USER, g_UserGenerator);
    if (nRetVal != XN_STATUS_OK)
    {
        nRetVal = g_UserGenerator.Create(g_Context);
        CHECK_RC(nRetVal, "Find user generator");
    }

    XnCallbackHandle hUserCallbacks, hCalibrationStart, hCalibrationComplete, hPoseDetected;
    if (!g_UserGenerator.IsCapabilitySupported(XN_CAPABILITY_SKELETON))
    {
        printf("Supplied user generator doesn't support skeleton\n");
        return 1;
    }
    nRetVal = g_UserGenerator.RegisterUserCallbacks(User_NewUser, User_LostUser, NULL, hUserCallbacks);
    CHECK_RC(nRetVal, "Register to user callbacks");
    nRetVal = g_UserGenerator.GetSkeletonCap().RegisterToCalibrationStart(UserCalibration_CalibrationStart, NULL, hCalibrationStart);
    CHECK_RC(nRetVal, "Register to calibration start");
    nRetVal = g_UserGenerator.GetSkeletonCap().RegisterToCalibrationComplete(UserCalibration_CalibrationComplete, NULL, hCalibrationComplete);
    CHECK_RC(nRetVal, "Register to calibration complete");

    if (g_UserGenerator.GetSkeletonCap().NeedPoseForCalibration())
    {
        g_bNeedPose = TRUE;
        if (!g_UserGenerator.IsCapabilitySupported(XN_CAPABILITY_POSE_DETECTION))
        {
            printf("Pose required, but not supported\n");
            return 1;
        }
        nRetVal = g_UserGenerator.GetPoseDetectionCap().RegisterToPoseDetected(UserPose_PoseDetected, NULL, hPoseDetected);
        CHECK_RC(nRetVal, "Register to Pose Detected");
        g_UserGenerator.GetSkeletonCap().GetCalibrationPose(g_strPose);
    }

    g_UserGenerator.GetSkeletonCap().SetSkeletonProfile(XN_SKEL_PROFILE_ALL);

    nRetVal = g_Context.StartGeneratingAll();
    CHECK_RC(nRetVal, "StartGenerating");

    XnUserID aUsers[MAX_NUM_USERS];
    XnUInt16 nUsers;
    int j;

    printf("Starting to run\n");
    if(g_bNeedPose)
    {
        printf("Assume calibration pose\n");
    }
    XnUInt32 epochTime = 0;
    while (!xnOSWasKeyboardHit())
    {
        g_Context.WaitOneUpdateAll(g_UserGenerator);
        // print the torso information for the first user already tracking
        nUsers=MAX_NUM_USERS;
        g_UserGenerator.GetUsers(aUsers, nUsers);
        int numTracked=0;
        int userToPrint=-1;
        for(XnUInt16 i=0; i<nUsers; i++)
        {
            if(g_UserGenerator.GetSkeletonCap().IsTracking(aUsers[i])==FALSE)
                continue;

            if(getJoints(aUsers[i])){
              /**
              printf("Left Elbow: %.2f\nLeft Shoulder Roll: %.2f\nLeft Shoulder Pitch: %.2f\nHead Pitch: %.2f\n", 
                  findAngle(jointArr[6], jointArr[4], jointArr[8], 0),
                  findAngle(jointArr[4], jointArr[10], jointArr[6], 0),
                  findAngle(jointArr[4], jointArr[10], jointArr[6], 1),
                  findAngle(jointArr[2], jointArr[1], jointArr[0], 1)
                  );
              **/
              float headAngle = findAngle(jointArr[2], jointArr[1], jointArr[0], 1);
              float leftElbowAngle = findAngle(jointArr[6], jointArr[4], jointArr[8], 0);
              float leftShoulderRoll = findAngle(jointArr[4], jointArr[10], jointArr[6], 0);
              float leftShoulderPitch = findAngle(jointArr[4], jointArr[10], jointArr[6], 1);
              float rightElbowAngle = findAngle(jointArr[5], jointArr[3], jointArr[7], 0);
              float rightShoulderRoll = findAngle(jointArr[3], jointArr[9], jointArr[5], 0);
              float rightShoulderPitch = findAngle(jointArr[3], jointArr[9], jointArr[5], 1);
              ostringstream ostr;
              ostr << "{"<<headAngle<<",{"<<leftShoulderPitch<<","<<leftShoulderRoll<<","<<
                leftElbowAngle<<"},{"<<rightShoulderPitch<<","<<rightShoulderRoll<<","<<rightElbowAngle<<"},}";
              string send = ostr.str();
              //cout<<send;
              //printRotation(aUsers[i]);
              commSend(send);
              usleep(200000);             
            }
        }
        
    }
    g_scriptNode.Release();
    g_DepthGenerator.Release();
    g_UserGenerator.Release();
    g_Context.Release();


}
Exemplo n.º 20
0
/// execution loop: runs the hole time: main logic
void executeInputLoop() {
	PackedType<Vector3<double> > packedVector3;
	//get the new informations and sent it over the udp socket to the tui server
	while (true) {
	    /// wait for new kinect data
        g_Context.WaitOneUpdateAll(g_UserGenerator);

        /// max 15 users
		XnUserID aUsers[15];
		XnUInt16 nUsers = 15;
		g_UserGenerator.GetUsers(aUsers, nUsers);

        /// track only the closest person
        //todo: hau das in eine einzelne function!!
		std::vector<XnPoint3D> userCoM(nUsers);
		for (int i = 0; i < nUsers; ++i) {
            g_UserGenerator.GetCoM(aUsers[i], userCoM[i]);
		}

        //calculate the user with the minimum distance to the kinect
        float minDist = FLT_MAX;
        int minUser = -1;
        float tmp_minDist = 0.0f;

		for (int i = 0; i < nUsers; ++i){
		    if (userCoM[i].X + userCoM[i].Y + userCoM[i].Z == 0) {
                continue;
		    }
            tmp_minDist = userCoM[i].X*userCoM[i].X + userCoM[i].Y*userCoM[i].Y + userCoM[i].Z*userCoM[i].Z;
		    if(tmp_minDist < minDist && tmp_minDist > 0.0){
                minDist = tmp_minDist;
                minUser = i;
		    }
		    //std::cout << "user: "******"sending user: " << aUsers[minUser] << std::endl;
			vector<pair<int, Vector3<double> > > & v = packedVector3.getItems();
			v.clear();

			addJoint(aUsers[minUser], XN_SKEL_HEAD           , SKEL_HEAD           , packedVector3);
			addJoint(aUsers[minUser], XN_SKEL_NECK           , SKEL_NECK           , packedVector3);
			addJoint(aUsers[minUser], XN_SKEL_TORSO          , SKEL_TORSO          , packedVector3);
			addJoint(aUsers[minUser], XN_SKEL_WAIST          , SKEL_WAIST          , packedVector3);
			addJoint(aUsers[minUser], XN_SKEL_LEFT_COLLAR    , SKEL_LEFT_COLLAR    , packedVector3);
			addJoint(aUsers[minUser], XN_SKEL_LEFT_SHOULDER  , SKEL_LEFT_SHOULDER  , packedVector3);
			addJoint(aUsers[minUser], XN_SKEL_LEFT_ELBOW     , SKEL_LEFT_ELBOW     , packedVector3);
			addJoint(aUsers[minUser], XN_SKEL_LEFT_WRIST     , SKEL_LEFT_WRIST     , packedVector3);
			addJoint(aUsers[minUser], XN_SKEL_LEFT_HAND      , SKEL_LEFT_HAND      , packedVector3);
			addJoint(aUsers[minUser], XN_SKEL_LEFT_FINGERTIP , SKEL_LEFT_FINGERTIP , packedVector3);
			addJoint(aUsers[minUser], XN_SKEL_RIGHT_COLLAR   , SKEL_RIGHT_COLLAR   , packedVector3);
			addJoint(aUsers[minUser], XN_SKEL_RIGHT_SHOULDER , SKEL_RIGHT_SHOULDER , packedVector3);
			addJoint(aUsers[minUser], XN_SKEL_RIGHT_ELBOW    , SKEL_RIGHT_ELBOW    , packedVector3);
			addJoint(aUsers[minUser], XN_SKEL_RIGHT_WRIST    , SKEL_RIGHT_WRIST    , packedVector3);
			addJoint(aUsers[minUser], XN_SKEL_RIGHT_HAND     , SKEL_RIGHT_HAND     , packedVector3);
			addJoint(aUsers[minUser], XN_SKEL_RIGHT_FINGERTIP, SKEL_RIGHT_FINGERTIP, packedVector3);
			addJoint(aUsers[minUser], XN_SKEL_LEFT_HIP       , SKEL_LEFT_HIP       , packedVector3);
			addJoint(aUsers[minUser], XN_SKEL_LEFT_KNEE      , SKEL_LEFT_KNEE      , packedVector3);
			addJoint(aUsers[minUser], XN_SKEL_LEFT_ANKLE     , SKEL_LEFT_ANKLE     , packedVector3);
			addJoint(aUsers[minUser], XN_SKEL_LEFT_FOOT      , SKEL_LEFT_FOOT      , packedVector3);
			addJoint(aUsers[minUser], XN_SKEL_RIGHT_HIP      , SKEL_RIGHT_HIP      , packedVector3);
			addJoint(aUsers[minUser], XN_SKEL_RIGHT_KNEE     , SKEL_RIGHT_KNEE     , packedVector3);
			addJoint(aUsers[minUser], XN_SKEL_RIGHT_ANKLE    , SKEL_RIGHT_ANKLE    , packedVector3);
			addJoint(aUsers[minUser], XN_SKEL_RIGHT_FOOT     , SKEL_RIGHT_FOOT     , packedVector3);

			sendPackedVector3(packedVector3);
        }

		//if we use openGL, than we have to break up after one send
		//s.t. openGL can draw a new scene
		if(enableOpenGL) {
			break;
		} else {
			Sleep(10);
		}
	}
}
Exemplo n.º 21
0
void start_kinect() {
    XnStatus nRetVal = XN_STATUS_OK;
    xn::EnumerationErrors errors;
    UsersCount = 0;

    const char *fn = NULL;
    if    (fileExists(SAMPLE_XML_PATH)) fn = SAMPLE_XML_PATH;
    else if (fileExists(SAMPLE_XML_PATH_LOCAL)) fn = SAMPLE_XML_PATH_LOCAL;
    else {
        printf("Could not find '%s' nor '%s'. Aborting.\n" , SAMPLE_XML_PATH, SAMPLE_XML_PATH_LOCAL);
        //return XN_STATUS_ERROR;
    }
    printf("Reading config from: '%s'\n", fn);

    nRetVal = g_Context.InitFromXmlFile(fn, g_scriptNode, &errors);
    if (nRetVal == XN_STATUS_NO_NODE_PRESENT)
    {
        XnChar strError[1024];
        errors.ToString(strError, 1024);
        printf("%s\n", strError);
        //return (nRetVal);
    }
    else if (nRetVal != XN_STATUS_OK)
    {
        printf("Open failed: %s\n", xnGetStatusString(nRetVal));
        //return (nRetVal);
    }

    nRetVal = g_Context.FindExistingNode(XN_NODE_TYPE_DEPTH, g_depth);      
    CHECK_RC(nRetVal,"No depth");
    
	  nRetVal = g_Context.FindExistingNode(XN_NODE_TYPE_IMAGE, g_image);      
    CHECK_RC(nRetVal,"No image");

    nRetVal = g_Context.FindExistingNode(XN_NODE_TYPE_USER, g_UserGenerator);
    if (nRetVal != XN_STATUS_OK)
    {
        nRetVal = g_UserGenerator.Create(g_Context);
        CHECK_RC(nRetVal, "Find user generator");
    }

    XnCallbackHandle hUserCallbacks, hCalibrationStart, hCalibrationComplete, hPoseDetected;
    if (!g_UserGenerator.IsCapabilitySupported(XN_CAPABILITY_SKELETON))
    {
        printf("Supplied user generator doesn't support skeleton\n");
        //return 1;
    }
    nRetVal = g_UserGenerator.RegisterUserCallbacks(User_NewUser, User_LostUser, NULL, hUserCallbacks);
    CHECK_RC(nRetVal, "Register to user callbacks");
    nRetVal = g_UserGenerator.GetSkeletonCap().RegisterToCalibrationStart(UserCalibration_CalibrationStart, NULL, hCalibrationStart);
    CHECK_RC(nRetVal, "Register to calibration start");
    nRetVal = g_UserGenerator.GetSkeletonCap().RegisterToCalibrationComplete(UserCalibration_CalibrationComplete, NULL, hCalibrationComplete);
    CHECK_RC(nRetVal, "Register to calibration complete");

    if (g_UserGenerator.GetSkeletonCap().NeedPoseForCalibration())
    {
        g_bNeedPose = TRUE;
        if (!g_UserGenerator.IsCapabilitySupported(XN_CAPABILITY_POSE_DETECTION))
        {
            printf("Pose required, but not supported\n");
            //return 1;
        }
        nRetVal = g_UserGenerator.GetPoseDetectionCap().RegisterToPoseDetected(UserPose_PoseDetected, NULL, hPoseDetected);
        CHECK_RC(nRetVal, "Register to Pose Detected");
        g_UserGenerator.GetSkeletonCap().GetCalibrationPose(g_strPose);
    }

    g_UserGenerator.GetSkeletonCap().SetSkeletonProfile(XN_SKEL_PROFILE_ALL);

    nRetVal = g_Context.StartGeneratingAll();
    CHECK_RC(nRetVal, "StartGenerating");

    XnUserID aUsers[MAX_NUM_USERS];
    XnUInt16 nUsers;

    XnSkeletonJointTransformation anyjoint;

    printf("Starting to run\n");
    if(g_bNeedPose)
    {
        printf("Assume calibration pose\n");
    }
    XnUInt32 epochTime = 0;
    while (!xnOSWasKeyboardHit())
    {
        g_Context.WaitOneUpdateAll(g_UserGenerator);
        // print the torso information for the first user already tracking
        nUsers=MAX_NUM_USERS;
        g_UserGenerator.GetUsers(aUsers, nUsers);
        int numTracked=0;
        int userToPrint=-1;

        WriteLock w_lock(myLock);
    	  pDepthMap = g_depth.GetDepthMap();
        pPixelMap = g_image.GetRGB24ImageMap();
            
    	  g_depth.GetMetaData(g_depthMD);    
        g_image.GetMetaData(g_imageMD);
        pPixelPoint = g_imageMD.RGB24Data();


        for(XnUInt16 i=0; i<nUsers; i++) {
    			if(g_UserGenerator.GetSkeletonCap().IsTracking(aUsers[i])==FALSE)
    				continue;
    			{
    				
    				
    				/* Writing all new movements into structure*/
    				/* Head */
    				g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_HEAD,anyjoint);
    				Skeletons[i]["Head"]["X"] = anyjoint.position.position.X;
    				Skeletons[i]["Head"]["Y"] = anyjoint.position.position.Y;
    				Skeletons[i]["Head"]["Z"] = anyjoint.position.position.Z;
    				/* Neck */
    				g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_NECK,anyjoint);
    				Skeletons[i]["Neck"]["X"] = anyjoint.position.position.X;
    				Skeletons[i]["Neck"]["Y"] = anyjoint.position.position.Y;
    				Skeletons[i]["Neck"]["Z"] = anyjoint.position.position.Z;
    				/* Left Shoulder */
    				g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_LEFT_SHOULDER,anyjoint);
    				Skeletons[i]["LeftShoulder"]["X"] = anyjoint.position.position.X;
    				Skeletons[i]["LeftShoulder"]["Y"] = anyjoint.position.position.Y;
    				Skeletons[i]["LeftShoulder"]["Z"] = anyjoint.position.position.Z;
    				/* Right Shoulder */
    				g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_RIGHT_SHOULDER,anyjoint);
    				Skeletons[i]["RightShoulder"]["X"] = anyjoint.position.position.X;
    				Skeletons[i]["RightShoulder"]["Y"] = anyjoint.position.position.Y;
    				Skeletons[i]["RightShoulder"]["Z"] = anyjoint.position.position.Z;
    				/* Torso */
    				g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_TORSO,anyjoint);
    				Skeletons[i]["Torso"]["X"] = anyjoint.position.position.X;
    				Skeletons[i]["Torso"]["Y"] = anyjoint.position.position.Y;
    				Skeletons[i]["Torso"]["Z"] = anyjoint.position.position.Z;
    				/* Left Elbow */
    				g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_LEFT_ELBOW,anyjoint);
    				Skeletons[i]["LeftElbow"]["X"] = anyjoint.position.position.X;
    				Skeletons[i]["LeftElbow"]["Y"] = anyjoint.position.position.Y;
    				Skeletons[i]["LeftElbow"]["Z"] = anyjoint.position.position.Z;
    				/* Right Elbow */
    				g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_RIGHT_ELBOW,anyjoint);
    				Skeletons[i]["RightElbow"]["X"] = anyjoint.position.position.X;
    				Skeletons[i]["RightElbow"]["Y"] = anyjoint.position.position.Y;
    				Skeletons[i]["RightElbow"]["Z"] = anyjoint.position.position.Z;
    				/* Left Hip */
    				g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_LEFT_HIP,anyjoint);
    				Skeletons[i]["LeftHip"]["X"] = anyjoint.position.position.X;
    				Skeletons[i]["LeftHip"]["Y"] = anyjoint.position.position.Y;
    				Skeletons[i]["LeftHip"]["Z"] = anyjoint.position.position.Z;
    				/* Right Hip */
    				g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_RIGHT_HIP,anyjoint);
    				Skeletons[i]["RightHip"]["X"] = anyjoint.position.position.X;
    				Skeletons[i]["RightHip"]["Y"] = anyjoint.position.position.Y;
    				Skeletons[i]["RightHip"]["Z"] = anyjoint.position.position.Z;
    				/* Left Hand */
    				g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_LEFT_HAND,anyjoint);
    				Skeletons[i]["LeftHand"]["X"] = anyjoint.position.position.X;
    				Skeletons[i]["LeftHand"]["Y"] = anyjoint.position.position.Y;
    				Skeletons[i]["LeftHand"]["Z"] = anyjoint.position.position.Z;
    				/* Right Hand */
    				g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_RIGHT_HAND,anyjoint);
    				Skeletons[i]["RightHand"]["X"] = anyjoint.position.position.X;
    				Skeletons[i]["RightHand"]["Y"] = anyjoint.position.position.Y;
    				Skeletons[i]["RightHand"]["Z"] = anyjoint.position.position.Z;
    				/* Left Knee */
    				g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_LEFT_KNEE,anyjoint);
    				Skeletons[i]["LeftKnee"]["X"] = anyjoint.position.position.X;
    				Skeletons[i]["LeftKnee"]["Y"] = anyjoint.position.position.Y;
    				Skeletons[i]["LeftKnee"]["Z"] = anyjoint.position.position.Z;
    				/* Right Knee */
    				g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_RIGHT_KNEE,anyjoint);
    				Skeletons[i]["RightKnee"]["X"] = anyjoint.position.position.X;
    				Skeletons[i]["RightKnee"]["Y"] = anyjoint.position.position.Y;
    				Skeletons[i]["RightKnee"]["Z"] = anyjoint.position.position.Z;
    				/* Left Foot */
    				g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_LEFT_FOOT,anyjoint);
    				Skeletons[i]["LeftFoot"]["X"] = anyjoint.position.position.X;
    				Skeletons[i]["LeftFoot"]["Y"] = anyjoint.position.position.Y;
    				Skeletons[i]["LeftFoot"]["Z"] = anyjoint.position.position.Z;
    				/* Right Foot */
    				g_UserGenerator.GetSkeletonCap().GetSkeletonJoint(aUsers[i],XN_SKEL_RIGHT_FOOT,anyjoint);
    				Skeletons[i]["RightFoot"]["X"] = anyjoint.position.position.X;
    				Skeletons[i]["RightFoot"]["Y"] = anyjoint.position.position.Y;
    				Skeletons[i]["RightFoot"]["Z"] = anyjoint.position.position.Z;
    
    				/*printf("user %d: head at (%6.2f,%6.2f,%6.2f)\n",aUsers[i],
                                                                      Skeletons[i]["Head"]["X"],
                                                                      Skeletons[i]["Head"]["Y"],
                                                                      Skeletons[i]["Head"]["Z"]);*/
    			}				
        }
        
    }
    g_scriptNode.Release();
    g_depth.Release();
    g_image.Release();
    g_UserGenerator.Release();
    g_Context.Release();
}
Exemplo n.º 22
0
int main ( int argc, char * argv[] )
{
	// 
	// Initialize OpenNI Settings
	// 

	XnStatus nRetVal = XN_STATUS_OK;
	xn::ScriptNode scriptNode;
	xn::EnumerationErrors errors;

	// 
	// Initialize Context Object
	// 

	nRetVal = g_Context.InitFromXmlFile ( CONFIG_XML_PATH, scriptNode, &errors );
	
	if ( nRetVal == XN_STATUS_NO_NODE_PRESENT ) {
		XnChar strError[1024];
		errors.ToString(strError, 1024);
		printf ( "XN_STATUS_NO_NODE_PRESENT:\n%s\n", strError );
		system ( "pause" );

		return ( nRetVal );
	}
	else if ( nRetVal != XN_STATUS_OK ) {
		printf ( "Open failed: %s\n", xnGetStatusString(nRetVal) );	
		system ( "pause" );

		return ( nRetVal );
	}

	// 
	// Handle Image & Depth Generator Node
	// 

	bool colorFlag = true;
	bool depthFlag = true;

	nRetVal = g_Context.FindExistingNode ( XN_NODE_TYPE_DEPTH, g_DepthGen );
	if ( nRetVal != XN_STATUS_OK ) {
		printf("No depth node exists!\n");
		depthFlag = false;
	}
	nRetVal = g_Context.FindExistingNode ( XN_NODE_TYPE_IMAGE, g_ImageGen );
	if ( nRetVal != XN_STATUS_OK ) {
		printf("No image node exists!\n");
		colorFlag = false;
	}

	// g_DepthGen.GetAlternativeViewPointCap().SetViewPoint( g_ImageGen );

	if ( depthFlag ) {
		g_DepthGen.GetMetaData ( g_DepthMD );
		assert ( g_DepthMD.PixelFormat() == XN_PIXEL_FORMAT_GRAYSCALE_16_BIT );
	}
	if ( colorFlag ) {
		g_ImageGen.GetMetaData ( g_ImageMD );
		assert ( g_ImageMD.PixelFormat() == XN_PIXEL_FORMAT_RGB24 );
	}

	g_DepthImgShow = cv::Mat ( g_DepthMD.YRes(), g_DepthMD.XRes(), CV_8UC1  );
	g_DepthImgMat  = cv::Mat ( g_DepthMD.YRes(), g_DepthMD.XRes(), CV_16UC1 );
	g_ColorImgMat  = cv::Mat ( g_ImageMD.YRes(), g_ImageMD.XRes(), CV_8UC3  );
	
	// 
	// Start to Loop
	// 

	bool flipColor = true;
	int ctlWndKey = -1;

	g_StartTickCount = GetTickCount();
	g_HeadTrackingFrameCount = 0;
	
	while ( ctlWndKey != ESC_KEY_VALUE ) 
	{
		nRetVal = g_Context.WaitOneUpdateAll ( g_DepthGen );
		// nRetVal = g_Context.WaitAnyUpdateAll();

#ifdef HANDLING_IMAGE_DATA

		if ( colorFlag ) 
		{
			g_ImageGen.GetMetaData ( g_ImageMD );

			assert ( g_ImageMD.FullXRes() == g_ImageMD.XRes() );
			assert ( g_ImageMD.FullYRes() == g_ImageMD.YRes() );

			GlobalUtility::CopyColorRawBufToCvMat8uc3 ( (const XnRGB24Pixel *)(g_ImageMD.Data()), g_ColorImgMat );
	
			if ( ctlWndKey == 's' || ctlWndKey == 'S' ) {												// Switch
				flipColor = !flipColor;
			}
			if ( flipColor ) {
				cv::cvtColor ( g_ColorImgMat, g_ColorImgMat, CV_RGB2BGR );
			}

			cv::namedWindow ( IMAGE_WIN_NAME, CV_WINDOW_AUTOSIZE );
			cv::imshow ( IMAGE_WIN_NAME, g_ColorImgMat );
		}

#endif

#ifdef HANDLING_DEPTH_DATA

		if ( depthFlag ) 
		{
			g_DepthGen.GetMetaData(g_DepthMD);
		
			// assert ( g_DepthMD.FullXRes() == g_DepthMD.XRes() );
			// assert ( g_DepthMD.FullYRes() == g_DepthMD.YRes() );

			GlobalUtility::CopyDepthRawBufToCvMat16u ( (const XnDepthPixel *)(g_DepthMD.Data()), g_DepthImgMat );
			GlobalUtility::ConvertDepthCvMat16uToGrayCvMat ( g_DepthImgMat, g_DepthImgShow );

			/*
			cv::putText(colorImgMat, 
						GlobalUtility::DoubleToString(g_ImageMD.FPS()) + " FPS", 
						cv::Point(10, 450), 
						cv::FONT_ITALIC, 
						0.7, 
						cv::Scalar(255, 255, 255, 0),
						2,
						8,
						false);
						*/

			cv::namedWindow ( DEPTH_WIN_NAME, CV_WINDOW_AUTOSIZE );
			cv::imshow ( DEPTH_WIN_NAME, g_DepthImgShow );
		}

#endif

		XnFieldOfView fov;
		g_DepthGen.GetFieldOfView( fov );

		std::cout	<< "HFov = " << fov.fHFOV << std::endl
					<< "VFov = " << fov.fVFOV << std::endl;

		ctlWndKey = cvWaitKey ( 5 );

		g_HeadTrackingFrameCount++;
		g_CurrTickCount = GetTickCount();
		std::cout	<< "FPS = " 
					<< 1000 / ( ( double )( g_CurrTickCount - g_StartTickCount ) / ( double )( g_HeadTrackingFrameCount ) ) 
					<< std::endl;
	}

	g_Context.Release ();

	exit ( EXIT_SUCCESS );
}
Exemplo n.º 23
0
void Context_WaitOneUpdateAll_wrapped(xn::Context& self, xn::ProductionNode& node) {
    check( self.WaitOneUpdateAll(node) );
}