Пример #1
0
        private void Start_btn_Click(object sender, EventArgs e)
        {
            // Set fixed form size
            pictureBox1.MinimumSize = pictureBox1.MaximumSize = new Size(mode.XRes, mode.YRes);
            //this.MinimumSize = this.MaximumSize = new Size(mode.XRes, mode.YRes);

            // Disable unnecessary caption bar buttons
            //this.MinimizeBox = this.MaximizeBox = false;

            // Enable double buffering to prevent flicker
            this.DoubleBuffered = true;
            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);

            // Run Nuitrack. This starts sensor data processing.
            if (!isStart)
            {
                try
                {
                    Nuitrack.Run();
                    isStart        = true;
                    State_txt.Text = "Run";
                }
                catch (System.Exception exception)
                {
                    Console.WriteLine("Cannot start Nuitrack.");
                    throw exception;
                }
            }
            else
            {
                Pause          = false;
                State_txt.Text = "Run";
                pictureBox1.Refresh();
            }
        }
Пример #2
0
    void OnSkeletonUpdate(SkeletonData skeletonData)
    {
        string json = Nuitrack.GetInstancesJson();

        faceInfo = JsonUtility.FromJson <FaceInfo>(json.Replace("\"\"", "[]"));

        if (faceInfo.Instances.Length == 0)
        {
            return;
        }

        for (int i = 0; i < faceAnimControllers.Count; i++)
        {
            if (i < skeletonData.Skeletons.Length)
            {
                Skeleton skeleton = skeletonData.GetSkeletonByID(faceInfo.Instances[i].id);
                if (skeleton != null)
                {
                    nuitrack.Joint headJoint = skeleton.GetJoint(JointType.Head);

                    faceAnimControllers[i].gameObject.SetActive(headJoint.Confidence > 0.5f);
                    faceAnimControllers[i].UpdateFace(faceInfo.Instances[i], headJoint);
                }
            }
            else
            {
                faceAnimControllers[i].gameObject.SetActive(false);
            }
        }
    }
Пример #3
0
        public Form1()
        {
            try
            {
                Nuitrack.Init("");
            }
            catch (System.Exception exception)
            {
                Console.WriteLine("Cannot initialize Nuitrack.");
                throw exception;
            }

            try
            {
                // Create and setup all required modules
                _depthSensor     = DepthSensor.Create();
                _colorSensor     = ColorSensor.Create();
                _userTracker     = UserTracker.Create();
                _skeletonTracker = SkeletonTracker.Create();
            }
            catch (System.Exception exception)
            {
                Console.WriteLine("Cannot create Nuitrack module.");
                throw exception;
            }

            _depthSensor.SetMirror(false);

            // Add event handlers for all modules
            _depthSensor.OnUpdateEvent             += onDepthSensorUpdate;
            _colorSensor.OnUpdateEvent             += onColorSensorUpdate;
            _userTracker.OnUpdateEvent             += onUserTrackerUpdate;
            _skeletonTracker.OnSkeletonUpdateEvent += onSkeletonUpdate;

            Nuitrack.onIssueUpdateEvent += onIssueDataUpdate;

            mode      = _depthSensor.GetOutputMode();
            colorMode = _colorSensor.GetOutputMode();

            if (mode.XRes < colorMode.XRes)
            {
                mode.XRes = colorMode.XRes;
            }
            if (mode.YRes < colorMode.YRes)
            {
                mode.YRes = colorMode.YRes;
            }

            _bitmap = new DirectBitmap(mode.XRes, mode.YRes);
            for (int y = 0; y < mode.YRes; ++y)
            {
                for (int x = 0; x < mode.XRes; ++x)
                {
                    _bitmap.SetPixel(x, y, Color.FromKnownColor(KnownColor.Aqua));
                }
            }

            InitializeComponent();
        }
Пример #4
0
    // Use this for initialization
    void Start()
    {
        Nuitrack.Init();

        depthSensor = DepthSensor.Create();
        depthSensor.OnUpdateEvent += DepthSensor_OnUpdateEvent;

        skeletonTracker = SkeletonTracker.Create();
        skeletonTracker.OnSkeletonUpdateEvent += SkeletonTracker_OnSkeletonUpdateEvent;

        Nuitrack.Run();
    }
Пример #5
0
        /// <summary>
        /// 手动拍照按钮 CQZ
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click_handleSnapXu(object sender, RoutedEventArgs e)
        {
            Console.WriteLine("点击手动拍照");
            //点击开始按钮时就时启动摄像头,此时没有自动计算并停止功能,点击手动抓拍进行拍照
            if (ShoulderWidth != 0 && ArmLengthUp != 0 && ArmLengthDown != 0 && LegLengthUp != 0 && LegLengthDown != 0)
            {
                Console.WriteLine("都不为0,开始计算");
                skeletonLength.Shoulder_width  = ShoulderWidth;
                skeletonLength.Arm_length_up   = ArmLengthUp;
                skeletonLength.Arm_length_down = ArmLengthDown;
                skeletonLength.Leg_length_up   = LegLengthUp;
                skeletonLength.Leg_length_down = LegLengthDown;
                //Console.WriteLine("肩宽mm" + skeletonLength.Shoulder_width);
                //Console.WriteLine("臂长(上)mm" + skeletonLength.Arm_length_up);
                //Console.WriteLine("臂长(下)mm" + skeletonLength.Arm_length_down);
                //Console.WriteLine("腿长(上)mm" + skeletonLength.Leg_length_up);
                //Console.WriteLine("腿长(下)mm" + skeletonLength.Leg_length_down);

                breakFlag = true;
                Thread.Sleep(100);

                //Console.WriteLine("开始渲染页面");

                this.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart) delegate()
                {
                    Console.WriteLine("Invoke内部");
                    Shoulder_width.Text  = (ShoulderWidth / 10).ToString("f2");
                    Arm_length_up.Text   = (ArmLengthUp / 10).ToString("f2");
                    Arm_length_down.Text = (ArmLengthDown / 10).ToString("f2");
                    Leg_length_up.Text   = (LegLengthUp / 10).ToString("f2");
                    Leg_length_down.Text = (LegLengthDown / 10).ToString("f2");
                    Body_length.Text     = (BodyLength / 10).ToString("f2");
                    Man_Height.Text      = (Height / 10).ToString("f2");
                });
                Nuitrack.onIssueUpdateEvent            -= onIssueDataUpdate;
                _depthSensor.OnUpdateEvent             -= onDepthSensorUpdate;
                _colorSensor.OnUpdateEvent             -= onColorSensorUpdate;
                _userTracker.OnUpdateEvent             -= onUserTrackerUpdate;
                _skeletonTracker.OnSkeletonUpdateEvent -= onSkeletonUpdate;
                //_handTracker.OnUpdateEvent -= onHandTrackerUpdate;
                _gestureRecognizer.OnNewGesturesEvent -= onNewGestures;
                Nuitrack.Release();

                Console.WriteLine("资源释放成功");
            }
            else
            {
                Nuitrack.Update(_skeletonTracker);
                Console.WriteLine("长度某个为0进行Update");
            }
        }
Пример #6
0
    private void OnApplicationQuit()
    {
        if (depthSensor != null)
        {
            depthSensor.OnUpdateEvent -= DepthSensor_OnUpdateEvent;
        }

        if (skeletonTracker != null)
        {
            skeletonTracker.OnSkeletonUpdateEvent -= SkeletonTracker_OnSkeletonUpdateEvent;
        }

        Nuitrack.Release();
    }
Пример #7
0
        /* Extract the datas when the Handlers are Updated then Send them via the Streamer */
        public void Step()
        {
            // We wait for the arrays to be populated
            try { Nuitrack.WaitUpdate(_skeletonTracker); }
            catch (LicenseNotAcquiredException exception) { Console.WriteLine("LicenseNotAcquired exception. Exception: {0}", exception.ToString()); }
            catch (System.Exception exception) { Console.WriteLine("Nuitrack update failed. Exception: {0}", exception.ToString()); }

            // We then format the datas in an array of bytes
            ExtractJoints();
            ExtractPixels();

            // Finaly we give the data to the Streamer
            _streamer.SendSkeleton(_pixels, _skeletonData.Timestamp);
            _streamer.SendPixels(_pixels, _skeletonData.Timestamp);
        }
