// Use this for initialization
    void Start()
    {
        rotationType = RotationType.Pinch;

        //sm = PXCMSession.CreateInstance();
        /* Initialize a PXCMSenseManager instance */
        sm = PXCMSenseManager.CreateInstance();
        if (sm != null)
        {
            /* Enable hand tracking and configure the hand module */
            pxcmStatus sts = sm.EnableHand();
            if (sts == pxcmStatus.PXCM_STATUS_NO_ERROR)
            {
                /* Hand module interface instance */
                hand = sm.QueryHand();
                /* Hand data interface instance */
                hand_data = hand.CreateOutput();

                // Create hand configuration instance and configure
                hcfg = hand.CreateActiveConfiguration();
                hcfg.EnableAllAlerts();
                hcfg.SubscribeAlert(OnFiredAlert);
                hcfg.EnableNormalizedJoints(true);
                hcfg.ApplyChanges();
                hcfg.Dispose();

                /* Initialize the execution pipeline */
                if (sm.Init() != pxcmStatus.PXCM_STATUS_NO_ERROR)
                {
                    OnDisable();
                }
            }
        }
    }
Пример #2
0
    // Update is called once per frame
    void Update()
    {
        /* Make sure PXCMSenseManager Instance is Initialized */
        if (SenseToolkitManager.Instance.SenseManager == null)
        {
            return;
        }
        /* Wait until any frame data is available true(aligned) false(unaligned) */
        if (SenseToolkitManager.Instance.SenseManager.AcquireFrame(false, 0) != pxcmStatus.PXCM_STATUS_NO_ERROR)
        {
            return;
        }
        /* Retrieve am instance of hand tracking Module */
        handAnalyzer = SenseToolkitManager.Instance.SenseManager.QueryHand();
        if (handAnalyzer != null)
        {
            /* Retrieve an instance of hand tracking Data */
            PXCMHandData _outputData = handAnalyzer.CreateOutput();
            if (_outputData != null)
            {
                _outputData.Update();
                //Retrieve joint data, gesture recognition data and alert notification data
                //refer to next section

                //AcquireFrame
                /* Retrieve Gesture Data */
                PXCMHandData.GestureData _gestureData;
                for (int i = 0; i < _outputData.QueryFiredGesturesNumber(); i++)
                {
                    if (_outputData.QueryFiredGestureData(i, out _gestureData) == pxcmStatus.PXCM_STATUS_NO_ERROR)
                    {
                        //Display the gestures:  explained in rendering the frame section
                        if ((_gestureData.name == "spreadfingers") || (_gestureData.name == "tap") ||
                            (_gestureData.name == "swipe"))
                        {
                            CursorController.isHandClicked = false;
                        }
                        else if ((_gestureData.name == "fist") || (_gestureData.name == "full_pinch") ||
                                 (_gestureData.name == "thumb_down") || (_gestureData.name == "thumb_up") ||
                                 (_gestureData.name == "two_fingers_pinch_open") || (_gestureData.name == "v_sign"))
                        {
                            CursorController.isHandClicked = true;
                        }
                        else if (_gestureData.name == "wave")
                        {
                            transform.position = new Vector3(0, 0, 0);
                        }
                    }
                }
            }
        }
        /* Realease the frame to process the next frame */
        SenseToolkitManager.Instance.SenseManager.ReleaseFrame();
    }
Пример #3
0
        public override void Work(Graphics g)
        {
            data = module.CreateOutput();
            data.Update();
            PXCMHandData.IHand hands = null;
            data.QueryHandData(PXCMHandData.AccessOrderType.ACCESS_ORDER_BY_ID, 0, out hands);
            if (hands == null)
            {
                return;
            }
            PXCMRectI32 rect      = hands.QueryBoundingBoxImage();
            Rectangle   rectangle = new Rectangle(rect.x, rect.y, rect.w, rect.h); // Convert to Rectangle

            g.DrawRectangle(pen, rectangle);                                       // Draw
        }
Пример #4
0
    void Start()
    {
        // Initialise a PXCMSenseManager instance
        psm = PXCMSenseManager.CreateInstance();
        if (psm == null)
        {
            Debug.LogError("SenseManager Init Failed");
            return;
        }

        // Enable the depth and colour streams
        psm.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_DEPTH, 640, 480);
        psm.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_COLOR, 640, 480);

        // Enable hand analysis
        pxcmStatus sts = psm.EnableHand();

        if (sts != pxcmStatus.PXCM_STATUS_NO_ERROR)
        {
            Debug.LogError("SenseManager Hand Init Failed");
            OnDisable();
            return;
        }
        handModule = psm.QueryHand();

        // Initialise the execution pipeline
        sts = psm.Init();
        if (sts != pxcmStatus.PXCM_STATUS_NO_ERROR)
        {
            Debug.LogError("SenseManager Pipeline Init Failed");
            OnDisable();
            return;
        }

        handData = handModule.CreateOutput();

        handConfig = handModule.CreateActiveConfiguration();
        handConfig.EnableAllGestures();
        handConfig.ApplyChanges();

        foreach (CapsuleCollider capsule in GetComponentsInChildren <CapsuleCollider>())
        {
            hands.Add(capsule.gameObject);
        }

        mainCamera = GetComponentInChildren <Camera>();
    }
Пример #5
0
        // 手の検出の初期化
        private void InitializeHandTracking()
        {
            // 手の検出器を取得する
            handAnalyzer = senseManager.QueryHand();
            if (handAnalyzer == null)
            {
                throw new Exception("手の検出器の取得に失敗しました");
            }

            // 手のデータを作成する
            handData = handAnalyzer.CreateOutput();
            if (handData == null)
            {
                throw new Exception("手の検出器の作成に失敗しました");
            }

            // RealSense カメラであれば、プロパティを設定する
            var device = senseManager.QueryCaptureManager().QueryDevice();

            PXCMCapture.DeviceInfo dinfo;
            device.QueryDeviceInfo(out dinfo);
            if (dinfo.model == PXCMCapture.DeviceModel.DEVICE_MODEL_IVCAM)
            {
                device.SetDepthConfidenceThreshold(1);
                //device.SetMirrorMode( PXCMCapture.Device.MirrorMode.MIRROR_MODE_DISABLED );
                device.SetIVCAMFilterOption(6);
            }

            // 手の検出の設定
            handConfig = handAnalyzer.CreateActiveConfiguration();

            // 登録されているジェスチャーを列挙する
            var num = handConfig.QueryGesturesTotalNumber();

            for (int i = 0; i < num; i++)
            {
                string gestureName;
                var    sts = handConfig.QueryGestureNameByIndex(i, out gestureName);
                if (sts == pxcmStatus.PXCM_STATUS_NO_ERROR)
                {
                    ComboGesture.Items.Add(gestureName);
                }
            }

            handConfig.ApplyChanges();
            handConfig.Update();
        }
Пример #6
0
        public override void Work(Graphics g)
        {
            // Retrieve gesture data
            hand = senseManager.QueryHand();
            face = senseManager.QueryFace(); //


            if (hand != null)
            {
                // Retrieve the most recent processed data
                handData = hand.CreateOutput();
                handData.Update();
                handWaving = handData.IsGestureFired("wave", out gestureData);
            }


            if (face != null)
            {
                faceData = face.CreateOutput();
                faceData.Update();

                //surching faces
                Int32 nfaces = faceData.QueryNumberOfDetectedFaces();
                for (Int32 i = 0; i < nfaces; i++)
                {
                    // Retrieve the data instance
                    PXCMFaceData.Face            faceI = faceData.QueryFaceByIndex(i);
                    PXCMFaceData.ExpressionsData edata = faceI.QueryExpressions();

                    if (edata != null)
                    {
                        edata.QueryExpression(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_SMILE, out score);
                        if (score.intensity >= 25)
                        {
                            smiling = true;
                        }
                        else
                        {
                            smiling = false;
                        }

                        Console.WriteLine(i + ": " + score.intensity);
                    }
                }
                faceData.Dispose();
            }
        }
Пример #7
0
        /// <summary> 手の検出の初期化 </summary>
        private void InitializeHandTracking()
        {
            // 手の検出器を取得する
            handAnalyzer = senseManager.QueryHand();
            if (handAnalyzer == null)
            {
                throw new Exception("手の検出器の取得に失敗しました");
            }

            // 手のデータを作成する
            handData = handAnalyzer.CreateOutput();
            if (handData == null)
            {
                throw new Exception("手の検出器の作成に失敗しました");
            }

            // RealSense カメラであれば、プロパティを設定する
            var device = senseManager.QueryCaptureManager().QueryDevice();

            PXCMCapture.DeviceInfo dinfo;
            device.QueryDeviceInfo(out dinfo);
            if (dinfo.model == PXCMCapture.DeviceModel.DEVICE_MODEL_IVCAM)
            {
                device.SetDepthConfidenceThreshold(1);
                //device.SetMirrorMode( PXCMCapture.Device.MirrorMode.MIRROR_MODE_DISABLED );
                device.SetIVCAMFilterOption(6);
            }

            // 手の検出の設定
            config = handAnalyzer.CreateActiveConfiguration();
            //config.EnableSegmentationImage(true);
            config.EnableJointSpeed(PXCMHandData.JointType.JOINT_MIDDLE_TIP, PXCMHandData.JointSpeedType.JOINT_SPEED_AVERAGE, 100);
            //config.EnableGesture("v_sign");
            config.EnableGesture("thumb_up");
            config.EnableGesture("thumb_down");
            //config.EnableGesture("tap");
            //config.EnableGesture("fist");
            config.SubscribeGesture(OnFiredGesture);
            config.ApplyChanges();
            config.Update();
            gestureTimer.Start();
        }
Пример #8
0
 public override void Listen()
 {
     // attach the controller to the PXCM sensor
     _senseManager = Session.CreateSenseManager();      
     _senseManager.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_COLOR, 640, 480, 30);
     _senseManager.EnableHand();
     _handModule = _senseManager.QueryHand();
     _handData = _handModule.CreateOutput();
     _handConfiguration = _handModule.CreateActiveConfiguration();
     _handConfiguration.SubscribeGesture(_handGestureHandler);
     _handConfiguration.SubscribeAlert(_handAlertHandler);
     _handConfiguration.EnableAlert(PXCMHandData.AlertType.ALERT_HAND_TRACKED);
     _handConfiguration.EnableAlert(PXCMHandData.AlertType.ALERT_HAND_CALIBRATED);
     _handConfiguration.EnableGesture("full_pinch");
     _handConfiguration.EnableGesture("thumb_up");
     _handConfiguration.ApplyChanges();
     _senseManager.Init(_handler);
     sensorActive = true;
     _senseManager.StreamFrames(true);
     _senseManager.Close();           
     }
        private void ProcessingThread()
        {
            // Start AcquireFrame/ReleaseFrame loop
            while (senseManager.AcquireFrame(true) >= pxcmStatus.PXCM_STATUS_NO_ERROR)
            {
                PXCMCapture.Sample  sample = senseManager.QuerySample();
                Bitmap              colorBitmap;
                PXCMImage.ImageData colorData;

                // Get color image data
                sample.color.AcquireAccess(PXCMImage.Access.ACCESS_READ, PXCMImage.PixelFormat.PIXEL_FORMAT_RGB24, out colorData);
                colorBitmap = colorData.ToBitmap(0, sample.color.info.width, sample.color.info.height);

                // Retrieve gesture data
                hand = senseManager.QueryHand();

                if (hand != null)
                {
                    // Retrieve the most recent processed data
                    handData = hand.CreateOutput();
                    handData.Update();
                    handWaving = handData.IsGestureFired("v_sign", out gestureData);
                }

                // Update the user interface
                UpdateUI(colorBitmap);

                // Release the frame
                if (handData != null)
                {
                    handData.Dispose();
                }
                colorBitmap.Dispose();
                sample.color.ReleaseAccess(colorData);
                senseManager.ReleaseFrame();
            }
        }