Пример #8
0
        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            if (Pause)
            {
                return;
            }
            base.OnPaint(e);

            // Update Nuitrack data. Data will be synchronized with skeleton time stamps.
            try
            {
                Nuitrack.Update(_skeletonTracker);
            }
            catch (LicenseNotAcquiredException exception)
            {
                Console.WriteLine("LicenseNotAcquired exception. Exception: ", exception);
                throw exception;
            }
            catch (System.Exception exception)
            {
                Console.WriteLine("Nuitrack update failed. Exception: ", exception);
            }

            // Draw a bitmap
            pictureBox1.Image = _bitmap.Bitmap;
            //e.Graphics.DrawImage(_bitmap.Bitmap, new Point(0, 0));

            Graphics g1 = Graphics.FromHwnd(pictureBox1.Handle);

            // Draw skeleton joints
            if (_skeletonData != null)
            {
                const int jointSize = 10;
                foreach (var skeleton in _skeletonData.Skeletons)
                {
                    SolidBrush brush = new SolidBrush(Color.FromArgb(255 - 40 * skeleton.ID, 0, 0));
                    foreach (var joint in skeleton.Joints)
                    {
                        g1.FillEllipse(brush, joint.Proj.X * _bitmap.Width - jointSize / 2,
                                       joint.Proj.Y * _bitmap.Height - jointSize / 2, jointSize, jointSize);
                    }
                }
            }


            // Update Form
            this.Invalidate();
        }
Пример #9
0
 static public void Main()
 {
     Console.CancelKeyPress += delegate {
         Nuitrack.Release();
         GC.Collect();
         GC.WaitForPendingFinalizers();
     };
     try
     {
         Application.Run(new MainForm());
     }
     catch (Exception exception)
     {
         Console.WriteLine(exception.ToString());
     }
 }
Пример #10
0
        /* Initialize the Nuitrack Environment */
        private void Initialize()
        {
            try {
                Nuitrack.Init("");
            }
            catch (nuitrack.Exception exception) {
                Console.WriteLine("Cannot initialize Nuitrack.");
                throw exception;
            }
            // Select the device
            _device = SelectDevice();

            // Select video configurations
            _configVideo = SelectVideoMode();


            // Activate the license
            ActivateDevice();

            Nuitrack.SetDevice(_device);

            // Add modules Sensors
            _depthSensor     = DepthSensor.Create();
            _colorSensor     = ColorSensor.Create();
            _userTracker     = UserTracker.Create();
            _skeletonTracker = SkeletonTracker.Create();

            // Add modules Events Handlers
            _depthSensor.OnUpdateEvent             += onDepthSensorUpdate;
            _colorSensor.OnUpdateEvent             += onColorSensorUpdate;
            _userTracker.OnUpdateEvent             += onUserTrackerUpdate;
            _userTracker.OnNewUserEvent            += onUserTrackerNewUser;
            _userTracker.OnLostUserEvent           += onUserTrackerLostUser;
            _skeletonTracker.OnSkeletonUpdateEvent += onSkeletonUpdate;

            // Connect to remote
            _streamer = SelectStreamer();


            // Run Nuitrack
            Nuitrack.Run();
            _running = true;

            Console.WriteLine("Nuitrack is Running...");
        }
Пример #11
0
        /* Stop the Main Loop and Reset the Events Handlers */
        public void Stop()
        {
            try {
                // Remove all modules
                _depthSensor.OnUpdateEvent             -= onDepthSensorUpdate;
                _colorSensor.OnUpdateEvent             -= onColorSensorUpdate;
                _userTracker.OnUpdateEvent             -= onUserTrackerUpdate;
                _userTracker.OnNewUserEvent            -= onUserTrackerNewUser;
                _userTracker.OnLostUserEvent           -= onUserTrackerLostUser;
                _skeletonTracker.OnSkeletonUpdateEvent -= onSkeletonUpdate;

                // Release Nuitrack
                Nuitrack.Release();
            }
            catch (System.Exception exception) {
                Console.WriteLine("Nuitrack release failed.");
                throw exception;
            }
        }
Пример #12
0
        private void NuitrackInitButton_Click(object sender, RoutedEventArgs e)
        {
            //Nuitrack.Init();
            TextBlock.Text = "Nuitrack.Init Success";

            // Run Nuitrack. This starts sensor data processing.
            try
            {
                Nuitrack.Run();
            }
            catch (nuitrack.Exception exception)
            {
                Debug.WriteLine("Cannot start Nuitrack.");
                throw exception;
            }

            timer.Interval = new TimeSpan(0, 0, 0, 0, 10);
            timer.Tick    += new EventHandler(ProcessingThread);
            timer.Start();
        }
Пример #13
0
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            // Release Nuitrack and remove all modules
            try
            {
                Nuitrack.onIssueUpdateEvent -= onIssueDataUpdate;

                _depthSensor.OnUpdateEvent             -= onDepthSensorUpdate;
                _colorSensor.OnUpdateEvent             -= onColorSensorUpdate;
                _userTracker.OnUpdateEvent             -= onUserTrackerUpdate;
                _skeletonTracker.OnSkeletonUpdateEvent -= onSkeletonUpdate;

                Nuitrack.Release();
            }
            catch (System.Exception exception)
            {
                Console.WriteLine("Nuitrack release failed.");
                throw exception;
            }
        }
 static public void Main(string[] argv)
 {
     Console.CancelKeyPress += delegate
     {
         Nuitrack.Release();
         GC.Collect();
         GC.WaitForPendingFinalizers();
     };
     try
     {
         //if(args.Length < 2)
         //{
         // Application.Exit();
         //}
         Application.Run(new MainForm(argv[0], Convert.ToInt32(argv[1])));
     }
     catch (Exception exception)
     {
         Console.WriteLine(exception.ToString());
     }
 }
Пример #15
0
 /// <summary>
 /// 手动拍照按钮 CQZ
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void Button_Click_handleSnapXu(object sender, RoutedEventArgs e)
 {
     Console.WriteLine("点击手动拍照");
     //点击开始按钮时就时启动摄像头,此时没有自动计算并停止功能,点击手动抓拍进行拍照
     if (ShoulderWidth != 0 && ArmLengthUp != 0 && ArmLengthDown != 0 && LegLengthUp != 0 && LegLengthDown != 0)
     {
         Console.WriteLine("都不为0,开始计算");
         skeletonLength.Shoulder_width  = ShoulderWidth;
         skeletonLength.Arm_length_up   = ArmLengthUp;
         skeletonLength.Arm_length_down = ArmLengthDown;
         skeletonLength.Leg_length_up   = LegLengthUp;
         skeletonLength.Leg_length_down = LegLengthDown;
         Console.WriteLine("肩宽mm" + skeletonLength.Shoulder_width);
         Console.WriteLine("臂长(上)mm" + skeletonLength.Arm_length_up);
         Console.WriteLine("臂长(下)mm" + skeletonLength.Arm_length_down);
         Console.WriteLine("腿长(上)mm" + skeletonLength.Leg_length_up);
         Console.WriteLine("腿长(下)mm" + skeletonLength.Leg_length_down);
         this.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart) delegate()
         {
             Shoulder_width.Text  = (ShoulderWidth / 10).ToString("f2");
             Arm_length_up.Text   = (ArmLengthUp / 10).ToString("f2");
             Arm_length_down.Text = (ArmLengthDown / 10).ToString("f2");
             Leg_length_up.Text   = (LegLengthUp / 10).ToString("f2");
             Leg_length_down.Text = (LegLengthDown / 10).ToString("f2");
             Body_length.Text     = (BodyLength / 10).ToString("f2");
             Man_Height.Text      = (Height / 10).ToString("f2");
         });
         //先渲染再停止
         Thread.Sleep(100);
         Nuitrack.Release();
         breakFlag = true;
         Console.WriteLine("资源释放成功");
     }
     else
     {
         Nuitrack.Update(_skeletonTracker);
         Console.WriteLine("长度某个为0进行Update");
     }
 }
Пример #16
0
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            // Release Nuitrack and remove all modules
            try
            {
                Nuitrack.onIssueUpdateEvent -= onIssueDataUpdate;

                _depthSensor.OnUpdateEvent             -= onDepthSensorUpdate;
                _colorSensor.OnUpdateEvent             -= onColorSensorUpdate;
                _userTracker.OnUpdateEvent             -= onUserTrackerUpdate;
                _skeletonTracker.OnSkeletonUpdateEvent -= onSkeletonUpdate;
                _handTracker.OnUpdateEvent             -= onHandTrackerUpdate;
                _gestureRecognizer.OnNewGesturesEvent  -= onNewGestures;

                Nuitrack.Release();
            }
            catch (nuitrack.Exception exception)
            {
                Debug.WriteLine("Nuitrack release failed.");
                throw exception;
            }
        }
Пример #17
0
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            // Release Nuitrack and remove all modules
            try
            {
                Nuitrack.onIssueUpdateEvent -= onIssueDataUpdate;

                _depthSensor.OnUpdateEvent             -= onDepthSensorUpdate;
                _colorSensor.OnUpdateEvent             -= onColorSensorUpdate;
                _userTracker.OnUpdateEvent             -= onUserTrackerUpdate;
                _skeletonTracker.OnSkeletonUpdateEvent -= onSkeletonUpdate;
                _handTracker.OnUpdateEvent             -= onHandTrackerUpdate;
                _gestureRecognizer.OnNewGesturesEvent  -= onNewGestures;

                Nuitrack.Release();
            }
            catch (Exception exception)
            {
                Console.WriteLine("Nuitrack release failed.");
                throw exception;
            }
        }
Пример #18
0
        private void ProcessingThread(object sender, EventArgs e)
        {
            Thread.CurrentThread.Priority = ThreadPriority.Highest;
            // Update Nuitrack data. Data will be synchronized with skeleton time stamps.
            try
            {
                Nuitrack.Update(_skeletonTracker);//
            }
            catch (LicenseNotAcquiredException exception)
            {
                Debug.WriteLine("LicenseNotAcquired exception. Exception: ", exception);
                throw exception;
            }
            catch (nuitrack.Exception exception)
            {
                Debug.WriteLine("Nuitrack update failed. Exception: ", exception);
            }

            Dispatcher.Invoke(DispatcherPriority.Render, new TimeSpan(0, 0, 0, 0, 200), (Action)(() =>
            {
                // Visualize depth or color image
                if (_bitmap != null)
                {
                    imgView.Source = Utilities.BitmapToBitmapSource(_bitmap.Bitmap);
                }

                // Draw skeleton joints
                if (_skeletonData != null)
                {
                    canvas.Children.Clear();
                    foreach (var skeleton in _skeletonData.Skeletons)
                    {
                        canvas.DrawSkeleton(skeleton, _bitmap.Bitmap);
                    }
                }
            }));
        }
Пример #19
0
        public MainForm()
        {
            // Initialize Nuitrack. This should be called before using any Nuitrack module.
            // By passing the default arguments we specify that Nuitrack must determine
            // the location automatically.
            try
            {
                Nuitrack.Init("");
            }
            catch (Exception exception)
            {
                Console.WriteLine("Cannot initialize Nuitrack.");
                throw exception;
            }

            try
            {
                // Create and setup all required modules
                _depthSensor       = DepthSensor.Create();
                _colorSensor       = ColorSensor.Create();
                _userTracker       = UserTracker.Create();
                _skeletonTracker   = SkeletonTracker.Create();
                _handTracker       = HandTracker.Create();
                _gestureRecognizer = GestureRecognizer.Create();
            }
            catch (Exception exception)
            {
                Console.WriteLine("Cannot create Nuitrack module.");
                throw exception;
            }

            //_depthSensor.SetMirror(false);

            // Add event handlers for all modules
            _depthSensor.OnUpdateEvent             += onDepthSensorUpdate;
            _colorSensor.OnUpdateEvent             += onColorSensorUpdate;
            _userTracker.OnUpdateEvent             += onUserTrackerUpdate;
            _userTracker.OnNewUserEvent            += onUserTrackerNewUser;
            _userTracker.OnLostUserEvent           += onUserTrackerLostUser;
            _skeletonTracker.OnSkeletonUpdateEvent += onSkeletonUpdate;
            _handTracker.OnUpdateEvent             += onHandTrackerUpdate;
            _gestureRecognizer.OnNewGesturesEvent  += onNewGestures;

            // Add an event handler for the IssueUpdate event
            Nuitrack.onIssueUpdateEvent += onIssueDataUpdate;

            // Create and configure the Bitmap object according to the depth sensor output mode
            OutputMode mode      = _depthSensor.GetOutputMode();
            OutputMode colorMode = _colorSensor.GetOutputMode();

            if (mode.XRes < colorMode.XRes)
            {
                mode.XRes = colorMode.XRes;
            }
            if (mode.YRes < colorMode.YRes)
            {
                mode.YRes = colorMode.YRes;
            }

            _bitmap = new DirectBitmap(mode.XRes, mode.YRes);
            for (int y = 0; y < mode.YRes; ++y)
            {
                for (int x = 0; x < mode.XRes; ++x)
                {
                    _bitmap.SetPixel(x, y, Color.FromKnownColor(KnownColor.Aqua));
                }
            }

            // Set fixed form size
            this.MinimumSize = this.MaximumSize = new Size(mode.XRes, mode.YRes);

            // Disable unnecessary caption bar buttons
            this.MinimizeBox = this.MaximizeBox = false;

            // Enable double buffering to prevent flicker
            this.DoubleBuffered = true;

            // Run Nuitrack. This starts sensor data processing.
            try
            {
                Nuitrack.Run();
            }
            catch (Exception exception)
            {
                Console.WriteLine("Cannot start Nuitrack.");
                throw exception;
            }

            this.Show();
        }
Пример #20
0
        public MainWindow()
        {
            InitializeComponent();

            try
            {
                Nuitrack.Init();
            }
            catch (nuitrack.Exception exception)
            {
                Debug.WriteLine("Can not initialize Nuitrack. Exception: ", exception);
            }

            try
            {
                // Create and setup all required modules
                _depthSensor       = DepthSensor.Create();
                _colorSensor       = ColorSensor.Create();
                _userTracker       = UserTracker.Create();
                _skeletonTracker   = SkeletonTracker.Create();
                _handTracker       = HandTracker.Create();
                _gestureRecognizer = GestureRecognizer.Create();
            }
            catch (nuitrack.Exception exception)
            {
                Debug.WriteLine("Cannot create Nuitrack module.");
                throw exception;
            }

            // Add event handlers for all modules
            _depthSensor.OnUpdateEvent             += onDepthSensorUpdate;
            _colorSensor.OnUpdateEvent             += onColorSensorUpdate;
            _userTracker.OnUpdateEvent             += onUserTrackerUpdate;
            _skeletonTracker.OnSkeletonUpdateEvent += onSkeletonUpdate;
            _handTracker.OnUpdateEvent             += onHandTrackerUpdate;
            _gestureRecognizer.OnNewGesturesEvent  += onNewGestures;

            // Add an event handler for the IssueUpdate event
            Nuitrack.onIssueUpdateEvent += onIssueDataUpdate;

            // Create and configure the Bitmap object according to the depth sensor output mode
            OutputMode mode      = _depthSensor.GetOutputMode();
            OutputMode colorMode = _colorSensor.GetOutputMode();

            if (mode.XRes < colorMode.XRes)
            {
                mode.XRes = colorMode.XRes;
            }
            if (mode.YRes < colorMode.YRes)
            {
                mode.YRes = colorMode.YRes;
            }
            _bitmap = new DirectBitmap(mode.XRes, mode.YRes);

            for (int y = 0; y < mode.YRes; ++y)
            {
                for (int x = 0; x < mode.XRes; ++x)
                {
                    _bitmap.SetPixel(x, y, System.Drawing.Color.FromKnownColor(KnownColor.Aqua));
                }
            }
        }