Пример #10
0
        // 手の検出の初期化
        private void InitializeHandTracking()
        {
            // 手の検出器を取得する
            handAnalyzer = senseManager.QueryHand();
            if (handAnalyzer == null)
            {
                throw new Exception("手の検出器の取得に失敗しました");
            }

            // 手のデータを作成する
            handData = handAnalyzer.CreateOutput();
            if (handData == null)
            {
                throw new Exception("手の検出器の作成に失敗しました");
            }

            // RealSense カメラであれば、プロパティを設定する
            var device = senseManager.QueryCaptureManager().QueryDevice();

            PXCMCapture.DeviceInfo dinfo;
            device.QueryDeviceInfo(out dinfo);
            if (dinfo.model == PXCMCapture.DeviceModel.DEVICE_MODEL_IVCAM)
            {
                device.SetDepthConfidenceThreshold(1);
                //device.SetMirrorMode( PXCMCapture.Device.MirrorMode.MIRROR_MODE_DISABLED );
                device.SetIVCAMFilterOption(6);
            }

            // 手の検出の設定
            var config = handAnalyzer.CreateActiveConfiguration();

            config.SetTrackingMode(PXCMHandData.TrackingModeType.TRACKING_MODE_EXTREMITIES);
            config.EnableSegmentationImage(true);

            config.ApplyChanges();
            config.Update();
        }
    // Use this for initialization
    void Start()
    {
        // Set up the reference to the aeroplane controller.
        m_Aeroplane = GetComponent <AeroplaneController>();

        /* Initialize a PXCMSenseManager instance */
        sm = PXCMSenseManager.CreateInstance();
        if (sm != null)
        {
            /* Enable hand tracking and configure the hand module */
            pxcmStatus sts = sm.EnableHand();
            if (sts == pxcmStatus.PXCM_STATUS_NO_ERROR)
            {
                /*init hand data structure*/
                handData = new PXCMHandData.IHand[2];

                /* Hand module interface instance */
                hand = sm.QueryHand();
                /* Hand data interface instance */
                hand_data = hand.CreateOutput();

                // Create hand configuration instance and configure
                hcfg = hand.CreateActiveConfiguration();
                hcfg.EnableAllAlerts();
                hcfg.SubscribeAlert(OnFiredAlert);
                hcfg.EnableNormalizedJoints(true);
                hcfg.ApplyChanges();
                hcfg.Dispose();

                /* Initialize the execution pipeline */
                if (sm.Init() != pxcmStatus.PXCM_STATUS_NO_ERROR)
                {
                    OnDisable();
                }
            }
        }
    }
        public void ProcessingThread()
        {
            // Start AcquireFrame/ReleaseFrame loop
            while (senseManager.AcquireFrame(true) >= pxcmStatus.PXCM_STATUS_NO_ERROR)
            {
                hand = senseManager.QueryHand();

                if (hand != null)
                {
                    // Retrieve the most recent processed data
                    handData = hand.CreateOutput();
                    handData.Update();

                    // Get number of tracked hands
                    nhands = handData.QueryNumberOfHands();

                    if (nhands > 0)
                    {
                        // Retrieve hand identifier
                        handData.QueryHandId(PXCMHandData.AccessOrderType.ACCESS_ORDER_BY_TIME, 0, out handId);

                        // Retrieve hand data
                        handData.QueryHandDataById(handId, out ihand);

                        PXCMHandData.BodySideType bodySideType = ihand.QueryBodySide();
                        if (bodySideType == PXCMHandData.BodySideType.BODY_SIDE_LEFT)
                        {
                            leftHand = true;
                        }
                        else if (bodySideType == PXCMHandData.BodySideType.BODY_SIDE_RIGHT)
                        {
                            leftHand = false;
                        }



                        // Retrieve all hand joint data
                        for (int i = 0; i < nhands; i++)
                        {
                            for (int j = 0; j < 0x20; j++)
                            {
                                PXCMHandData.JointData jointData;
                                ihand.QueryTrackedJoint((PXCMHandData.JointType)j, out jointData);
                                nodes[i][j] = jointData;
                            }
                        }

                        // Get world coordinates for tip of middle finger on the first hand in camera range
                        handTipX = nodes[0][Convert.ToInt32(PXCMHandData.JointType.JOINT_MIDDLE_TIP)].positionWorld.x;
                        handTipY = nodes[0][Convert.ToInt32(PXCMHandData.JointType.JOINT_MIDDLE_TIP)].positionWorld.y;
                        handTipZ = nodes[0][Convert.ToInt32(PXCMHandData.JointType.JOINT_MIDDLE_TIP)].positionWorld.z;


                        swipehandTipX = nodes[0][Convert.ToInt32(PXCMHandData.JointType.JOINT_MIDDLE_TIP)].positionImage.x;
                        swipehandTipY = nodes[0][Convert.ToInt32(PXCMHandData.JointType.JOINT_MIDDLE_TIP)].positionImage.y;
                        swipehandTipZ = nodes[0][Convert.ToInt32(PXCMHandData.JointType.JOINT_MIDDLE_TIP)].positionImage.z;

                        //Console.Out.WriteLine("Before x={0}", swipehandTipX);
                        //Console.Out.WriteLine("Before speed={0}", nodes[0][Convert.ToInt32(PXCMHandData.JointType.JOINT_MIDDLE_TIP)].speed.x);

                        // Retrieve gesture data
                        if (handData.IsGestureFired("spreadfingers", out gestureData))
                        {
                            gesture = Gesture.FingerSpread;
                        }
                        else if (handData.IsGestureFired("two_fingers_pinch_open", out gestureData))
                        {
                            gesture = Gesture.Pinch;
                        }
                        else if (handData.IsGestureFired("wave", out gestureData))
                        {
                            gesture = Gesture.Wave;
                        }
                        else if (handData.IsGestureFired("swipe_left", out gestureData))
                        {
                            gesture = Gesture.SwipeLeft;
                        }
                        else if (handData.IsGestureFired("swipe_right", out gestureData))
                        {
                            gesture = Gesture.SwipeRight;
                        }
                        else if (handData.IsGestureFired("fist", out gestureData))
                        {
                            gesture = Gesture.Fist;
                        }
                        else if (handData.IsGestureFired("thumb_up", out gestureData))
                        {
                            gesture = Gesture.Thumb;
                        }
                    }
                    else
                    {
                        gesture = Gesture.Undefined;
                    }

                    UpdateUI();
                    if (handData != null)
                    {
                        handData.Dispose();
                    }
                }
                senseManager.ReleaseFrame();
            }
        }
Пример #13
0
        private void ProcessingHandThread()
        {
            // Start AcquireFrame/ReleaseFrame loop
            while (senseManager.AcquireFrame(true) >= pxcmStatus.PXCM_STATUS_NO_ERROR)
            {
                hand = senseManager.QueryHand();

                if (hand != null)
                {

                    // Retrieve the most recent processed data
                    handData = hand.CreateOutput();
                    handData.Update();

                    // Get number of tracked hands
                    nhands = handData.QueryNumberOfHands();

                    if (nhands > 0)
                    {
                        // Retrieve hand identifier
                        handData.QueryHandId(PXCMHandData.AccessOrderType.ACCESS_ORDER_BY_TIME, 0, out handId);

                        // Retrieve hand data
                        handData.QueryHandDataById(handId, out ihand);

                        // Retrieve all hand joint data
                        for (int i = 0; i < nhands; i++)
                        {
                            for (int j = 0; j < 0x20; j++)
                            {
                                PXCMHandData.JointData jointData;
                                ihand.QueryTrackedJoint((PXCMHandData.JointType)j, out jointData);
                                nodes[i][j] = jointData;
                            }
                        }

                        // Get world coordinates for tip of middle finger on the first hand in camera range
                        handTipX = nodes[0][Convert.ToInt32(PXCMHandData.JointType.JOINT_MIDDLE_TIP)].positionWorld.x;
                        handTipY = nodes[0][Convert.ToInt32(PXCMHandData.JointType.JOINT_MIDDLE_TIP)].positionWorld.y;
                        handTipZ = nodes[0][Convert.ToInt32(PXCMHandData.JointType.JOINT_MIDDLE_TIP)].positionWorld.z;

                        // Retrieve gesture data
                        if (handData.IsGestureFired("spreadfingers", out gestureData))
                        {
                            gesture = Gesture.FingerSpread;
                        }
                        else if (handData.IsGestureFired("two_fingers_pinch_open", out gestureData))
                        {
                            gesture = Gesture.Pinch;
                        }
                        else if (handData.IsGestureFired("wave", out gestureData))
                        {
                            gesture = Gesture.Wave;
                        }
                    }
                    else
                    {
                        gesture = Gesture.Undefined;
                    }

                    // Get alert status
                    for (int i = 0; i < handData.QueryFiredAlertsNumber(); i++)
                    {
                        PXCMHandData.AlertData alertData;
                        if (handData.QueryFiredAlertData(i, out alertData) != pxcmStatus.PXCM_STATUS_NO_ERROR) { continue; }

                        //Displaying last alert
                        switch (alertData.label)
                        {
                            case PXCMHandData.AlertType.ALERT_HAND_DETECTED:
                                detectionAlert = "Hand Detected";
                                detectionStatusOk = true;
                                break;
                            case PXCMHandData.AlertType.ALERT_HAND_NOT_DETECTED:
                                detectionAlert = "Hand Not Detected";
                                detectionStatusOk = false;
                                break;
                            case PXCMHandData.AlertType.ALERT_HAND_CALIBRATED:
                                calibrationAlert = "Hand Calibrated";
                                calibrationStatusOk = true;
                                break;
                            case PXCMHandData.AlertType.ALERT_HAND_NOT_CALIBRATED:
                                calibrationAlert = "Hand Not Calibrated";
                                calibrationStatusOk = false;
                                break;
                            case PXCMHandData.AlertType.ALERT_HAND_INSIDE_BORDERS:
                                bordersAlert = "Hand Inside Borders";
                                borderStatusOk = true;
                                break;
                            case PXCMHandData.AlertType.ALERT_HAND_OUT_OF_BORDERS:
                                bordersAlert = "Hand Out Of Borders";
                                borderStatusOk = false;
                                break;
                        }
                    }

                    UpdateUI();
                    if (handData != null) handData.Dispose();
                }
                senseManager.ReleaseFrame();
            }
        }
Пример #14
0
    // Update is called once per frame
    void Update()
    {
        /* Make sure SenseManager Instance is valid */
        if (sm == null)
        {
            return;
        }

        /* Wait until any frame data is available */
        if (sm.AcquireFrame(false) != pxcmStatus.PXCM_STATUS_NO_ERROR)
        {
            return;
        }

        /* Retrieve hand tracking Module Instance */
        handAnalyzer = sm.QueryHand();

        if (handAnalyzer != null)
        {
            /* Retrieve hand tracking Data */
            PXCMHandData _handData = handAnalyzer.CreateOutput();
            if (_handData != null)
            {
                _handData.Update();

                /* Retrieve all joint Data */
                bool[] someJointsDetected = { false, false };
                for (int i = 0; i < _handData.QueryNumberOfHands(); i++)
                {
                    PXCMHandData.IHand _iHand;
                    if (_handData.QueryHandData(PXCMHandData.AccessOrderType.ACCESS_ORDER_FIXED, i, out _iHand) == pxcmStatus.PXCM_STATUS_NO_ERROR)
                    {
                        for (int j = 0; j < MaxJoints; j++)
                        {
                            if (_iHand.QueryTrackedJoint((PXCMHandData.JointType)j, out jointData[i, j]) != pxcmStatus.PXCM_STATUS_NO_ERROR)
                            {
                                jointData[i, j] = null;
                            }
                            else if (jointData[i, j].confidence == 100)
                            {
                                someJointsDetected[i] = true;
                            }
                        }
                        if (!handList.ContainsKey(_iHand.QueryUniqueId()))
                        {
                            handList.Add(_iHand.QueryUniqueId(), _iHand.QueryBodySide());
                        }
                    }
                }

                for (int i = 0; i < MaxHands; i++)
                {
                    if (!someJointsDetected[i] && handWasTracked[i])
                    {
                        for (int j = 0; j < MaxJoints; j++)
                        {
                            Joint joint = myJoints[i, j];
                            if (joint == null)
                            {
                                continue;
                            }
                            joint.transform.position = joint.originalPosition;
                            joint.transform.rotation = joint.originalRotation;

                            foreach (Joint e in joint.extensions)
                            {
                                e.transform.position = e.originalPosition;
                                e.transform.rotation = e.originalRotation;
                            }
                        }
                    }
                    else
                    {
                        if (!handWasTracked[i])
                        {
                            if (myJoints[i, 0] == null || jointData[i, 0] == null || jointData[i, 0].confidence < 100)
                            {
                                break;
                            }
                            PXCMPoint3DF32 smoothedPoint  = smoother3D[i, 0].SmoothValue(jointData[i, 0].positionWorld);
                            Vector3        targetPosition = new Vector3(-1 * smoothedPoint.x, smoothedPoint.y, smoothedPoint.z);
                            trackingOffset[i] = targetPosition - myJoints[i, 0].originalPosition;
                        }
                        /* Smooth the data and move the joints*/
                        MoveJoints(i);
                    }
                    handWasTracked[i] = someJointsDetected[i];
                }
            }
            handAnalyzer.Dispose();
        }


        sm.ReleaseFrame();

        RotateCam();
    }
Пример #15
0
	// Update is called once per frame
	void Update () {
		/* Make sure SenseManager Instance is valid */
		if (senseManager == null)
			return;
		
		/* Wait until any frame data is available */
		if (senseManager.AcquireFrame (false) != pxcmStatus.PXCM_STATUS_NO_ERROR)
			return;
		
		/* Retrieve hand tracking Module Instance */
		handAnalyzer = senseManager.QueryHand ();
		
		try
		{
			if (handAnalyzer != null) {
				/* Retrieve hand tracking Data */
				PXCMHandData _handData = handAnalyzer.CreateOutput ();
				if (_handData != null) {
					_handData.Update ();

					PXCMHandData.IHand[] _iHand = new PXCMHandData.IHand[MaxHands];
					NumOfHands = _handData.QueryNumberOfHands ();

					hands.isLeft = false;
					hands.isRight = false;

					/* Retrieve all joint Data */
					if (_handData.QueryHandData (PXCMHandData.AccessOrderType.ACCESS_ORDER_LEFT_HANDS, 0, out _iHand[0]) == pxcmStatus.PXCM_STATUS_NO_ERROR) {
						/*Identify left/right hand */
						gesture[0].isExist = true;
						hands.isLeft = true;

						for (int i = 0; i <  _handData.QueryFiredGesturesNumber(); i++){
							//Debug.Log (i.ToString());
							if (_handData.QueryFiredGestureData (i, out gesture[0].gestureData) == pxcmStatus.PXCM_STATUS_NO_ERROR)
								Debug.Log (gesture[0].gestureData.name);
								//continue;//If you want to use this gesture info, you need to realize a SEND function here.
						}
						for (int j = 0; j < MaxJoints; j++) {
							if (_iHand[0].QueryTrackedJoint ((PXCMHandData.JointType)j, out hands.jointData [0] [j]) != pxcmStatus.PXCM_STATUS_NO_ERROR)					
								hands.jointData [0] [j] = null;
						/*	hands.smoothPosition[0][j].AddSample(hands.jointData[0][j].positionWorld);
							hands.smoothLocalRotation[0][j].AddSample(((Quaternion)hands.jointData[0][j].localRotation).eulerAngles);
							hands.smoothGlobalRotation[0][j].AddSample(((Quaternion)hands.jointData[0][j].globalOrientation).eulerAngles);
						*/}

						if (!handList.ContainsKey (_iHand[0].QueryUniqueId ()))
							handList.Add (_iHand[0].QueryUniqueId (), _iHand[0].QueryBodySide ());
					}else{
						gesture[0].isExist = false;
					}

					if (_handData.QueryHandData (PXCMHandData.AccessOrderType.ACCESS_ORDER_RIGHT_HANDS, 0, out _iHand[1]) == pxcmStatus.PXCM_STATUS_NO_ERROR) {
						/*Identify left/right hand */	
						gesture[1].isExist = true;
						hands.isRight = true;

						for (int i = 0; i < _handData.QueryFiredGesturesNumber(); i++)
							if (_handData.QueryFiredGestureData (i, out gesture[1].gestureData) == pxcmStatus.PXCM_STATUS_NO_ERROR)
								continue;//If you want to use this gesture info, you need to realize a SEND function here.

						for (int j = 0; j < MaxJoints; j++) {
							if (_iHand[1].QueryTrackedJoint ((PXCMHandData.JointType)j, out hands.jointData [1] [j]) != pxcmStatus.PXCM_STATUS_NO_ERROR)					
								hands.jointData [1] [j] = null;
						}
						
						if (!handList.ContainsKey (_iHand[1].QueryUniqueId ()))
							handList.Add (_iHand[1].QueryUniqueId (), _iHand[1].QueryBodySide ());
					}else{
						gesture[1].isExist = false;
					}
				}
				_handData.Dispose ();
			}
		}
		catch (IOException ex)
		{
			Console.WriteLine("An IOException has been thrown!");
			Console.WriteLine(ex.ToString());
			Console.ReadLine();
			return;
		}
		handAnalyzer.Dispose ();
		senseManager.ReleaseFrame ();
	}
        // 手の検出の初期化
        private void InitializeHandTracking()
        {
            // 手の検出器を取得する
            handAnalyzer = senseManager.QueryHand();
            if ( handAnalyzer == null ) {
                throw new Exception( "手の検出器の取得に失敗しました" );
            }

            // 手のデータを作成する
            handData = handAnalyzer.CreateOutput();
            if ( handData == null ) {
                throw new Exception( "手の検出器の作成に失敗しました" );
            }

            // RealSense カメラであれば、プロパティを設定する
            var device = senseManager.QueryCaptureManager().QueryDevice();
            PXCMCapture.DeviceInfo dinfo;
            device.QueryDeviceInfo( out dinfo );
            if ( dinfo.model == PXCMCapture.DeviceModel.DEVICE_MODEL_IVCAM ) {
                device.SetDepthConfidenceThreshold( 1 );
                //device.SetMirrorMode( PXCMCapture.Device.MirrorMode.MIRROR_MODE_DISABLED );
                device.SetIVCAMFilterOption( 6 );
            }

            // 手の検出の設定
            var config = handAnalyzer.CreateActiveConfiguration();
            config.EnableSegmentationImage( true );

            config.ApplyChanges();
            config.Update();
        }
Пример #17
0
        public void InitializeHandsStream()
        {
            manager.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_DEPTH, 640, 480, 30);
            var s = manager.EnableHand();

            this.handAnalyzer = manager.QueryHand();

            var re = manager.Init();

            this.outputData = handAnalyzer.CreateOutput();

            if (re != pxcmStatus.PXCM_STATUS_NO_ERROR)
                throw new RealSenseException("error: " + re, re);

            this.isHandsStreamEnabled = true;
        }
Пример #18
0
    public Main.HandCoord[] GetJointCoordinates()
    {
        #region Catch exception errors
        /* Wait until frame is available and SenseManager is ready */

        /* Make sure SenseManager has an instance */
        if (SenseManager == null)
        {
            return(null);
        }

        /* Wait until any frame data is available */
        if (SenseManager.AcquireFrame(true) != pxcmStatus.PXCM_STATUS_NO_ERROR)
        {
            return(null);
        }

        #endregion

        #region Get joint coordinates
        HandModule = SenseManager.QueryHand();  // Get hand tracking Module instance
        HandData   = HandModule.CreateOutput(); // Get hand tracking data

        if (HandData != null)
        {
            HandData.Update();  // Update hand data to the most current output
            /*Reset the detected hands to zero*/
            for (int i = 0; i < NumOfHands; i++)
            {
                Coordinates[i].HandDetected = false;
            }

            /* Retrieve all joint data */
            for (int i = 0; i < HandData.QueryNumberOfHands(); i++)
            {
                Coordinates[i].HandDetected = true;
                PXCMHandData.IHand iHand;
                Status = HandData.QueryHandData(PXCMHandData.AccessOrderType.ACCESS_ORDER_FIXED, i, out iHand);
                if (Status != pxcmStatus.PXCM_STATUS_NO_ERROR)
                {
                    Debug.LogError(Status);
                }
                else
                {
                    for (int j = 0; j < NumOfJoints; j++)
                    {
                        Status = iHand.QueryTrackedJoint((PXCMHandData.JointType)j, out JointData[i][j]);
                        if (Status == pxcmStatus.PXCM_STATUS_NO_ERROR)
                        {
                            Coordinates[i].Coordinates[0, j] = JointData[i][j].positionWorld.x * -100;
                            Coordinates[i].Coordinates[1, j] = JointData[i][j].positionWorld.y * 100;
                            Coordinates[i].Coordinates[2, j] = JointData[i][j].positionWorld.z * 100;
                            Coordinates[i].Coordinates[3, j] = JointData[i][j].speed.x * -100;
                            Coordinates[i].Coordinates[4, j] = JointData[i][j].speed.y * -100;
                            Coordinates[i].Coordinates[5, j] = JointData[i][j].speed.z * 100;
                        }
                    }
                }
            }
        }

        SenseManager.ReleaseFrame();    // Prepare for a new frame

        return(Coordinates);

        #endregion
    }