Пример #21
0
 // Update is called once per frame
 void Update()
 {
     Nuitrack.Update();
 }
Пример #22
0
        //开始扫描按钮点击事件
        private void DealWith()
        {
            try
            {
                // Console.WriteLine("Update");
                Nuitrack.Update(_skeletonTracker);
            }
            catch (LicenseNotAcquiredException exception)
            {
                // Console.WriteLine("LicenseNotAcquired exception. Exception: ", exception);
                App.Current.Dispatcher.Invoke((Action)(() =>
                {
                    MessageBoxX.Error("免费许可证单次开启时常为三分钟,请点击开始重新初始化");
                    Nuitrack.Release();
                    this.Restart();
                }));
                return;
            }
            catch (nuitrack.Exception exception)
            {
                // Console.WriteLine("Nuitrack update failed. Exception: ", exception);
                App.Current.Dispatcher.Invoke((Action)(() =>
                {
                    MessageBoxX.Error("3D摄像头内部异常,请点击开始重新初始化。");
                    Nuitrack.Release();
                    this.Restart();
                }));
                return;
            }

            // Draw skeleton joints
            //CQZ:检测骨架关节数据,骨骼数组不为空开始,里边while循环判断骨骼数组里如果为空,就调用API更新骨骼数据,线程sleep 0.1秒再循环检测
            //骨骼关节数据不为空后开始进行图像渲染,各个关节的计算初始化等操作。
            try
            {
                while (!breakFlag)
                {    //_skeletonData.Skeletons[0].Joints表示关节   _skeletonData.Skeletons.Length > 0 是指人
                     // 每次update都可能导致_skeletonData变为null
                    if (null != _skeletonData && _skeletonData.Skeletons.Length > 0)
                    {
                        if (_skeletonData.Skeletons[0].Joints.Length > 0)
                        {
                            // Console.WriteLine("外层循环");
                            // CQZ:一直以来罪魁祸首崩溃异常的大坑!数组越界bug修改!!!!不应该是i < [].length  应该是 i < [].length-1
                            // XJH:为啥是length-1
                            for (int i = 0; i < _skeletonData.Skeletons[0].Joints.Length - 1; i++)
                            {
                                Skeleton skeleton = _skeletonData.Skeletons[0];

                                this.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart) delegate()
                                {
                                    //描点
                                    // Console.WriteLine("图像渲染前" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
                                    DrawingVisual drawingVisual      = new DrawingVisual();
                                    DrawingContext drawingContext    = drawingVisual.RenderOpen();
                                    System.Windows.Media.Brush brush = new SolidColorBrush(System.Windows.Media.Color.FromRgb(255, 0, 0));
                                    foreach (var joint in skeleton.Joints)
                                    {
                                        drawingContext.DrawEllipse(brush, new System.Windows.Media.Pen(), new System.Windows.Point((joint.Proj.X * _bitmap.Width - 10 / 2) - 53, (joint.Proj.Y * _bitmap.Height - 10 / 2) - 70), 5, 5);
                                    }
                                    drawingContext.Close();
                                    RenderTargetBitmap bmp = new RenderTargetBitmap(640, 480, 120, 120, PixelFormats.Pbgra32);
                                    bmp.Render(drawingVisual);
                                    // 将骨骼点渲染到屏幕上
                                    statusImage1.Source = bmp;
                                    // Console.WriteLine("图像渲染后" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
                                });
                                //Console.WriteLine("类型" + i + " " + skeleton.Joints[i].Type.ToString());
                                if (skeleton.Joints[i].Type.ToString() == "Head")
                                {
                                    Head = skeleton.Joints[i];
                                    // Console.WriteLine("头部位置坐标" + i + "||" + Head.Real.X + "||" + Head.Real.Y + "||" + Head.Real.Z);
                                }
                                if (skeleton.Joints[i].Type.ToString() == "LeftCollar")
                                {
                                    Collar = skeleton.Joints[i];
                                    // Console.WriteLine("衣领位置坐标" + i + "||" + Collar.Real.X + "||" + Collar.Real.Y + "||" + Collar.Real.Z);
                                }
                                if (skeleton.Joints[i].Type.ToString() == "LeftShoulder")
                                {
                                    LeftShoulder = skeleton.Joints[i];
                                    // Console.WriteLine("左肩关节坐标" + i + "||" + LeftShoulder.Real.X + "||" + LeftShoulder.Real.Y + "||" + LeftShoulder.Real.Z);
                                }
                                if (skeleton.Joints[i].Type.ToString() == "LeftWrist")
                                {
                                    LeftWrist = skeleton.Joints[i];
                                    //Console.WriteLine("左手手腕关节坐标" + i + "||" + LeftWrist.Real.X + "||" + LeftWrist.Real.Y + "||" + LeftWrist.Real.Z);
                                }
                                if (skeleton.Joints[i].Type.ToString() == "LeftHip")
                                {
                                    LeftHip = skeleton.Joints[i];
                                    // Console.WriteLine("左大腿关节坐标" + i + "||" + LeftHip.Real.X + "||" + LeftHip.Real.Y + "||" + LeftHip.Real.Z);
                                }
                                if (skeleton.Joints[i].Type.ToString() == "LeftAnkle")
                                {
                                    LeftAnkle = skeleton.Joints[i];
                                    // Console.WriteLine("左脚踝坐标" + i + "||" + LeftAnkle.Real.X + "||" + LeftAnkle.Real.Y + "||" + LeftAnkle.Real.Z);
                                }
                                if (skeleton.Joints[i].Type.ToString() == "LeftElbow")
                                {
                                    LeftElbow = skeleton.Joints[i];
                                    // Console.WriteLine("左胳膊肘坐标" + i + "||" + LeftElbow.Real.X + "||" + LeftElbow.Real.Y + "||" + LeftElbow.Real.Z);
                                }
                                if (skeleton.Joints[i].Type.ToString() == "LeftKnee")
                                {
                                    LeftKnee = skeleton.Joints[i];
                                    //Console.WriteLine("左膝盖坐标" + i + "||" + LeftKnee.Real.X + "||" + LeftKnee.Real.Y + "||" + LeftKnee.Real.Z);
                                }
                                if (skeleton.Joints[i].Type.ToString() == "Waist")
                                {
                                    Waist = skeleton.Joints[i];
                                    //Console.WriteLine("腰部坐标" + i + "||" + Waist.Real.X + "||" + Waist.Real.Y + "||" + Waist.Real.Z);
                                }
                                //因为手动抓拍功能 改为全局变量 CQZ
                                //计算距离
                                NeckLength    = ComputeDistanceBetween2Joints(Head, Collar);
                                ShoulderWidth = ComputeDistanceBetween2Joints(LeftShoulder, Collar);
                                ArmLengthUp   = ComputeDistanceBetween2Joints(LeftShoulder, LeftElbow);
                                ArmLengthDown = ComputeDistanceBetween2Joints(LeftElbow, LeftWrist);
                                LegLengthUp   = ComputeDistanceBetween2Joints(LeftHip, LeftKnee);
                                LegLengthDown = ComputeDistanceBetween2Joints(LeftKnee, LeftAnkle);
                                BodyLength    = ComputeDistanceBetween2Joints(Collar, Waist);
                                //获取权重
                                string initWeight = ConfigUtil.Get("initWeight");
                                //CQZ:身高计算:各个骨骼相加再补常量 常量请根据测试情况调节
                                Height = LegLengthUp + LegLengthDown + BodyLength + NeckLength + Double.Parse(initWeight);
                            }
                            //更新,直到点击手动拍照按钮。
                            try
                            {
                                Nuitrack.Update(_skeletonTracker);
                            }
                            catch (LicenseNotAcquiredException exception)
                            { // Console.WriteLine("LicenseNotAcquired exception. Exception: ", exception);
                                App.Current.Dispatcher.Invoke((Action)(() =>
                                {
                                    MessageBoxX.Error("免费许可证单次开启时常为三分钟,请点击开始重新初始化");
                                    Nuitrack.Release();
                                    this.Restart();
                                }));
                                return;
                            }
                            if (breakFlag)
                            {
                                // Console.WriteLine("breakFlag--if--true");
                                return;
                            }
                        }
                        else
                        {
                            try
                            {
                                this.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart) delegate()
                                {
                                    statusImage1.Source = null;
                                });
                                Nuitrack.Update(_skeletonTracker);
                                //Console.WriteLine("未捕获到关节");
                            }
                            catch (LicenseNotAcquiredException exception)
                            { // Console.WriteLine("LicenseNotAcquired exception. Exception: ", exception);
                                App.Current.Dispatcher.Invoke((Action)(() =>
                                {
                                    MessageBoxX.Error("免费许可证单次开启时常为三分钟,请点击开始重新初始化");
                                    Nuitrack.Release();
                                    this.Restart();
                                }));
                                return;
                            }
                        }
                    }
                    else
                    {
                        try
                        {
                            this.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart) delegate()
                            {
                                statusImage1.Source = null;
                            });
                            Nuitrack.Update(_skeletonTracker);
                            //Console.WriteLine("没有检测到人,进行Update");
                        }
                        catch (LicenseNotAcquiredException exception)
                        { // Console.WriteLine("LicenseNotAcquired exception. Exception: ", exception);
                            App.Current.Dispatcher.Invoke((Action)(() =>
                            {
                                MessageBoxX.Error("免费许可证单次开启时常为三分钟,请点击开始重新初始化");
                                Nuitrack.Release();
                                this.Restart();
                            }));
                            return;
                        }
                    }
                }
                // Console.WriteLine("break为false,循环结束");
                // 点击拍照按钮时,跳出最外层循环让线程结束。
                return;
            }
            catch (IndexOutOfRangeException)
            {
                //扫描过程中距离过远,或者是转圈,导致人体不识别,  _skeletonData.Skeletons[0].Joints.Length > 0越界
                // Console.WriteLine("3D扫描数组越界。");
                App.Current.Dispatcher.Invoke((Action)(() =>
                {
                    MessageBoxX.Error("距离太远了,请点击开始重新扫描。");
                    Nuitrack.Release();
                    this.Restart();
                }));
                return;
            }
        }
Пример #23
0
        /// <summary>
        ///3D扫描的构造函数 -byCQZ 2019.6.16
        ///
        /// </summary>
        private void NuitrackCreate()
        {
            try
            {
                Nuitrack.Init("");
                Console.WriteLine("Initialize succneed.");
            }
            catch (nuitrack.Exception exception)
            {
                Console.WriteLine("Cannot initialize Nuitrack.");
                //throw exception;
                MessageBoxX.Warning("3D摄像头初始化失败,请检查SDK配置和是否进行密钥认证。");
                Application.Current.Shutdown();
            }

            try
            {
                // Create and setup all required modules
                _depthSensor     = DepthSensor.Create();
                _colorSensor     = ColorSensor.Create();
                _userTracker     = UserTracker.Create();
                _skeletonTracker = SkeletonTracker.Create();
                //_handTracker = HandTracker.Create();
                _gestureRecognizer = GestureRecognizer.Create();
            }
            catch (nuitrack.Exception exception)
            {
                Console.WriteLine("Cannot create Nuitrack module.");
                //throw exception;
                MessageBoxX.Warning("3D摄像头初始化失败,请检查SDK配置和是否进行密钥认证。");
                Application.Current.Shutdown();
            }

            _depthSensor.SetMirror(false);
            // Add event handlers for all modules
            _depthSensor.OnUpdateEvent             += onDepthSensorUpdate;
            _colorSensor.OnUpdateEvent             += onColorSensorUpdate;
            _userTracker.OnUpdateEvent             += onUserTrackerUpdate;
            _skeletonTracker.OnSkeletonUpdateEvent += onSkeletonUpdate;
            //_handTracker.OnUpdateEvent += onHandTrackerUpdate;
            _gestureRecognizer.OnNewGesturesEvent += onNewGestures;
            // Add an event handler for the IssueUpdate event
            Nuitrack.onIssueUpdateEvent += onIssueDataUpdate;

            // Create and configure the Bitmap object according to the depth sensor output mode
            OutputMode mode      = _depthSensor.GetOutputMode();
            OutputMode colorMode = _colorSensor.GetOutputMode();

            if (mode.XRes < colorMode.XRes)
            {
                mode.XRes = colorMode.XRes;
            }
            if (mode.YRes < colorMode.YRes)
            {
                mode.YRes = colorMode.YRes;
            }
            Console.WriteLine(mode.XRes + "=====================" + mode.YRes);
            _bitmap = new DirectBitmap(mode.XRes, mode.YRes);
            for (int y = 0; y < mode.YRes; ++y)
            {
                for (int x = 0; x < mode.XRes; ++x)
                {
                    _bitmap.SetPixel(x, y, Color.FromKnownColor(KnownColor.Aqua));
                }
            }
            try
            {
                Nuitrack.Run();
                Console.WriteLine("Start Nuitrack.");
            }
            catch (nuitrack.Exception exception)
            {
                Console.WriteLine("Cannot start Nuitrack.");
                //throw exception;
                MessageBoxX.Warning("3D摄像头启动失败,请检查SDK配置和是否进行密钥认证。");
                Application.Current.Shutdown();
            }
        }
Пример #24
0
    static public void Main()
    {
        Console.CancelKeyPress += new ConsoleCancelEventHandler(consoleEventHandler);
        try
        {
            Nuitrack.Init("");

            // get devices list
            List <NuitrackDevice> devices = Nuitrack.GetDeviceList();
            if (devices.Count == 0)
            {
                throw new nuitrack.Exception("No devices found.");
            }

            // print available devices
            Console.Write("\nAvailable devices:\n");
            for (int i = 0; i < devices.Count; i++)
            {
                Console.WriteLine("    [{0}] {1} ({2}), License: {3}",
                                  i,
                                  devices[i].GetInfo(DeviceInfoType.SERIAL_NUMBER),
                                  devices[i].GetInfo(DeviceInfoType.DEVICE_NAME),
                                  ToString(devices[i].GetActivationStatus()));
            }
            // select a device
            int            devIndex = UserInteraction.AskInt("\nSelect the device number: ", 0, devices.Count);
            NuitrackDevice device   = devices[devIndex];

            // select video modes
            selectDeviceVideoMode(device, StreamType.DEPTH);
            selectDeviceVideoMode(device, StreamType.COLOR);

            // activate selected device
            bool isActivated = Convert.ToBoolean(device.GetActivationStatus());
            if (isActivated)
            {
                isActivated = !UserInteraction.Confirm("The device is already activated. Do you want to reactivate it?");
            }

            if (!isActivated)
            {
                string activationKey = UserInteraction.AskString("Enter the activation key: ");
                device.Activate(activationKey);
                Console.WriteLine("Activation status: {0}", ToString(device.GetActivationStatus()));
            }

            // set device and run Nuitrack
            if (UserInteraction.Confirm("Do you want to run Nuitrack with the selected device?"))
            {
                Nuitrack.SetDevice(device);

                DepthSensor depthSensor = DepthSensor.Create();
                ColorSensor colorSensor = ColorSensor.Create();

                depthSensor.OnUpdateEvent += onDepthSensorUpdate;
                colorSensor.OnUpdateEvent += onColorSensorUpdate;

                Nuitrack.Run();
                _run = true;

                while (!_finished)
                {
                    Nuitrack.WaitUpdate(depthSensor);
                }

                colorSensor.OnUpdateEvent -= onColorSensorUpdate;
                depthSensor.OnUpdateEvent -= onDepthSensorUpdate;
            }

            Nuitrack.Release();
        }
        catch (nuitrack.Exception exception)
        {
            Console.WriteLine("Error: " + exception.ToString());
        }
    }