Пример #19
0
        void OnEnable()
        {
            Initialized = false;

            /* Create a SenseManager instance */
            SenseManager = PXCMSenseManager.CreateInstance();

            if (SenseManager == null)
            {
                print("Unable to create the pipeline instance");
                return;
            }

            if (_speechCommandsRef.Count != 0)
            {
                SetSenseOption(SenseOption.SenseOptionID.Speech);
            }

            int numberOfEnabledModalities = 0;

            //Set mode according to RunMode - play from file / record / live stream
            if (RunMode == MCTTypes.RunModes.PlayFromFile)
            {
                //CHECK IF FILE EXISTS
                if (!System.IO.File.Exists(FilePath))
                {
                    Debug.LogWarning("No Filepath Set Or File Doesn't Exist, Run Mode Will Be Changed to Live Stream");
                    RunMode = MCTTypes.RunModes.LiveStream;
                }
                else
                {
                    PXCMCaptureManager cManager = SenseManager.QueryCaptureManager();
                    cManager.SetFileName(FilePath, false);
                    Debug.Log("SenseToolkitManager: Playing from file: " + FilePath);
                }
            }

            if (RunMode == MCTTypes.RunModes.RecordToFile)
            {
                //CHECK IF PATH
                string PathOnly = FilePath;
                while (!PathOnly[PathOnly.Length - 1].Equals('\\'))
                {
                    PathOnly = PathOnly.Remove(PathOnly.Length - 1, 1);
                }

                if (!System.IO.Directory.Exists(PathOnly))
                {
                    Debug.LogWarning("No Filepath Set Or Path Doesn't Exist, Run Mode Will Be Changed to Live Stream");
                    RunMode = MCTTypes.RunModes.LiveStream;
                }
                else
                {
                    PXCMCaptureManager cManager = SenseManager.QueryCaptureManager();
                    cManager.SetFileName(FilePath, true);
                    Debug.Log("SenseToolkitManager: Recording to file: " + FilePath);
                }
            }

            /* Enable modalities according to the set options*/
            if (IsSenseOptionSet(SenseOption.SenseOptionID.Face, true))
            {
                SenseManager.EnableFace();
                _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.Face).Initialized = true;
                _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.Face).Enabled     = true;
                SetSenseOption(SenseOption.SenseOptionID.VideoColorStream);
                numberOfEnabledModalities++;
            }

            if (IsSenseOptionSet(SenseOption.SenseOptionID.Hand, true))
            {
                _sts = SenseManager.EnableHand();
                _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.Hand).Initialized = true;
                _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.Hand).Enabled     = true;
                numberOfEnabledModalities++;
            }

            if (IsSenseOptionSet(SenseOption.SenseOptionID.Object, true))
            {
                _sts = SenseManager.EnableTracker();
                _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.Object).Initialized = true;
                _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.Object).Enabled     = true;
                numberOfEnabledModalities++;
            }

            if (IsSenseOptionSet(SenseOption.SenseOptionID.Speech, true))
            {
                if (!SpeechManager.IsInitialized)
                {
                    if (SpeechManager.InitalizeSpeech())
                    {
                        _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.Speech).Initialized = true;
                        _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.Speech).Enabled     = true;
                        numberOfEnabledModalities++;
                    }
                    else
                    {
                        UnsetSenseOption(SenseOption.SenseOptionID.Speech);
                    }
                }
                else
                {
                    _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.Speech).Initialized = true;
                    _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.Speech).Enabled     = true;
                    numberOfEnabledModalities++;
                }
            }

            if (IsSenseOptionSet(SenseOption.SenseOptionID.VideoDepthStream, true))
            {
                SenseManager.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_DEPTH, 0, 0, 0);
                _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.VideoDepthStream).Initialized = true;
                _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.VideoDepthStream).Enabled     = true;
                numberOfEnabledModalities++;
            }

            if (IsSenseOptionSet(SenseOption.SenseOptionID.VideoIRStream, true))
            {
                SenseManager.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_IR, 0, 0, 0);
                _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.VideoIRStream).Initialized = true;
                _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.VideoIRStream).Enabled     = true;
                numberOfEnabledModalities++;
            }

            if (IsSenseOptionSet(SenseOption.SenseOptionID.VideoColorStream, true))
            {
                //SenseManager.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_COLOR, 960, 540, 0);
                SenseManager.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_COLOR, 640, 480, 0);
                _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.VideoColorStream).Initialized = true;
                _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.VideoColorStream).Enabled     = true;
                numberOfEnabledModalities++;
            }


            /* Initialize the execution */
            _sts = SenseManager.Init();
            if (_sts < pxcmStatus.PXCM_STATUS_NO_ERROR)
            {
                if (numberOfEnabledModalities > 0)
                {
                    print("Unable to initialize all modalities");
                }
                return;
            }
            //Set different configurations:

            //SenseManager.QueryCaptureManager().device.SetMirrorMode(PXCMCapture.Device.MirrorMode.MIRROR_MODE_DISABLED);

            // Face
            if (IsSenseOptionSet(SenseOption.SenseOptionID.Face, true))
            {
                var faceModule        = SenseManager.QueryFace();
                var faceConfiguration = faceModule.CreateActiveConfiguration();
                if (faceConfiguration == null)
                {
                    throw new UnityException("CreateActiveConfiguration returned null");
                }

                faceConfiguration.Update();

                faceConfiguration.detection.isEnabled      = true;
                faceConfiguration.detection.smoothingLevel = PXCMFaceConfiguration.SmoothingLevelType.SMOOTHING_DISABLED;

                faceConfiguration.landmarks.isEnabled      = true;
                faceConfiguration.landmarks.smoothingLevel = PXCMFaceConfiguration.SmoothingLevelType.SMOOTHING_DISABLED;

                faceConfiguration.pose.isEnabled      = true;
                faceConfiguration.pose.smoothingLevel = PXCMFaceConfiguration.SmoothingLevelType.SMOOTHING_DISABLED;

                faceConfiguration.DisableAllAlerts();

                faceConfiguration.strategy = PXCMFaceConfiguration.TrackingStrategyType.STRATEGY_APPEARANCE_TIME;

                faceConfiguration.detection.maxTrackedFaces = NumberOfDetectedFaces;
                faceConfiguration.landmarks.maxTrackedFaces = NumberOfDetectedFaces;
                faceConfiguration.pose.maxTrackedFaces      = NumberOfDetectedFaces;

                PXCMFaceConfiguration.ExpressionsConfiguration expressionConfig = faceConfiguration.QueryExpressions();
                expressionConfig.Enable();
                expressionConfig.EnableAllExpressions();


                faceConfiguration.ApplyChanges();
                faceConfiguration.Dispose();

                FaceModuleOutput = faceModule.CreateOutput();

                UnsetSenseOption(SenseOption.SenseOptionID.VideoColorStream);
            }

            // Hand
            if (IsSenseOptionSet(SenseOption.SenseOptionID.Hand, true))
            {
                PXCMHandModule handAnalysis = SenseManager.QueryHand();

                PXCMHandConfiguration handConfiguration = handAnalysis.CreateActiveConfiguration();
                if (handConfiguration == null)
                {
                    throw new UnityException("CreateActiveConfiguration returned null");
                }

                handConfiguration.Update();
                handConfiguration.EnableAllGestures();
                handConfiguration.EnableAllAlerts();
                handConfiguration.EnableSegmentationImage(true);
                handConfiguration.ApplyChanges();
                handConfiguration.Dispose();

                HandDataOutput = handAnalysis.CreateOutput();
            }

            if (IsSenseOptionSet(SenseOption.SenseOptionID.Object, true))
            {
                if (_senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.Object).Enabled != true)
                {
                    _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.Object).Enabled = true;
                    OnDisable();
                    OnEnable();
                    Start();
                }
            }

            if (IsSenseOptionSet(SenseOption.SenseOptionID.Speech, true))
            {
                UpdateSpeechCommands();
                SpeechManager.Start();
            }

            // Create an instance for the projection
            if (_projection == null)
            {
                _projection = SenseManager.QueryCaptureManager().QueryDevice().CreateProjection();
            }

            // Set initialization flag
            Initialized = true;
        }