Пример #25
0
        static void Main(string[] args)
        {//UDP writer for OSC
            UdpWriter udpWrite = new UdpWriter("127.0.0.1", 7000);

            try
            {
                Nuitrack.Init("");
            }
            catch (Exception exception)
            {
                Console.WriteLine("Cannot initialize Nuitrack.");
                throw exception;
            }

            try
            {
                // Create and setup all required modules
                _depthSensor     = DepthSensor.Create();
                _userTracker     = UserTracker.Create();
                _skeletonTracker = SkeletonTracker.Create();
            }
            catch (Exception exception)
            {
                Console.WriteLine("Cannot create Nuitrack module.");
                Console.WriteLine(exception.Message);
                throw exception;
            }
            // Add event handlers for all modules
            _depthSensor.OnUpdateEvent             += OnDepthSensorUpdate;
            _userTracker.OnNewUserEvent            += OnUserTrackerNewUser;
            _userTracker.OnLostUserEvent           += OnUserTrackerLostUser;
            _skeletonTracker.OnSkeletonUpdateEvent += OnSkeletonUpdate;

            // Add an event handler for the IssueUpdate event
            Nuitrack.onIssueUpdateEvent += OnIssueDataUpdate;

            try
            {
                Nuitrack.Run();
                Console.WriteLine(DateTime.Now.ToString());
            }
            catch (Exception exception)
            {
                Console.WriteLine("Cannot start Nuitrack.");
                throw exception;
            }
            bool a = true;

            while (a)
            {
                int start = (int)DateTime.Now.TimeOfDay.TotalMilliseconds;
                // Update Nuitrack data. Data will be synchronized with skeleton time stamps.
                try
                {
                    Nuitrack.Update(_skeletonTracker);
                }
                catch (LicenseNotAcquiredException exception)
                {
                    Console.WriteLine(DateTime.Now.ToString());
                    Console.WriteLine("LicenseNotAcquired exception. Exception: {0}", exception);
                    throw exception;
                }
                catch (Exception exception)
                {
                    Console.WriteLine("Nuitrack update failed. Exception: ", exception);
                }
                if (_skeletonData != null)
                {
                    //Create new bundle for each time skeleton data is refreshed
                    OscBundle bundle = new OscBundle();

                    //const int jointSize = 10;
                    foreach (var skeleton in _skeletonData.Skeletons)
                    {
                        foreach (var joint in skeleton.Joints)
                        {
                            float[] rotationMatrix = joint.Orient.Matrix;

                            //Ignore joints that are not currently used by Nuitrack
                            if (joint.Type == JointType.None || joint.Type == JointType.LeftFingertip || joint.Type == JointType.RightFingertip || joint.Type == JointType.LeftFoot || joint.Type == JointType.RightFoot)
                            {
                                continue;
                            }

                            //Create new message element for joint containing joint type and rotation matrix
                            OscElement jointMessage = new OscElement("/" + joint.Type, joint.Real.X, joint.Real.Y, joint.Real.Z, rotationMatrix[0], rotationMatrix[1], -1 * rotationMatrix[2], rotationMatrix[3], rotationMatrix[4], -1 * rotationMatrix[5], -1 * rotationMatrix[6], -1 * rotationMatrix[7], rotationMatrix[8]);
                            Console.WriteLine(joint.Real.X + " " + joint.Real.Y + " " + joint.Real.Z);
                            bundle.AddElement(jointMessage);
                        }
                        //Send the message bundle with the data
                        udpWrite.Send(bundle);
                        int difference = delay - start - (int)DateTime.Now.TimeOfDay.TotalMilliseconds;
                        System.Threading.Thread.Sleep(delay);
                    }
                }
            }

            Nuitrack.Release();
            Console.ReadLine();
        }