Пример #20
0
        private void ProcessingThread()
        {
            // Start AcquireFrame/ReleaseFrame loop
            while (senseManager.AcquireFrame(true).IsSuccessful())
            {
                PXCMCapture.Sample sample = senseManager.QuerySample();

                #region face
                // Retrieve gesture data
                face = senseManager.QueryFace();

                if (face != null)
                {
                    // Retrieve the most recent processed data
                    faceData = face.CreateOutput();
                    faceData.Update();

                    if (faceData.QueryNumberOfDetectedFaces() > 0)
                    {
                        var face = faceData.QueryFaceByIndex(0);
                        var pose = face.QueryPose();

                        if (pose != null)
                        {
                            PXCMFaceData.PoseEulerAngles angles;
                            pose.QueryPoseAngles(out angles);

                            if (angles != null)
                            {
                                double correctedYaw = (angles.yaw + 20) / 40;

                                correctedYaw = correctedYaw < 1 ? correctedYaw : 1;
                                correctedYaw = correctedYaw > 0 ? correctedYaw : 0;

                                correctedYaw = Math.Round(correctedYaw, 2);
                                correctedYaw = correctedYaw - correctedYaw % .02;

                                double correctedPitch = (-angles.pitch - 9) / 8;

                                correctedPitch = correctedPitch < 1 ? correctedPitch : 1;
                                correctedPitch = correctedPitch > 0 ? correctedPitch : 0;

                                correctedPitch = Math.Round(correctedPitch, 2);
                                correctedPitch = correctedPitch - correctedPitch % .02;

                                Nullable <PXCMPointF32> point = new PXCMPointF32();

                                Dispatcher.Invoke(() =>
                                {
                                    double maxX    = App.Current.MainWindow.RenderSize.Width;
                                    float currentX = Convert.ToSingle(maxX * correctedYaw);

                                    double maxY    = App.Current.MainWindow.RenderSize.Height;
                                    float currentY = Convert.ToSingle(maxY * correctedPitch);

                                    point = new PXCMPointF32(currentX, currentY);
                                });

                                point = smoother2D.SmoothValue(point.Value);
                                point = smoother2D2.SmoothValue(point.Value);

                                SetCursorPosition(Convert.ToInt32(point.Value.x), Convert.ToInt32(point.Value.y));
                            }
                        }

                        var expressions = face.QueryExpressions();

                        if (expressions != null)
                        {
                            PXCMFaceData.ExpressionsData.FaceExpressionResult result;
                            expressions.QueryExpression(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_MOUTH_OPEN, out result);

                            if (result != null && result.intensity > 35)
                            {
                                Click();
                            }
                        }
                    }
                }
                #endregion

                #region hand
                hand = senseManager.QueryHand();

                if (hand != null)
                {
                    using (var handData = hand.CreateOutput())
                    {
                        handData.Update();

                        var handCount = handData.QueryNumberOfHands();

                        for (int i = 0; i < handCount; i++)
                        {
                            PXCMHandData.IHand handInfo;
                            handData.QueryHandData(PXCMHandData.AccessOrderType.ACCESS_ORDER_RIGHT_HANDS, i, out handInfo);

                            if (handInfo != null && handInfo.HasTrackedJoints())
                            {
                                if (handInfo.QueryBodySide() == PXCMHandData.BodySideType.BODY_SIDE_RIGHT)
                                {
                                    PXCMHandData.FingerData finger;
                                    handInfo.QueryFingerData(PXCMHandData.FingerType.FINGER_INDEX, out finger);

                                    Nullable <PXCMPointF32> mouseLocation = null;

                                    if (finger.foldedness > 85)
                                    {
                                        PXCMHandData.JointData joint;
                                        handInfo.QueryTrackedJoint(PXCMHandData.JointType.JOINT_INDEX_TIP, out joint);

                                        double appX = 0;
                                        double appY = 0;

                                        Dispatcher.Invoke(() =>
                                        {
                                            appX = App.Current.MainWindow.RenderSize.Width;
                                            appY = App.Current.MainWindow.RenderSize.Height;
                                        });

                                        var xScaled = (joint.positionImage.x - 580) * -1 * (appX / 640) * 1.2;
                                        var yScaled = (joint.positionImage.y - 60) * (appY / 480) * 1.6;

                                        mouseLocation = smoother2D.SmoothValue(new PXCMPointF32(Convert.ToSingle(xScaled), Convert.ToSingle(yScaled)));

                                        SetCursorPosition(Convert.ToInt32(mouseLocation.Value.x), Convert.ToInt32(mouseLocation.Value.y));
                                    }

                                    handInfo.QueryFingerData(PXCMHandData.FingerType.FINGER_PINKY, out finger);

                                    if (finger.foldedness > 85)
                                    {
                                        if (DateTime.Now - lastClick > new TimeSpan(0, 0, 2))
                                        {
                                            Click();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                #endregion

                // Update the user interface
                //UpdateUI(colorBitmap);

                // Release the frame
                if (faceData != null)
                {
                    faceData.Dispose();
                }

                senseManager.ReleaseFrame();
            }
        }
Пример #21
0
        // Update is called once per frame
        void Update()
        {
            if (session == null)
            {
                return;
            }

            // For accessing hand data
            handAnalyzer = session.QueryHand();
            faceAnalyzer = session.QueryFace();


            if (handAnalyzer != null)
            {
                PXCMHandData handData = handAnalyzer.CreateOutput();
                if (handData != null)
                {
                    handData.Update();

                    PXCMHandData.IHand IHAND; // Ihand instance for accessing future data
                    //   Int32 IhandData; // for QueryOpenness Value
                    //    PXCMPoint3DF32 location; // Stores hand tracking position

                    //Fills IHAND with information to later be grabbed and used for tracking + openness
                    handData.QueryHandData(PXCMHandData.AccessOrderType.ACCESS_ORDER_NEAR_TO_FAR, 0, out IHAND);


                    // If there is data in Ihand
                    if (IHAND != null)
                    {
                        // Debug.DrawLine(transform.position, hit.point, Color.red);


                        // Inits hand tracking from the center of the hand.
                        //        location = IHAND.QueryMassCenterWorld();
                        //      if (mCurrentDart != null)
                        //    {
                        //      Vector3 locationUnity = new Vector3(location.x, location.y, location.z);
                        //      mCurrentDart.transform.localPosition = locationUnity * RSScale;
                        // }
                    }
                }
                handAnalyzer.Dispose();
                session.ReleaseFrame();
            }


            if (faceAnalyzer != null)
            {
                PXCMFaceData facedata = faceAnalyzer.CreateOutput();
                if (facedata != null)
                {
                    Int32 nfaces = facedata.QueryNumberOfDetectedFaces();
                    for (Int32 i = 0; i < nfaces; i++)
                    {
                        // Retrieve the face landmark data instance

                        PXCMFaceData.Face face = facedata.QueryFaceByIndex(i);

                        PXCMFaceData.PoseData pdata = face.QueryPose();



                        // retrieve the pose information

                        PXCMFaceData.PoseEulerAngles angles;

                        pdata.QueryPoseAngles(out angles);
                        Debug.Log("Eular Angles yaw : " + angles.yaw);
                        Debug.Log("Eular Angles pitch: " + angles.pitch);
                        Debug.Log("Eular Angles Roll: " + angles.roll);
                        angles.pitch = gameObject.transform.rotation.z;
                        angles.yaw   = gameObject.transform.rotation.y;
                    }

                    // device is a PXCMCapture.Device instance
                }
            }
        }
Пример #22
0
    // Update is called once per frame
    void Update()
    {
        /* Make sure SenseManager Instance is valid */
        if (sm == null)
        {
            return;
        }

        /* Wait until any frame data is available */
        if (sm.AcquireFrame(false) != pxcmStatus.PXCM_STATUS_NO_ERROR)
        {
            return;
        }

        /* Retrieve hand tracking Module Instance */
        handAnalyzer = sm.QueryHand();

        if (handAnalyzer != null)
        {
            /* Retrieve hand tracking Data */
            PXCMHandData _handData = handAnalyzer.CreateOutput();
            if (_handData != null)
            {
                _handData.Update();

                /* Retrieve Gesture Data to manipulate GUIText */
                PXCMHandData.GestureData gestureData;
                for (int i = 0; i < _handData.QueryFiredGesturesNumber(); i++)
                {
                    if (_handData.QueryFiredGestureData(i, out gestureData) == pxcmStatus.PXCM_STATUS_NO_ERROR)
                    {
                        DisplayGestures(gestureData);
                    }
                }


                /* Retrieve Alert Data to manipulate GUIText */
                PXCMHandData.AlertData alertData;
                for (int i = 0; i < _handData.QueryFiredAlertsNumber(); i++)
                {
                    if (_handData.QueryFiredAlertData(i, out alertData) == pxcmStatus.PXCM_STATUS_NO_ERROR)
                    {
                        ProcessAlerts(alertData);
                    }
                }

                /* Retrieve all joint Data */
                for (int i = 0; i < _handData.QueryNumberOfHands(); i++)
                {
                    PXCMHandData.IHand _iHand;
                    if (_handData.QueryHandData(PXCMHandData.AccessOrderType.ACCESS_ORDER_FIXED, i, out _iHand) == pxcmStatus.PXCM_STATUS_NO_ERROR)
                    {
                        for (int j = 0; j < MaxJoints; j++)
                        {
                            if (_iHand.QueryTrackedJoint((PXCMHandData.JointType)j, out jointData[i][j]) != pxcmStatus.PXCM_STATUS_NO_ERROR)
                            {
                                jointData[i][j] = null;
                            }
                        }
                        if (!handList.ContainsKey(_iHand.QueryUniqueId()))
                        {
                            handList.Add(_iHand.QueryUniqueId(), _iHand.QueryBodySide());
                        }
                    }
                }

                /* Smoothen and Display the Data - Joints and Bones*/
                DisplayJoints();
            }
            handAnalyzer.Dispose();
        }


        sm.ReleaseFrame();

        RotateCam();
    }
Пример #23
0
        private void ProcessingThread()
        {
            // Start AcquireFrame/ReleaseFrame loop - MAIN PROCESSING LOOP
            while (senseManager.AcquireFrame(true) >= pxcmStatus.PXCM_STATUS_NO_ERROR)
            {
                if (firstFrame == true)
                {
                    firstFrame = false;
                    //pipeClient.SendMessage(CAMERA_CONNECTED_MESSAGE);
                }

                //Get sample from the sensemanager to convert to bitmap and show
                PXCMCapture.Sample sample = senseManager.QuerySample();
                Bitmap colorBitmap;
                PXCMImage.ImageData colorData = null;

                // Get color/ir image data
                if (cameraMode == "Color")
                    sample.color.AcquireAccess(PXCMImage.Access.ACCESS_READ, PXCMImage.PixelFormat.PIXEL_FORMAT_RGB24, out colorData);
                else if (cameraMode == "IR")
                    sample.ir.AcquireAccess(PXCMImage.Access.ACCESS_READ, PXCMImage.PixelFormat.PIXEL_FORMAT_RGB24, out colorData);
                else if (cameraMode == "Depth")
                    ;// -> broken! // sample.depth.AcquireAccess(PXCMImage.Access.ACCESS_READ, PXCMImage.PixelFormat.PIXEL_FORMAT_DEPTH, out colorData);
                else
                    sample.color.AcquireAccess(PXCMImage.Access.ACCESS_READ, PXCMImage.PixelFormat.PIXEL_FORMAT_RGB24, out colorData);

                //convert it to bitmap
                colorBitmap = colorData.ToBitmap(0, sample.color.info.width, sample.color.info.height);

                // Retrieve hand and face data AND EMOTION DATA
                hand = senseManager.QueryHand();
                face = senseManager.QueryFace();
                emotion = senseManager.QueryEmotion();

                //Process hand data
                if (hand != null)
                {
                    // Retrieve the most recent processed data
                    handData = hand.CreateOutput();
                    handData.Update();
                    handWaving = handData.IsGestureFired("wave", out gestureData);
                }

                //Process face data
                if (face != null)
                {
                    // Retrieve the most recent processed data
                    faceData = face.CreateOutput();
                    faceData.Update();
                    numFacesDetected = faceData.QueryNumberOfDetectedFaces();
                    if (numFacesDetected > 0)
                    {
                        // for (Int32 i = 0; i < numFacesDetected; i++) --> MULTIPLE FACE DETECTION DISABLED, UNCOMMENT TO INCLUDE
                        // {
                        // PXCMFaceData.Face singleFace = faceData.QueryFaceByIndex(i); --> FOR MULTIPLE FACE DETECTION

                        //get all possible data from frame
                        PXCMFaceData.Face singleFaceData = faceData.QueryFaceByIndex(0); //only getting first face!
                        PXCMFaceData.ExpressionsData singleExprData = singleFaceData.QueryExpressions();
                        PXCMFaceData.DetectionData detectionData = singleFaceData.QueryDetection();
                        PXCMFaceData.LandmarksData landmarksData = singleFaceData.QueryLandmarks();
                        PXCMFaceData.PoseData poseData = singleFaceData.QueryPose();

                        //Work on face location data from detectionData
                        if (detectionData != null)
                        {
                            // vars are defined globally
                            detectionData.QueryBoundingRect(out boundingRect);
                            detectionData.QueryFaceAverageDepth(out averageDepth);
                        }

                        //Work on getting landmark data
                        if (landmarksData != null)
                        {
                            //var is defined globally
                            landmarksData.QueryPoints(out landmarkPoints);
                        }

                        //Work on getting euler angles for face pose data
                        if (poseData != null)
                        {

                            //var is defined globally
                            poseData.QueryPoseAngles(out eulerAngles);
                            poseData.QueryPoseQuaternion(out quaternionAngles);

                        }

                        //Do work on all face location data from singleExprData
                        if (singleExprData != null)
                        {
                            //get scores and intensities for right and left eye closing - 22 possible expressions --> put into hashtable
                            PXCMFaceData.ExpressionsData.FaceExpressionResult score;

                            //this gets a list of enum names as strings
                            var enumNames = Enum.GetNames(typeof(PXCMFaceData.ExpressionsData.FaceExpression));
                            //for all enumnames, calculate the
                            for (int j = 0; j < enumNames.Length; j++)
                            {
                                PXCMFaceData.ExpressionsData.FaceExpressionResult innerScore;
                                singleExprData.QueryExpression((PXCMFaceData.ExpressionsData.FaceExpression)(j), out innerScore);

                                //Console.WriteLine((PXCMFaceData.ExpressionsData.FaceExpression)(j));
                                exprTable[enumNames[j]] = innerScore.intensity;

                            }

                            //Attempt to write to file if there are any significant events
                            /*   //check if everything is 0
                               bool significantEntry = false;
                               foreach (DictionaryEntry entry in exprTable)
                               {
                                   if (Convert.ToInt32(entry.Value.ToString()) != 0)
                                   {
                                       significantEntry = true;
                                       break;
                                   }

                               }
                               if (significantEntry) */
                            writeSignificantToFile(exprTable, boundingRect, averageDepth, landmarkPoints, eulerAngles, quaternionAngles);

                            singleExprData.QueryExpression(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_EYES_CLOSED_LEFT, out score);
                            lEyeClosedIntensity = score.intensity;

                            singleExprData.QueryExpression(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_EYES_CLOSED_RIGHT, out score);
                            rEyeClosedIntensity = score.intensity;

                            //eye closed logic -> will be reset in UI thread after some number of frames
                            if (lEyeClosedIntensity >= EYE_CLOSED_DETECT_THRESHOLD)
                                lEyeClosed = true;

                            if (rEyeClosedIntensity >= EYE_CLOSED_DETECT_THRESHOLD)
                                rEyeClosed = true;
                        }

                        // }
                    }

                }

                if (emotion != null)
                {
                    int numFaces = emotion.QueryNumFaces();
                    for (int fid = 0; fid < numFaces; fid++)
                    {
                        //TODO - MULTIPLE FACE IMPLEMENTATION?
                        //retrieve all est data
                        PXCMEmotion.EmotionData[] arrData = new PXCMEmotion.EmotionData[10];
                        emotion.QueryAllEmotionData(fid, out arrData);

                        //find emotion with maximum evidence
                        int idx_outstanding_emotion = 0;
                        int max_evidence = arrData[0].evidence;
                        for (int k = 1; k < 7; k++)
                        {
                            if (arrData[k].evidence < max_evidence)
                            {

                            }
                            else
                            {
                                max_evidence = arrData[k].evidence;
                                idx_outstanding_emotion = k;
                            }

                        }

                        currentEmotion = arrData[idx_outstanding_emotion].eid;
                        //Console.WriteLine(currentEmotion.ToString());
                        emotionEvidence = max_evidence;

                       // Console.WriteLine(currentEmotion.ToString() + ":" + emotionEvidence.ToString());

                    }
                }

                // Update the user interface
                UpdateUI(colorBitmap);

                // Release the frame
                if (handData != null) handData.Dispose();
               // colorBitmap.Dispose();
                sample.color.ReleaseAccess(colorData);
                senseManager.ReleaseFrame();

            }
        }
Пример #24
0
        void OnEnable()
        {
            Initialized = false;

            /* Create a SenseManager instance */
            SenseManager = PXCMSenseManager.CreateInstance();

            if (SenseManager == null)
            {
                print("Unable to create the pipeline instance");
                return;
            }

            if (_speechCommandsRef.Count != 0)
            {
                SetSenseOption(SenseOption.SenseOptionID.Speech);
            }

            int numberOfEnabledModalities = 0;

            //Set mode according to RunMode - play from file / record / live stream
            if (RunMode == MCTTypes.RunModes.PlayFromFile)
            {
                //CHECK IF FILE EXISTS
                if (!System.IO.File.Exists(FilePath))
                {
                    Debug.LogWarning("No Filepath Set Or File Doesn't Exist, Run Mode Will Be Changed to Live Stream");
                    RunMode = MCTTypes.RunModes.LiveStream;
                }
                else
                {
                    PXCMCaptureManager cManager = SenseManager.QueryCaptureManager();
                    cManager.SetFileName(FilePath, false);
                    Debug.Log("SenseToolkitManager: Playing from file: " + FilePath);
                }
            }

            if (RunMode == MCTTypes.RunModes.RecordToFile)
            {
                //CHECK IF PATH
                string PathOnly = FilePath;
                while (!PathOnly[PathOnly.Length - 1].Equals('\\'))
                {
                    PathOnly = PathOnly.Remove(PathOnly.Length - 1, 1);
                }

                if (!System.IO.Directory.Exists(PathOnly))
                {
                    Debug.LogWarning("No Filepath Set Or Path Doesn't Exist, Run Mode Will Be Changed to Live Stream");
                    RunMode = MCTTypes.RunModes.LiveStream;
                }
                else
                {
                    PXCMCaptureManager cManager = SenseManager.QueryCaptureManager();
                    cManager.SetFileName(FilePath, true);
                    Debug.Log("SenseToolkitManager: Recording to file: " + FilePath);
                }
            }

            /* Enable modalities according to the set options*/
            if (IsSenseOptionSet(SenseOption.SenseOptionID.Face, true))
            {
                SenseManager.EnableFace();
                _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.Face).Initialized = true;
                _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.Face).Enabled     = true;
                SetSenseOption(SenseOption.SenseOptionID.VideoColorStream);
                numberOfEnabledModalities++;
            }

            if (IsSenseOptionSet(SenseOption.SenseOptionID.Hand, true))
            {
                _sts = SenseManager.EnableHand();
                _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.Hand).Initialized = true;
                _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.Hand).Enabled     = true;
                numberOfEnabledModalities++;
            }

            if (IsSenseOptionSet(SenseOption.SenseOptionID.Blob, true))
            {
                _sts = SenseManager.EnableBlob();
                _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.Blob).Initialized = true;
                _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.Blob).Enabled     = true;
                numberOfEnabledModalities++;
            }

            if (IsSenseOptionSet(SenseOption.SenseOptionID.Object, true))
            {
                _sts = SenseManager.EnableTracker();
                _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.Object).Initialized = true;
                _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.Object).Enabled     = true;
                numberOfEnabledModalities++;
            }

            if (IsSenseOptionSet(SenseOption.SenseOptionID.Speech, true))
            {
                if (!SpeechManager.IsInitialized)
                {
                    if (SpeechManager.InitalizeSpeech())
                    {
                        _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.Speech).Initialized = true;
                        _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.Speech).Enabled     = true;
                        numberOfEnabledModalities++;
                    }
                    else
                    {
                        UnsetSenseOption(SenseOption.SenseOptionID.Speech);
                    }
                }
                else
                {
                    _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.Speech).Initialized = true;
                    _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.Speech).Enabled     = true;
                    numberOfEnabledModalities++;
                }
            }

            if (IsSenseOptionSet(SenseOption.SenseOptionID.VideoDepthStream, true) ||
                IsSenseOptionSet(SenseOption.SenseOptionID.PointCloud, true))
            {
                SenseManager.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_DEPTH, 0, 0, 0);
                _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.VideoDepthStream).Initialized = true;
                _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.VideoDepthStream).Enabled     = true;
                numberOfEnabledModalities++;
            }

            if (IsSenseOptionSet(SenseOption.SenseOptionID.VideoIRStream, true))
            {
                SenseManager.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_IR, 0, 0, 0);
                _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.VideoIRStream).Initialized = true;
                _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.VideoIRStream).Enabled     = true;
                numberOfEnabledModalities++;
            }

            if (IsSenseOptionSet(SenseOption.SenseOptionID.VideoColorStream, true))
            {
                if (ColorImageQuality == MCTTypes.RGBQuality.FullHD)
                {
                    SenseManager.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_COLOR, 1920, 1080, 0);
                }
                else if (ColorImageQuality == MCTTypes.RGBQuality.HD)
                {
                    SenseManager.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_COLOR, 1280, 720, 0);
                }
                else if (ColorImageQuality == MCTTypes.RGBQuality.HalfHD)
                {
                    SenseManager.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_COLOR, 960, 540, 0);
                }
                else
                {
                    SenseManager.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_COLOR, 640, 480, 0);
                }
                _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.VideoColorStream).Initialized = true;
                _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.VideoColorStream).Enabled     = true;
                numberOfEnabledModalities++;
            }

            if (IsSenseOptionSet(SenseOption.SenseOptionID.VideoSegmentation, true))
            {
                if (ColorImageQuality == MCTTypes.RGBQuality.FullHD)
                {
                    SenseManager.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_COLOR, 1920, 1080, 0);
                }
                else if (ColorImageQuality == MCTTypes.RGBQuality.HD)
                {
                    SenseManager.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_COLOR, 1280, 720, 0);
                }
                else if (ColorImageQuality == MCTTypes.RGBQuality.HalfHD)
                {
                    SenseManager.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_COLOR, 960, 540, 0);
                }
                else
                {
                    SenseManager.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_COLOR, 640, 480, 0);
                }
                SenseManager.Enable3DSeg();
                _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.VideoSegmentation).Initialized = true;
                _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.VideoSegmentation).Enabled     = true;
                numberOfEnabledModalities++;
            }

            /* Initialize the execution */
            _sts = SenseManager.Init();
            if (_sts < pxcmStatus.PXCM_STATUS_NO_ERROR)
            {
                return;
            }

            //Set different configurations:

            // Face
            if (IsSenseOptionSet(SenseOption.SenseOptionID.Face, true))
            {
                var faceModule = SenseManager.QueryFace();
                if (faceModule == null)
                {
                    throw new UnityException("QueryFace returned null");
                }

                var faceConfiguration = faceModule.CreateActiveConfiguration();
                if (faceConfiguration == null)
                {
                    throw new UnityException("CreateActiveConfiguration returned null");
                }

                faceConfiguration.Update();

                faceConfiguration.detection.isEnabled      = true;
                faceConfiguration.detection.smoothingLevel = PXCMFaceConfiguration.SmoothingLevelType.SMOOTHING_DISABLED;

                faceConfiguration.landmarks.isEnabled      = true;
                faceConfiguration.landmarks.smoothingLevel = PXCMFaceConfiguration.SmoothingLevelType.SMOOTHING_DISABLED;

                faceConfiguration.pose.isEnabled      = true;
                faceConfiguration.pose.smoothingLevel = PXCMFaceConfiguration.SmoothingLevelType.SMOOTHING_DISABLED;

                faceConfiguration.DisableAllAlerts();

                faceConfiguration.strategy = PXCMFaceConfiguration.TrackingStrategyType.STRATEGY_APPEARANCE_TIME;

                if ((NumberOfDetectedFaces < 1) || (NumberOfDetectedFaces > 15))
                {
                    Debug.Log("Ilegal value for Number Of Detected Faces, value is set to 1");
                    NumberOfDetectedFaces = 1;
                }

                faceConfiguration.detection.maxTrackedFaces = NumberOfDetectedFaces;
                faceConfiguration.landmarks.maxTrackedFaces = NumberOfDetectedFaces;
                faceConfiguration.pose.maxTrackedFaces      = NumberOfDetectedFaces;

                PXCMFaceConfiguration.ExpressionsConfiguration expressionConfig = faceConfiguration.QueryExpressions();
                if (expressionConfig == null)
                {
                    throw new UnityException("QueryExpressions returned null");
                }

                expressionConfig.Enable();
                expressionConfig.EnableAllExpressions();


                faceConfiguration.ApplyChanges();
                faceConfiguration.Dispose();

                FaceModuleOutput = faceModule.CreateOutput();

                UnsetSenseOption(SenseOption.SenseOptionID.VideoColorStream);
            }

            // Hand
            if (IsSenseOptionSet(SenseOption.SenseOptionID.Hand, true))
            {
                PXCMHandModule handAnalysis = SenseManager.QueryHand();
                if (handAnalysis == null)
                {
                    throw new UnityException("QueryHand returned null");
                }

                PXCMHandConfiguration handConfiguration = handAnalysis.CreateActiveConfiguration();
                if (handConfiguration == null)
                {
                    throw new UnityException("CreateActiveConfiguration returned null");
                }

                handConfiguration.Update();
                handConfiguration.EnableAllGestures();
                handConfiguration.EnableStabilizer(true);
                handConfiguration.DisableAllAlerts();
                handConfiguration.EnableSegmentationImage(false);
                handConfiguration.ApplyChanges();
                handConfiguration.Dispose();

                HandDataOutput = handAnalysis.CreateOutput();
            }

            // Blob
            if (IsSenseOptionSet(SenseOption.SenseOptionID.Blob, true))
            {
                PXCMBlobModule blobAnalysis = SenseManager.QueryBlob();
                if (blobAnalysis == null)
                {
                    throw new UnityException("QueryBlob returned null");
                }

                PXCMBlobConfiguration blobConfiguration = blobAnalysis.CreateActiveConfiguration();
                if (blobConfiguration == null)
                {
                    throw new UnityException("CreateActiveConfiguration returned null");
                }

                blobConfiguration.Update();
                blobConfiguration.EnableContourExtraction(true);
                blobConfiguration.EnableSegmentationImage(true);
                blobConfiguration.EnableStabilizer(true);
                blobConfiguration.SetMaxDistance(50 * 10);
                blobConfiguration.ApplyChanges();
                blobConfiguration.Dispose();

                BlobDataOutput = blobAnalysis.CreateOutput();
            }

            if (IsSenseOptionSet(SenseOption.SenseOptionID.Object, true))
            {
                if (_senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.Object).Enabled != true)
                {
                    _senseOptions.Find(i => i.ID == SenseOption.SenseOptionID.Object).Enabled = true;
                    OnDisable();
                    OnEnable();
                }
            }

            if (IsSenseOptionSet(SenseOption.SenseOptionID.Speech, true))
            {
                UpdateSpeechCommands();
                SpeechManager.Start();
            }

            // Create an instance for the projection & blob extractor

            if (Projection == null)
            {
                Projection = SenseManager.QueryCaptureManager().QueryDevice().CreateProjection();
            }

            /* GZ
             *          if (BlobExtractor == null)
             *          {
             *                  SenseManager.session.CreateImpl<PXCMBlobExtractor>(out BlobExtractor);
             *          }*/

            // Set initialization flag
            Initialized = true;
        }
Пример #25
0
        pxcmStatus newHandFrame(PXCMHandModule hand)
        {
            if (hand != null)
            {
                PXCMHandData handData = hand.CreateOutput();
                handData.Update();

                PXCMHandData.IHand     iHandDataLeft = null, iHandDataRight = null;
                PXCMHandData.JointData jointData = null;
                PXCMImage image = null;

                handData.QueryHandData(PXCMHandData.AccessOrderType.ACCESS_ORDER_LEFT_HANDS, 0, out iHandDataLeft);
                handData.QueryHandData(PXCMHandData.AccessOrderType.ACCESS_ORDER_RIGHT_HANDS, 0, out iHandDataRight);
                if (handForm != null && !handForm.IsDisposed)
                {
                    this.handForm.HandCount = handData.QueryNumberOfHands();
                    if (iHandDataLeft != null)
                    {
                        iHandDataLeft.QuerySegmentationImage(out image);
                        if (image != null)
                        {
                            PXCMImage.ImageData data = new PXCMImage.ImageData();
                            image.AcquireAccess(PXCMImage.Access.ACCESS_READ, PXCMImage.PixelFormat.PIXEL_FORMAT_RGB32, out data);
                            handForm.LeftHand = data.ToBitmap(0, image.info.width, image.info.height);
                            image.ReleaseAccess(data);
                        }
                    }
                    if (iHandDataRight != null)
                    {
                        iHandDataRight.QuerySegmentationImage(out image);
                        if (image != null)
                        {
                            PXCMImage.ImageData data = new PXCMImage.ImageData();
                            image.AcquireAccess(PXCMImage.Access.ACCESS_READ, PXCMImage.PixelFormat.PIXEL_FORMAT_RGB32, out data);
                            handForm.RightHand = data.ToBitmap(0, image.info.width, image.info.height);
                            image.ReleaseAccess(data);
                        }
                    }
                }
                if (iHandDataLeft != null)
                {
                    if (jointData == null)
                    {
                        iHandDataLeft.QueryTrackedJoint(PXCMHandData.JointType.JOINT_INDEX_TIP, out jointData);
                    }
                }
                if (iHandDataRight != null)
                {
                    if (jointData == null)
                    {
                        iHandDataRight.QueryTrackedJoint(PXCMHandData.JointType.JOINT_INDEX_TIP, out jointData);
                    }
                }
                if (jointData != null && canTrack.Checked)
                {
                    Cursor.Position = new System.Drawing.Point(
                        (int)((640.0f - jointData.positionImage.x) * Screen.PrimaryScreen.Bounds.Width / 640.0f),
                        (int)(jointData.positionImage.y * Screen.PrimaryScreen.Bounds.Height / 480.0f));
                    PXCMHandData.GestureData gestureData = null;
                    if (handData.IsGestureFired("two_fingers_pinch_open", out gestureData))
                    {
                        Program.DoMouseClick();
                    }
                    Console.WriteLine("Z Position: " + jointData.positionWorld.z);
                }

                handData.Dispose();
            }
            return(pxcmStatus.PXCM_STATUS_NO_ERROR);
        }