Пример #26
0
    private void Update()
    {
        string json = Nuitrack.GetInstancesJson();

        faceInfo = JsonUtility.FromJson <JsonInfo>(json.Replace("\"\"", "[]"));
    }
        protected override void OnPaint(PaintEventArgs args)
        {
            int exit_cnt = 0;

            base.OnPaint(args);

            // Update Nuitrack data. Data will be synchronized with skeleton time stamps.
            try
            {
                Nuitrack.Update(_skeletonTracker);
            }
            catch (LicenseNotAcquiredException exception)
            {
                Console.WriteLine("LicenseNotAcquired exception. Exception: ", exception);
                throw exception;
            }
            catch (Exception exception)
            {
                Console.WriteLine("Nuitrack update failed. Exception: ", exception);
            }

            // Draw a bitmap
            args.Graphics.DrawImage(_bitmap.Bitmap, new Point(0, 0));

            // Draw skeleton joints
            if (_skeletonData != null)
            {
                Database_set();
                using (conn = new MySqlConnection(DB_INFO))
                {
                    if (conn.State != System.Data.ConnectionState.Open)
                    {
                        conn.Open();
                    }


                    /*
                     * If not exist database of userId, DB creation
                     * If exist, skip
                     */
                    try
                    {
                        string create_sql = "CREATE TABLE IF NOT EXISTS " + this.TBL_NAME + "(" +
                                            "TYPE VARCHAR(10) NOT NULL, " +
                                            "ANGLE INT NOT NULL, " +
                                            "TIME DATETIME NOT NULL" +
                                            ")";
                        MySqlCommand create_cmd = new MySqlCommand(create_sql, conn);
                        create_cmd.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("CREATE TABLE USER_ID error!");
                        MessageBox.Show(ex.Message);
                        MessageBox.Show(ex.StackTrace);
                    }
                    finally
                    {
                        //Console.WriteLine("CREATE TABLE IF NOT EXISTS Success.");
                        conn.Close();
                    }
                }

                if (conn.State == System.Data.ConnectionState.Open)
                {
                    conn.Close();
                }

                const int jointSize = 10;
                foreach (var skeleton in _skeletonData.Skeletons)
                {
                    SolidBrush brush = new SolidBrush(Color.FromArgb(255 - 40 * skeleton.ID, 0, 0));

                    int _cnt = 0;
                    foreach (var joint in skeleton.Joints)
                    {
                        args.Graphics.FillEllipse(brush, joint.Proj.X * _bitmap.Width - jointSize / 2,
                                                  joint.Proj.Y * _bitmap.Height - jointSize / 2, jointSize, jointSize);


                        //Type & enum
                        //Console.WriteLine(joint.Type + " : " + joint.Proj.X + " " + joint.Proj.Y + " " + joint.Proj.Z);

                        _myAngle._myJoint[_cnt++].setValue
                        (
                            joint.Real.X,
                            joint.Real.Y,
                            joint.Real.Z
                        );
                    }


                    // print the data at about 1(sec) intervals
                    if (myCnt >= 1000)
                    {
                        int temp = (int)(GetJointAngle.AngleBetweenJoints
                                         (
                                             _myAngle._myJoint[angleInfo[this.SET_NUM, 0]],
                                             _myAngle._myJoint[angleInfo[this.SET_NUM, 1]],
                                             _myAngle._myJoint[angleInfo[this.SET_NUM, 2]]
                                         )
                                         );

                        using (conn = new MySqlConnection(DB_INFO))
                        {
                            if (conn.State != System.Data.ConnectionState.Open)
                            {
                                conn.Open();
                            }

                            DateTime now  = DateTime.Now;
                            string   date = now.ToString("yyyy-MM-dd H:mm:ss");

                            try
                            {
                                string sql = "INSERT INTO " + TBL_NAME + " VALUES(" +
                                             "'" + "SET " + SET_NUM + "'" + "," +
                                             "'" + temp + "'" + "," +
                                             "'" + date + "'" +
                                             ")";
                                MySqlCommand cmd = new MySqlCommand(sql, conn);
                                //cmd.Connection.Open();
                                cmd.ExecuteNonQuery();

                                if (exit_cnt++ >= 3)
                                {
                                    Application.Exit();
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("MySQL connection error!");
                                MessageBox.Show(ex.Message);
                                MessageBox.Show(ex.StackTrace);
                            }
                            finally
                            {
                                //Console.WriteLine("INSERT INTO TBL VALUES() Success.");
                                conn.Close();
                            }
                        }

                        Console.WriteLine(temp + " DB Insert !");
                        myCnt = 0;
                    }
                    else
                    {
                        myCnt++;
                    }
                }
            }

            // Draw hand pointers
            if (_handTrackerData != null)
            {
                foreach (var userHands in _handTrackerData.UsersHands)
                {
                    if (userHands.LeftHand != null)
                    {
                        HandContent hand  = userHands.LeftHand.Value;
                        int         size  = hand.Click ? 20 : 30;
                        Brush       brush = new SolidBrush(Color.Aquamarine);
                        args.Graphics.FillEllipse(brush, hand.X * _bitmap.Width - size / 2, hand.Y * _bitmap.Height - size / 2, size, size);
                    }

                    if (userHands.RightHand != null)
                    {
                        HandContent hand  = userHands.RightHand.Value;
                        int         size  = hand.Click ? 20 : 30;
                        Brush       brush = new SolidBrush(Color.DarkBlue);
                        args.Graphics.FillEllipse(brush, hand.X * _bitmap.Width - size / 2, hand.Y * _bitmap.Height - size / 2, size, size);
                    }
                }
            }

            // Update Form
            this.Invalidate();
        }
Пример #28
0
        private void DealWith()
        {
            try
            {
                Console.WriteLine("Update");
                Nuitrack.Update(_skeletonTracker);
            }
            catch (LicenseNotAcquiredException exception)
            {
                Console.WriteLine("LicenseNotAcquired exception. Exception: ", exception);
                MessageBoxX.Error("3D摄像头认证异常,请重新进入页面重试。");
                //throw exception;
            }
            catch (nuitrack.Exception exception)
            {
                Console.WriteLine("Nuitrack update failed. Exception: ", exception);
                MessageBoxX.Error("3D摄像头更新异常,请重新进入页面重试。");
            }

            // Draw skeleton joints
            //CQZ:检测骨架关节数据,骨骼数组不为空开始,里边while循环判断骨骼数组里如果为空,就调用API更新骨骼数据,线程sleep 0.1秒再循环检测
            while (true)
            {
                if (_skeletonData != null)
                {
                    //加try catch处理 --CQZ
                    try
                    {
                        Console.WriteLine("_skeletonData不为空,捕捉到人");
                        while (_skeletonData.Skeletons.Length == 0)
                        {
                            Nuitrack.Update(_skeletonTracker);
                            Console.WriteLine("Skeletons为空进行Update,Skeletons是个数组,每个元素对应一个人");
                            Thread.Sleep(100);
                        }
                    }
                    catch
                    {
                        Console.WriteLine("Skeletons为空进行Update异常");
                        MessageBoxX.Error("骨骼数据为空,请站到指定位置再开始扫描。");
                    }


                    Joint Head         = new Joint(); //衣领位置
                    Joint Collar       = new Joint(); //衣领位置
                    Joint LeftShoulder = new Joint(); //左肩关节
                    Joint LeftElbow    = new Joint(); //左胳膊肘
                    Joint LeftWrist    = new Joint(); //左手手腕关节
                    Joint LeftHip      = new Joint(); //左大腿关节
                    Joint LeftKnee     = new Joint(); //左膝盖关节
                    Joint LeftAnkle    = new Joint(); //左脚踝
                    Joint Waist        = new Joint(); //腰部
                    Console.WriteLine("Joints长度为" + _skeletonData.Skeletons[0].Joints.Length);

                    //骨骼关节数据不为空后开始进行图像渲染,各个关节的计算初始化等操作。
                    try
                    {
                        while (!breakFlag)
                        {    //_skeletonData.Skeletons[0].Joints表示关节   _skeletonData.Skeletons.Length > 0 &&是不是可以删掉
                            if (_skeletonData.Skeletons.Length > 0 && _skeletonData.Skeletons[0].Joints.Length > 0)
                            {
                                Console.WriteLine("外层循环");
                                //CQZ:一直以来罪魁祸首崩溃异常的大坑!数组越界bug修改!!!!不应该是i < [].length  应该是 i < [].length-1
                                for (int i = 0; i < _skeletonData.Skeletons[0].Joints.Length - 1; i++)
                                {
                                    Skeleton skeleton = _skeletonData.Skeletons[0];

                                    this.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart) delegate()
                                    {
                                        //描点
                                        Console.WriteLine("图像渲染前" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
                                        DrawingVisual drawingVisual      = new DrawingVisual();
                                        DrawingContext drawingContext    = drawingVisual.RenderOpen();
                                        System.Windows.Media.Brush brush = new SolidColorBrush(System.Windows.Media.Color.FromRgb(255, 0, 0));
                                        foreach (var joint in skeleton.Joints)
                                        {
                                            drawingContext.DrawEllipse(brush, new System.Windows.Media.Pen(), new System.Windows.Point((joint.Proj.X * _bitmap.Width - 10 / 2) - 53, (joint.Proj.Y * _bitmap.Height - 10 / 2) - 70), 5, 5);
                                        }
                                        drawingContext.Close();
                                        RenderTargetBitmap bmp = new RenderTargetBitmap(640, 480, 120, 120, PixelFormats.Pbgra32);
                                        bmp.Render(drawingVisual);
                                        statusImage1.Source = bmp;
                                        Console.WriteLine("图像渲染后" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
                                    });
                                    //Console.WriteLine("类型" + i + " " + skeleton.Joints[i].Type.ToString());
                                    if (skeleton.Joints[i].Type.ToString() == "Head")
                                    {
                                        Head = skeleton.Joints[i];
                                        // Console.WriteLine("头部位置坐标" + i + "||" + Head.Real.X + "||" + Head.Real.Y + "||" + Head.Real.Z);
                                    }
                                    if (skeleton.Joints[i].Type.ToString() == "LeftCollar")
                                    {
                                        Collar = skeleton.Joints[i];
                                        // Console.WriteLine("衣领位置坐标" + i + "||" + Collar.Real.X + "||" + Collar.Real.Y + "||" + Collar.Real.Z);
                                    }
                                    if (skeleton.Joints[i].Type.ToString() == "LeftShoulder")
                                    {
                                        LeftShoulder = skeleton.Joints[i];
                                        // Console.WriteLine("左肩关节坐标" + i + "||" + LeftShoulder.Real.X + "||" + LeftShoulder.Real.Y + "||" + LeftShoulder.Real.Z);
                                    }
                                    if (skeleton.Joints[i].Type.ToString() == "LeftWrist")
                                    {
                                        LeftWrist = skeleton.Joints[i];
                                        //Console.WriteLine("左手手腕关节坐标" + i + "||" + LeftWrist.Real.X + "||" + LeftWrist.Real.Y + "||" + LeftWrist.Real.Z);
                                    }
                                    if (skeleton.Joints[i].Type.ToString() == "LeftHip")
                                    {
                                        LeftHip = skeleton.Joints[i];
                                        // Console.WriteLine("左大腿关节坐标" + i + "||" + LeftHip.Real.X + "||" + LeftHip.Real.Y + "||" + LeftHip.Real.Z);
                                    }
                                    if (skeleton.Joints[i].Type.ToString() == "LeftAnkle")
                                    {
                                        LeftAnkle = skeleton.Joints[i];
                                        // Console.WriteLine("左脚踝坐标" + i + "||" + LeftAnkle.Real.X + "||" + LeftAnkle.Real.Y + "||" + LeftAnkle.Real.Z);
                                    }
                                    if (skeleton.Joints[i].Type.ToString() == "LeftElbow")
                                    {
                                        LeftElbow = skeleton.Joints[i];
                                        // Console.WriteLine("左胳膊肘坐标" + i + "||" + LeftElbow.Real.X + "||" + LeftElbow.Real.Y + "||" + LeftElbow.Real.Z);
                                    }
                                    if (skeleton.Joints[i].Type.ToString() == "LeftKnee")
                                    {
                                        LeftKnee = skeleton.Joints[i];
                                        //Console.WriteLine("左膝盖坐标" + i + "||" + LeftKnee.Real.X + "||" + LeftKnee.Real.Y + "||" + LeftKnee.Real.Z);
                                    }
                                    if (skeleton.Joints[i].Type.ToString() == "Waist")
                                    {
                                        Waist = skeleton.Joints[i];
                                        //Console.WriteLine("腰部坐标" + i + "||" + Waist.Real.X + "||" + Waist.Real.Y + "||" + Waist.Real.Z);
                                    }
                                    //因为手动抓拍功能 改为全局变量 CQZ
                                    //计算距离
                                    NeckLength    = ComputeDistanceBetween2Joints(Head, Collar);
                                    ShoulderWidth = ComputeDistanceBetween2Joints(LeftShoulder, Collar);
                                    ArmLengthUp   = ComputeDistanceBetween2Joints(LeftShoulder, LeftElbow);
                                    ArmLengthDown = ComputeDistanceBetween2Joints(LeftElbow, LeftWrist);
                                    LegLengthUp   = ComputeDistanceBetween2Joints(LeftHip, LeftKnee);
                                    LegLengthDown = ComputeDistanceBetween2Joints(LeftKnee, LeftAnkle);
                                    BodyLength    = ComputeDistanceBetween2Joints(Collar, Waist);
                                    //获取权重
                                    string initWeight = ConfigUtil.Get("initWeight");
                                    //CQZ:身高计算:各个骨骼相加再补常量 常量请根据测试情况调节
                                    Height = LegLengthUp + LegLengthDown + BodyLength + NeckLength + Double.Parse(initWeight);
                                    //更新,直到点击手动拍照按钮。
                                    Console.WriteLine("Update前");
                                    Nuitrack.Update(_skeletonTracker);
                                    Console.WriteLine("Update后");
                                }
                            }
                            else
                            {
                                Nuitrack.Update(_skeletonTracker);
                                Console.WriteLine("未捕获到关节,更新");
                            }
                        }
                        break;
                    }
                    catch (IndexOutOfRangeException)
                    {
                        //如果调用release应该会抛出异常并被catch捕获,在此break;
                        Console.WriteLine("3D扫描数组越界。");
                        MessageBoxX.Error("扫描失败,请重置后再点击开始重新扫描。");
                    }
                }
                else
                {
                    Nuitrack.Update(_skeletonTracker);
                    Console.WriteLine("没有检测到人,进行Update");
                }
            }//如果_skeletonData为空,并没有进行处理,就会出现只有一帧画面就停止的状况。使用while(true)包围加上else{update}
        }
Пример #29
0
        protected override void OnPaint(PaintEventArgs args)
        {
            base.OnPaint(args);

            // Update Nuitrack data. Data will be synchronized with skeleton time stamps.
            try
            {
                Nuitrack.Update(_skeletonTracker);
            }
            catch (LicenseNotAcquiredException exception)
            {
                Console.WriteLine("LicenseNotAcquired exception. Exception: ", exception);
                throw exception;
            }
            catch (Exception exception)
            {
                Console.WriteLine("Nuitrack update failed. Exception: ", exception);
            }

            // Draw a bitmap
            args.Graphics.DrawImage(_bitmap.Bitmap, new Point(0, 0));

            // Draw skeleton joints
            if (_skeletonData != null)
            {
                const int jointSize = 10;
                foreach (var skeleton in _skeletonData.Skeletons)
                {
                    SolidBrush brush = new SolidBrush(Color.FromArgb(255 - 40 * skeleton.ID, 0, 0));
                    foreach (var joint in skeleton.Joints)
                    {
                        args.Graphics.FillEllipse(brush, joint.Proj.X * _bitmap.Width - jointSize / 2,
                                                  joint.Proj.Y * _bitmap.Height - jointSize / 2, jointSize, jointSize);
                    }
                }
            }

            // Draw hand pointers
            if (_handTrackerData != null)
            {
                foreach (var userHands in _handTrackerData.UsersHands)
                {
                    if (userHands.LeftHand != null)
                    {
                        HandContent hand  = userHands.LeftHand.Value;
                        int         size  = hand.Click ? 20 : 30;
                        Brush       brush = new SolidBrush(Color.Aquamarine);
                        args.Graphics.FillEllipse(brush, hand.X * _bitmap.Width - size / 2, hand.Y * _bitmap.Height - size / 2, size, size);
                    }

                    if (userHands.RightHand != null)
                    {
                        HandContent hand  = userHands.RightHand.Value;
                        int         size  = hand.Click ? 20 : 30;
                        Brush       brush = new SolidBrush(Color.DarkBlue);
                        args.Graphics.FillEllipse(brush, hand.X * _bitmap.Width - size / 2, hand.Y * _bitmap.Height - size / 2, size, size);
                    }
                }
            }

            // Update Form
            this.Invalidate();
        }
Пример #30
0
        /* Load the List of available devices and Select the Device */
        private NuitrackDevice SelectDevice()
        {
            // List availaible devices
            List <NuitrackDevice> devices = Nuitrack.GetDeviceList();
            int devices_count             = devices.Count;

            Console.Clear();

            // Check for an Empty List
            if (devices_count == 0)
            {
                Console.WriteLine("Error: there is no connected devices."); throw new nuitrack.Exception("Error: there is no connected devices.");
            }

            // Format the devices to String and output the array
            Console.WriteLine("Connected devices:");
            for (int i = 0; i < devices_count; i++)
            {
                Console.WriteLine("Device {0}:\n * Camera name: {1}\n * Serial number: {2}\n * Provider name: {3}\n * Activated: {4}", i, devices[i].GetInfo(DeviceInfoType.DEVICE_NAME), devices[i].GetInfo(DeviceInfoType.SERIAL_NUMBER), devices[i].GetInfo(DeviceInfoType.PROVIDER_NAME), devices[i].GetActivationStatus().ToString());
            }

            // Select a device
            Console.WriteLine("Select a device (Write a number or just press ENTER to select the camera 0 ({0})", devices[0].GetInfo(DeviceInfoType.DEVICE_NAME));
            int selected = -1;

            while (selected == -1)
            {
                string input = Console.ReadLine();

                // Default Input
                if (input == "")
                {
                    selected = 0;
                    break;
                }

                // Numeric input : Check that the input is valid
                if (int.TryParse(input, out selected))
                {
                    if (selected > devices_count - 1 || selected < 0)
                    {
                        selected = -1;
                        Console.SetCursorPosition(0, 2 + devices_count * 5); Console.Write(new string(' ', Console.WindowWidth));
                        Console.SetCursorPosition(0, 3 + devices_count * 5); Console.Write(new string(' ', Console.WindowWidth));
                        Console.SetCursorPosition(0, 2 + devices_count * 5);
                        Console.WriteLine("Bad entry: there is only {0} connected devices. Enter a number equal or lower than {1}.", devices_count, devices_count - 1);
                    }
                }
                else
                {
                    selected = -1;
                    Console.SetCursorPosition(0, 2 + devices_count * 5); Console.Write(new string(' ', Console.WindowWidth));
                    Console.SetCursorPosition(0, 3 + devices_count * 5); Console.Write(new string(' ', Console.WindowWidth));
                    Console.SetCursorPosition(0, 2 + devices_count * 5);
                    Console.WriteLine("Bad entry: you must write an integer equal or lower than {0}", devices_count - 1);
                }
            }

            // Return the selected Device
            Console.WriteLine("Selected device: {0}", selected);
            return(devices[selected]);
        }