Пример #26
0
        public HandsRecognition(int mod)
        {
			try
			{
				session = PXCMSession.CreateInstance();
				mode = mod;
				if (mod == 0)
				{
					rightcp = new checkPiano();
					leftcp = new checkPiano();
				}
				else if (mod == 1)
				{
					rightcp = new checkDrum();
					leftcp = new checkDrum();
				}

				_disconnected = false;

				instance = session.CreateSenseManager();
				if (instance == null)
				{
					MessageBox.Show("Failed creating SenseManager", "OnAlert");
					return;
				}

				/* Set Module */
				pxcmStatus status = instance.EnableHand();//form.GetCheckedModule());
				handAnalysis = instance.QueryHand();

				if (status != pxcmStatus.PXCM_STATUS_NO_ERROR || handAnalysis == null)
				{
					MessageBox.Show("Failed Loading Module", "OnAlert");
					return;
				}

				handler = new PXCMSenseManager.Handler();
				handler.onModuleProcessedFrame = new PXCMSenseManager.Handler.OnModuleProcessedFrameDelegate(OnNewFrame);

				handData = handAnalysis.CreateOutput();
			}
			catch
			{
				MessageBox.Show("Init Failed.");
				Environment.Exit(0);
			}
        }
Пример #27
0
        public void InitializeGestureRecognition(List<String> gestures = null)
        {
            manager.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_DEPTH, 640, 480, 30);
            var s = manager.EnableHand();

            this.handAnalyzer = manager.QueryHand();

            var re = manager.Init();

            this.outputData = handAnalyzer.CreateOutput();
            this.config = handAnalyzer.CreateActiveConfiguration();

            if (gestures == null)
                this.config.EnableAllGestures();

            else
                foreach (var g in gestures) this.config.EnableGesture(g);

            this.config.ApplyChanges();

            if (re != pxcmStatus.PXCM_STATUS_NO_ERROR)
                throw new RealSenseException("error: " + re, re);

            this.isGestureRecognitionEnabled = true;
        }
Пример #28
0
        // Update is called once per frame
        void Update()
        {
            if (session == null)
                return;

            // For accessing hand data
            handAnalyzer = session.QueryHand();
            faceAnalyzer = session.QueryFace();

            if (handAnalyzer != null)
            {
                PXCMHandData handData = handAnalyzer.CreateOutput();
                if (handData != null)
                {
                    handData.Update();

                    PXCMHandData.IHand IHAND; // Ihand instance for accessing future data
                 //   Int32 IhandData; // for QueryOpenness Value
                //    PXCMPoint3DF32 location; // Stores hand tracking position

                    //Fills IHAND with information to later be grabbed and used for tracking + openness
                    handData.QueryHandData(PXCMHandData.AccessOrderType.ACCESS_ORDER_NEAR_TO_FAR, 0, out IHAND);

                    // If there is data in Ihand
                    if (IHAND != null)
                    {

                        // Debug.DrawLine(transform.position, hit.point, Color.red);

                        // Inits hand tracking from the center of the hand.
                //        location = IHAND.QueryMassCenterWorld();
                  //      if (mCurrentDart != null)
                    //    {
                      //      Vector3 locationUnity = new Vector3(location.x, location.y, location.z);
                      //      mCurrentDart.transform.localPosition = locationUnity * RSScale;
                       // }

                    }

                }
                handAnalyzer.Dispose();
                session.ReleaseFrame();

            }

            if (faceAnalyzer != null)
            {

                PXCMFaceData facedata = faceAnalyzer.CreateOutput();
                if (facedata != null)
                {
                    Int32 nfaces = facedata.QueryNumberOfDetectedFaces();
                    for (Int32 i = 0; i < nfaces; i++)
                    {

                        // Retrieve the face landmark data instance

                        PXCMFaceData.Face face = facedata.QueryFaceByIndex(i);

                        PXCMFaceData.PoseData pdata = face.QueryPose();

                        // retrieve the pose information

                        PXCMFaceData.PoseEulerAngles angles;

                        pdata.QueryPoseAngles(out angles);
                        Debug.Log("Eular Angles yaw : " + angles.yaw);
                        Debug.Log("Eular Angles pitch: " + angles.pitch);
                        Debug.Log("Eular Angles Roll: " + angles.roll);
                        angles.pitch = gameObject.transform.rotation.z;
                        angles.yaw = gameObject.transform.rotation.y;

                    }

                    // device is a PXCMCapture.Device instance

                }
            }
        }
    // Update is called once per frame
    void Update()
    {
        /* Make sure SenseManager Instance is valid */
        if (sm == null)
            return;

        /* Wait until any frame data is available */
        if (sm.AcquireFrame (false) != pxcmStatus.PXCM_STATUS_NO_ERROR)
            return;

        /* Retrieve hand tracking Module Instance */
        handAnalyzer = sm.QueryHand ();

        if (handAnalyzer != null) {
            /* Retrieve hand tracking Data */
            PXCMHandData _handData = handAnalyzer.CreateOutput ();
            if (_handData != null) {
                _handData.Update ();

                /* Retrieve Gesture Data to manipulate GUIText */
                PXCMHandData.GestureData gestureData;
                for (int i = 0; i < _handData.QueryFiredGesturesNumber(); i++)
                    if (_handData.QueryFiredGestureData (i, out gestureData) == pxcmStatus.PXCM_STATUS_NO_ERROR)
                        DisplayGestures (gestureData);

                /* Retrieve Alert Data to manipulate GUIText */
                PXCMHandData.AlertData alertData;
                for (int i=0; i<_handData.QueryFiredAlertsNumber(); i++)
                    if (_handData.QueryFiredAlertData (i, out alertData) == pxcmStatus.PXCM_STATUS_NO_ERROR)
                        ProcessAlerts (alertData);

                /* Retrieve all joint Data */
                for (int i = 0; i < _handData.QueryNumberOfHands (); i++) {
                    PXCMHandData.IHand _iHand;
                    if (_handData.QueryHandData (PXCMHandData.AccessOrderType.ACCESS_ORDER_FIXED, i, out _iHand) == pxcmStatus.PXCM_STATUS_NO_ERROR) {
                        for (int j = 0; j < MaxJoints; j++) {
                            if (_iHand.QueryTrackedJoint ((PXCMHandData.JointType)j, out jointData [i] [j]) != pxcmStatus.PXCM_STATUS_NO_ERROR)
                                jointData [i] [j] = null;
                        }
                        if (!handList.ContainsKey (_iHand.QueryUniqueId ()))
                            handList.Add (_iHand.QueryUniqueId (), _iHand.QueryBodySide ());
                    }
                }

                /* Smoothen and Display the Data - Joints and Bones*/
                DisplayJoints ();

            }
            _handData.Dispose ();
        }

        handAnalyzer.Dispose ();

        sm.ReleaseFrame ();

        RotateCam ();
    }
Пример #30
0
        /* Using PXCMSenseManager to handle data */
        public void SimplePipeline()
        {
            form.UpdateInfo(String.Empty, Color.Black);
            bool liveCamera = false;

            bool             flag     = true;
            PXCMSenseManager instance = null;

            _disconnected = false;
            instance      = form.g_session.CreateSenseManager();
            if (instance == null)
            {
                form.UpdateStatus("Failed creating SenseManager");
                return;
            }

            if (form.GetRecordState())
            {
                instance.captureManager.SetFileName(form.GetFileName(), true);
                PXCMCapture.DeviceInfo info;
                if (form.Devices.TryGetValue(form.GetCheckedDevice(), out info))
                {
                    instance.captureManager.FilterByDeviceInfo(info);
                }
            }
            else if (form.GetPlaybackState())
            {
                instance.captureManager.SetFileName(form.GetFileName(), false);
                instance.captureManager.SetRealtime(false);
            }
            else
            {
                PXCMCapture.DeviceInfo info;
                if (String.IsNullOrEmpty(form.GetCheckedDevice()))
                {
                    form.UpdateStatus("Device Failure");
                    return;
                }

                if (form.Devices.TryGetValue(form.GetCheckedDevice(), out info))
                {
                    instance.captureManager.FilterByDeviceInfo(info);
                }

                liveCamera = true;
            }
            /* Set Module */
            pxcmStatus     status       = instance.EnableHand(form.GetCheckedModule());
            PXCMHandModule handAnalysis = instance.QueryHand();

            if (status != pxcmStatus.PXCM_STATUS_NO_ERROR || handAnalysis == null)
            {
                form.UpdateStatus("Failed Loading Module");
                return;
            }

            PXCMSenseManager.Handler handler = new PXCMSenseManager.Handler();
            handler.onModuleProcessedFrame = new PXCMSenseManager.Handler.OnModuleProcessedFrameDelegate(OnNewFrame);


            PXCMHandConfiguration handConfiguration = handAnalysis.CreateActiveConfiguration();
            PXCMHandData          handData          = handAnalysis.CreateOutput();

            if (handConfiguration == null)
            {
                form.UpdateStatus("Failed Create Configuration");
                return;
            }
            if (handData == null)
            {
                form.UpdateStatus("Failed Create Output");
                return;
            }

            if (form.getInitGesturesFirstTime() == false)
            {
                int totalNumOfGestures = handConfiguration.QueryGesturesTotalNumber();
                if (totalNumOfGestures > 0)
                {
                    this.form.UpdateGesturesToList("", 0);
                    for (int i = 0; i < totalNumOfGestures; i++)
                    {
                        string gestureName = string.Empty;
                        if (handConfiguration.QueryGestureNameByIndex(i, out gestureName) ==
                            pxcmStatus.PXCM_STATUS_NO_ERROR)
                        {
                            this.form.UpdateGesturesToList(gestureName, i + 1);
                        }
                    }
                    form.setInitGesturesFirstTime(true);
                    form.UpdateGesturesListSize();
                }
            }


            FPSTimer timer = new FPSTimer(form);

            form.UpdateStatus("Init Started");
            if (handAnalysis != null && instance.Init(handler) == pxcmStatus.PXCM_STATUS_NO_ERROR)
            {
                PXCMCapture.DeviceInfo dinfo;

                PXCMCapture.Device device = instance.captureManager.device;
                if (device != null)
                {
                    pxcmStatus result = device.QueryDeviceInfo(out dinfo);
                    if (result == pxcmStatus.PXCM_STATUS_NO_ERROR && dinfo != null && dinfo.model == PXCMCapture.DeviceModel.DEVICE_MODEL_IVCAM)
                    {
                        device.SetDepthConfidenceThreshold(1);
                        device.SetMirrorMode(PXCMCapture.Device.MirrorMode.MIRROR_MODE_DISABLED);
                        device.SetIVCAMFilterOption(6);
                    }

                    _maxRange = device.QueryDepthSensorRange().max;
                }


                if (handConfiguration != null)
                {
                    handConfiguration.EnableAllAlerts();
                    handConfiguration.EnableSegmentationImage(true);

                    handConfiguration.ApplyChanges();
                    handConfiguration.Update();
                }

                form.UpdateStatus("Streaming");
                int    frameCounter = 0;
                int    frameNumber = 0;
                string nextPageGesture, previousPageGesture, firstPageGesture, endPageGesture;
                HandsRecognition.Hand nextHand, previousHand, firstHand, endHand;

                while (!form.stop)
                {
                    form.GetHandType(out nextHand, out previousHand, out firstHand, out endHand);
                    form.GetGestureName(out nextPageGesture, out previousPageGesture, out firstPageGesture, out endPageGesture);
                    handConfiguration.DisableAllGestures();
                    if (string.IsNullOrEmpty(nextPageGesture) == false && handConfiguration.IsGestureEnabled(nextPageGesture) == false)
                    {
                        handConfiguration.EnableGesture(nextPageGesture, true);
                        NextPageGesture.Gesture  = nextPageGesture;
                        NextPageGesture.handler  = form.NextPage;
                        NextPageGesture.HandType = nextHand;
                    }
                    if (string.IsNullOrEmpty(previousPageGesture) == false && handConfiguration.IsGestureEnabled(previousPageGesture) == false)
                    {
                        handConfiguration.EnableGesture(previousPageGesture, true);
                        PreviousPageGesture.Gesture  = previousPageGesture;
                        PreviousPageGesture.handler  = form.PreviousPage;
                        PreviousPageGesture.HandType = previousHand;
                    }
                    if (string.IsNullOrEmpty(firstPageGesture) == false && handConfiguration.IsGestureEnabled(firstPageGesture) == false)
                    {
                        handConfiguration.EnableGesture(firstPageGesture, true);
                        FirstPageGesture.Gesture  = firstPageGesture;
                        FirstPageGesture.handler  = form.FirstPage;
                        FirstPageGesture.HandType = firstHand;
                    }
                    if (string.IsNullOrEmpty(endPageGesture) == false && handConfiguration.IsGestureEnabled(endPageGesture) == false)
                    {
                        handConfiguration.EnableGesture(endPageGesture, true);
                        EndPageGesture.Gesture  = endPageGesture;
                        EndPageGesture.handler  = form.EndPage;
                        EndPageGesture.HandType = endHand;
                    }
                    handConfiguration.ApplyChanges();
                    if (instance.AcquireFrame(true) < pxcmStatus.PXCM_STATUS_NO_ERROR)
                    {
                        break;
                    }

                    frameCounter++;

                    if (!DisplayDeviceConnection(!instance.IsConnected()))
                    {
                        if (handData != null)
                        {
                            handData.Update();
                        }

                        PXCMCapture.Sample sample = instance.QueryHandSample();
                        if (sample != null && sample.depth != null)
                        {
                            DisplayPicture(sample.depth, handData);

                            if (handData != null)
                            {
                                frameNumber = liveCamera ? frameCounter : instance.captureManager.QueryFrameIndex();

                                DisplayJoints(handData);
                                DisplayGesture(handData, frameNumber);
                                DisplayAlerts(handData, frameNumber);
                            }
                            form.UpdatePanel();
                        }
                        timer.Tick();
                    }
                    instance.ReleaseFrame();
                }

                // Clean Up
                if (handData != null)
                {
                    handData.Dispose();
                }
                if (handConfiguration != null)
                {
                    handConfiguration.Dispose();
                }
            }
            else
            {
                form.UpdateStatus("Init Failed");
                flag = false;
            }
            foreach (PXCMImage pxcmImage in m_images)
            {
                pxcmImage.Dispose();
            }



            instance.Close();
            instance.Dispose();
            if (flag)
            {
                form.UpdateStatus("Stopped");
            }
        }
Пример #31
0
        public static void start(IoT_RealSense_Surfing frm)
        {
            keepLooping = true;
            iot_form    = frm;
            InitializeMqqtClient();
            PXCMSession session = PXCMSession.CreateInstance();

            // Querying the SDK version
            Console.WriteLine(frm.comboTarget.SelectedText);
            if (session != null)
            {
                // Optional steps to send feedback to Intel Corporation to understand how often each SDK sample is used.
                PXCMMetadata md = session.QueryInstance <PXCMMetadata>();
                if (md != null)
                {
                    string sample_name = "Emotion Viewer CS";
                    md.AttachBuffer(1297303632, System.Text.Encoding.Unicode.GetBytes(sample_name));
                }
                //Application.Run(new MainForm(session));
                //session.Dispose();
            }
            //PXCMSession.ImplVersion version = session.QueryVersion();
            //Console.WriteLine("RealSense SDK Version {0}.{1}", version.major, version.minor);

            session.CreateImpl <PXCMRotation>(out rotationHelper);

            // Creating the SenseManager
            PXCMSenseManager senseManager = session.CreateSenseManager();

            if (senseManager == null)
            {
                Console.WriteLine("Failed to create the SenseManager object.");
                return;
            }

            // Enabling Emotion Module
            pxcmStatus enablingModuleStatus = senseManager.EnableEmotion();

            if (enablingModuleStatus != pxcmStatus.PXCM_STATUS_NO_ERROR)
            {
                Console.WriteLine("Failed to enable the Emotion Module");
                return;
            }

            // Getting the instance of the Emotion Module
            PXCMEmotion emotionModule = senseManager.QueryEmotion();

            if (emotionModule == null)
            {
                Console.WriteLine("Failed to query the emotion module");
                return;
            }

            // Initializing the camera
            if (senseManager.Init() < pxcmStatus.PXCM_STATUS_NO_ERROR)
            {
                Console.WriteLine("Failed to initialize the SenseManager");
                return;
            }

            // Enabling the Hand module
            pxcmStatus enablingModuleStatus1 = senseManager.EnableHand("Hand Module");

            if (enablingModuleStatus1 != pxcmStatus.PXCM_STATUS_NO_ERROR)
            {
                Console.WriteLine("Failed to enable the Hand Module");
                return;
            }

            // Getting the instance of the Hand Module
            PXCMHandModule handModule = senseManager.QueryHand();

            if (handModule == null)
            {
                Console.WriteLine("Failed to get the HandModule object.");
                return;
            }

            // Creating an active configuration
            PXCMHandConfiguration handConfiguration = handModule.CreateActiveConfiguration();

            if (handConfiguration == null)
            {
                Console.WriteLine("Failed to create the HandConfiguration object.");
                return;
            }

            // Listing the available gestures
            int supportedGesturesCount = handConfiguration.QueryGesturesTotalNumber();

            if (supportedGesturesCount > 0)
            {
                Console.WriteLine("Supported gestures:");
                for (int i = 0; i < supportedGesturesCount; i++)
                {
                    string gestureName = string.Empty;

                    if (handConfiguration.QueryGestureNameByIndex(i, out gestureName) == pxcmStatus.PXCM_STATUS_NO_ERROR)
                    {
                        Console.WriteLine("\t" + gestureName);
                    }
                }
            }

            // Enabling some gestures
            String[] enabledGestures = { GESTURE_CLICK, GESTURE_VSIGN, GESTURE_FIST, GESTURE_SPREADFINGERS };
            foreach (String gesture in enabledGestures)
            {
                if (!handConfiguration.IsGestureEnabled(gesture))
                {
                    handConfiguration.EnableGesture(gesture);
                }
            }
            handConfiguration.ApplyChanges();

            // Creating a data output object
            PXCMHandData handData = handModule.CreateOutput();

            if (handData == null)
            {
                Console.WriteLine("Failed to create the HandData object.");
                return;
            }

            // Initializing the SenseManager
            if (senseManager.Init() != pxcmStatus.PXCM_STATUS_NO_ERROR)
            {
                Console.WriteLine(senseManager.Init());
                return;
            }

            // Looping to query the hands information
            while (keepLooping)
            {
                // Acquiring a frame
                if (senseManager.AcquireFrame(true) < pxcmStatus.PXCM_STATUS_NO_ERROR)
                {
                    break;
                }

                // Updating the hand data
                if (handData != null)
                {
                    handData.Update();
                }
                //ProcessHands(handData);
                ProcessGestures(handData);
                ProcessEmotions(emotionModule);
                // Releasing the acquired frame
                senseManager.ReleaseFrame();

                /* using another frame to process different stuff? may be...
                 * // Acquiring a frame
                 * if (senseManager.AcquireFrame(true) < pxcmStatus.PXCM_STATUS_NO_ERROR)
                 * {
                 *  break;
                 * }
                 *
                 * // Processing Emotions
                 * ProcessEmotions(emotionModule);
                 *
                 * // Releasing the acquired frame
                 * senseManager.ReleaseFrame();*/
            }


            // Releasing resources
            if (handData != null)
            {
                handData.Dispose();
            }
            if (handConfiguration != null)
            {
                handConfiguration.Dispose();
            }
            rotationHelper.Dispose();

            senseManager.Close();
            senseManager.Dispose();
            session.Dispose();
            client.Disconnect();
        }
Пример #32
0
    //Called every frame when in manual mode
    private void UpdateFreeMovementState()
    {

        if (!manualEnabled)
            return;

        if (gesture.Equals("fist"))
        {
            GetComponent<Rigidbody>().AddForce(1 * transform.forward * forceMultiplier);
        }
        else if (gesture.Equals("v_sign"))
        {
            GetComponent<Rigidbody>().AddTorque(-1 * transform.up * forceMultiplier * rotateFactor);
            gesture = "";
        }
        else if (gesture.Equals("thumb_down"))
        {
            GetComponent<Rigidbody>().AddTorque(1 * transform.up * forceMultiplier * rotateFactor);
            gesture = "";
        }


        /* Retrieve hand tracking Module Instance */
        handAnalyzer = sm.QueryHand();

        /* Retrieve hand tracking Data */
        PXCMHandData _handData = handAnalyzer.CreateOutput();

        if (_handData != null)
        {
            _handData.Update();
        }

        handAnalyzer.Dispose();
        sm.ReleaseFrame();

    }
        // 手の検出の初期化
        private void InitializeHandTracking()
        {
            // 手の検出器を取得する
            handAnalyzer = senseManager.QueryHand();
            if ( handAnalyzer == null ) {
                throw new Exception( "手の検出器の取得に失敗しました" );
            }

            // 手のデータを作成する
            handData = handAnalyzer.CreateOutput();
            if ( handData == null ) {
                throw new Exception( "手の検出器の作成に失敗しました" );
            }

            // RealSense カメラであれば、プロパティを設定する
            var device = senseManager.QueryCaptureManager().QueryDevice();
            PXCMCapture.DeviceInfo dinfo;
            device.QueryDeviceInfo( out dinfo );
            if ( dinfo.model == PXCMCapture.DeviceModel.DEVICE_MODEL_IVCAM ) {
                device.SetDepthConfidenceThreshold( 1 );
                //device.SetMirrorMode( PXCMCapture.Device.MirrorMode.MIRROR_MODE_DISABLED );
                device.SetIVCAMFilterOption( 6 );
            }

            // 手の検出の設定
            handConfig = handAnalyzer.CreateActiveConfiguration();

            // 登録されているジェスチャーを列挙する
            var num = handConfig.QueryGesturesTotalNumber();
            for ( int i = 0; i < num; i++ ){
                string gestureName;
                var sts = handConfig.QueryGestureNameByIndex( i, out gestureName );
                if ( sts == pxcmStatus.PXCM_STATUS_NO_ERROR ){
                    ComboGesture.Items.Add( gestureName  );
                }
            }

            handConfig.ApplyChanges();
            handConfig.Update();
        }