Example #1
0
        private void FaceTrackingPipeline()
        {
            IsDispose = false;
            OnStart?.Invoke(this, null);

            #region Manager Init
            realSenseManager = RealSenseObjects.Session.CreateSenseManager();

            if (realSenseManager == null)
            {
                MessageBox.Show(
                    "PXCMSenseManager初始化失敗。",
                    "初始化失敗",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                OnStop?.Invoke(this, null);
                return;
            }

            PXCMCaptureManager captureManager = realSenseManager.captureManager;
            if (captureManager == null)
            {
                MessageBox.Show(
                    "PXCMCaptureManager初始化失敗。",
                    "初始化失敗",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                OnStop?.Invoke(this, null);
                return;
            }
            #endregion

            #region 基本設定
            //設定裝置
            captureManager.FilterByDeviceInfo(Form.SelectedDevice);

            //設定串流類型
            captureManager.FilterByStreamProfiles(Form.SelectedDeviceStreamProfile);


            //啟用臉部追蹤模組
            realSenseManager.EnableFace();
            PXCMFaceModule faceModule = realSenseManager.QueryFace();
            if (faceModule == null)
            {
                MessageBox.Show(
                    "取得PXCMFaceModule失敗。",
                    "初始化失敗",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                OnStop?.Invoke(this, null);
                return;
            }

            //建立臉部追蹤模組設定
            moduleConfiguration = faceModule.CreateActiveConfiguration();
            if (moduleConfiguration == null)
            {
                MessageBox.Show(
                    "建立PXCMFaceConfiguration失敗。",
                    "初始化失敗",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                OnStop?.Invoke(this, null);
                return;
            }
            //追蹤模式設定
            moduleConfiguration.SetTrackingMode(Form.ModeType);

            moduleConfiguration.strategy                  = PXCMFaceConfiguration.TrackingStrategyType.STRATEGY_RIGHT_TO_LEFT;
            moduleConfiguration.detection.isEnabled       = true;
            moduleConfiguration.detection.maxTrackedFaces = 4;//最大追蹤4個臉
            moduleConfiguration.landmarks.isEnabled       = false;
            moduleConfiguration.pose.isEnabled            = false;

            recognitionConfig =
                moduleConfiguration.QueryRecognition();

            if (recognitionConfig == null)
            {
                MessageBox.Show(
                    "建立RecognitionConfiguration失敗。",
                    "初始化失敗",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                OnStop?.Invoke(this, null);
                return;
            }

            recognitionConfig.Enable();
            #endregion

            #region 讀取資料庫數據
            if (Form.FaceData != null)
            {
                recognitionConfig.SetDatabase(Form.FaceData);
                moduleConfiguration.ApplyChanges();
            }
            #endregion

            #region 預備啟動
            moduleConfiguration.EnableAllAlerts();
            //moduleConfiguration.SubscribeAlert(FaceAlertHandler);

            pxcmStatus applyChangesStatus = moduleConfiguration.ApplyChanges();
            Form.SetStatus("RealSenseManager初始化中");
            if (applyChangesStatus.IsError() || realSenseManager.Init().IsError())
            {
                MessageBox.Show(
                    "RealSenseManager初始化失敗,請檢查設定正確。",
                    "初始化失敗",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                OnStop?.Invoke(this, null);
                return;
            }
            #endregion

            using (moduleOutput = faceModule.CreateOutput()) {
                PXCMCapture.Device.StreamProfileSet profiles;
                PXCMCapture.Device device = captureManager.QueryDevice();

                if (device == null)
                {
                    MessageBox.Show(
                        "取得設備失敗。",
                        "初始化失敗",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                    OnStop?.Invoke(this, null);
                    return;
                }

                device.QueryStreamProfileSet(PXCMCapture.StreamType.STREAM_TYPE_DEPTH, 0, out profiles);

                #region Loop
                while (!_Stop)
                {
                    while (_Paush)
                    {
                        Application.DoEvents();
                    }
                    if (realSenseManager.AcquireFrame(true).IsError())
                    {
                        break;
                    }
                    var isConnected = realSenseManager.IsConnected();
                    if (isConnected)
                    {
                        var sample = realSenseManager.QueryFaceSample();
                        if (sample == null)
                        {
                            realSenseManager.ReleaseFrame();
                            continue;
                        }
                        #region 畫面取出
                        PXCMImage image = null;
                        if (Form.ModeType == PXCMFaceConfiguration.TrackingModeType.FACE_MODE_IR)
                        {
                            image = sample.ir;
                        }
                        else
                        {
                            image = sample.color;
                        }
                        #endregion

                        moduleOutput.Update();//更新辨識
                        PXCMFaceConfiguration.RecognitionConfiguration recognition = moduleConfiguration.QueryRecognition();
                        if (recognition == null)
                        {
                            realSenseManager.ReleaseFrame();
                            continue;
                        }


                        #region 繪圖與事件
                        OnFrame?.Invoke(this, new FaceRecognitionEventArgs()
                        {
                            Image = ToBitmap(image)
                        });
                        FindFace(moduleOutput);
                        #endregion
                    }
                    //發布框
                    realSenseManager.ReleaseFrame();
                }
                #endregion

                //更新資料庫緩衝區
                //Buffer = moduleOutput.QueryRecognitionModule().GetDatabaseBuffer();
            }

            #region 釋放資源
            moduleConfiguration.Dispose();
            realSenseManager.Close();
            realSenseManager.Dispose();
            #endregion

            IsDispose = true;
            OnStop?.Invoke(this, null);
        }
        private void ConfigureRealSense()
        {
            PXCMFaceModule faceModule;
            PXCMFaceConfiguration faceConfig;

            // Start the SenseManager and session
            senseManager = PXCMSenseManager.CreateInstance();
            captureManager = senseManager.captureManager;

            // Enable the color stream
            senseManager.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_COLOR, 640, 480, 60);
            //senseManager.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_DEPTH, 640, 480, 0);

            // Enable the face module
            senseManager.EnableFace();
            faceModule = senseManager.QueryFace();
            faceConfig = faceModule.CreateActiveConfiguration();

            // Configure for 3D face tracking (if camera cannot support depth it will revert to 2D tracking)
            faceConfig.SetTrackingMode(PXCMFaceConfiguration.TrackingModeType.FACE_MODE_COLOR_PLUS_DEPTH);

            // Enable facial recognition
            recognitionConfig = faceConfig.QueryRecognition();
            recognitionConfig.Enable();

            //Enable Landmark Detection

            faceConfig.landmarks.isEnabled = true;
            // Create a recognition database
            PXCMFaceConfiguration.RecognitionConfiguration.RecognitionStorageDesc recognitionDesc = new PXCMFaceConfiguration.RecognitionConfiguration.RecognitionStorageDesc();
            recognitionDesc.maxUsers = DatabaseUsers;
            //recognitionConfig.CreateStorage(DatabaseName, out recognitionDesc);
            //recognitionConfig.UseStorage(DatabaseName);
            LoadDatabaseFromFile();
            recognitionConfig.SetRegistrationMode(PXCMFaceConfiguration.RecognitionConfiguration.RecognitionRegistrationMode.REGISTRATION_MODE_CONTINUOUS);

            // Apply changes and initialize
            faceConfig.ApplyChanges();
            senseManager.Init();
            faceData = faceModule.CreateOutput();

            // Mirror image
            senseManager.QueryCaptureManager().QueryDevice().SetMirrorMode(PXCMCapture.Device.MirrorMode.MIRROR_MODE_HORIZONTAL);
            // Release resources
            faceConfig.Dispose();
            faceModule.Dispose();
        }
Example #3
0
        public void SimplePipeline()
        {
            PXCMSenseManager pp = m_form.Session.CreateSenseManager();

            if (pp == null)
            {
                throw new Exception("PXCMSenseManager null");
            }

            PXCMCaptureManager captureMgr = pp.captureManager;

            if (captureMgr == null)
            {
                throw new Exception("PXCMCaptureManager null");
            }

            var selectedRes = m_form.GetCheckedColorResolution();

            if (selectedRes != null && !m_form.IsInPlaybackState())
            {
                // Set active camera
                PXCMCapture.DeviceInfo deviceInfo;
                m_form.Devices.TryGetValue(m_form.GetCheckedDevice(), out deviceInfo);
                captureMgr.FilterByDeviceInfo(m_form.GetCheckedDeviceInfo());

                // activate filter only live/record mode , no need in playback mode
                var set = new PXCMCapture.Device.StreamProfileSet
                {
                    color =
                    {
                        frameRate = selectedRes.Item2,
                        imageInfo =
                        {
                            format = selectedRes.Item1.format,
                            height = selectedRes.Item1.height,
                            width  = selectedRes.Item1.width
                        }
                    }
                };

                if (m_form.IsPulseEnabled() && (set.color.imageInfo.width < 1280 || set.color.imageInfo.height < 720))
                {
                    captureMgr.FilterByStreamProfiles(PXCMCapture.StreamType.STREAM_TYPE_COLOR, 1280, 720, 0);
                }
                else
                {
                    captureMgr.FilterByStreamProfiles(set);
                }
            }

            // Set Source & Landmark Profile Index
            if (m_form.IsInPlaybackState())
            {
                //pp.captureManager.FilterByStreamProfiles(null);
                captureMgr.SetFileName(m_form.GetFileName(), false);
                captureMgr.SetRealtime(false);
            }
            else if (m_form.GetRecordState())
            {
                captureMgr.SetFileName(m_form.GetFileName(), true);
            }

            // Set Module
            pp.EnableFace();
            PXCMFaceModule faceModule = pp.QueryFace();

            if (faceModule == null)
            {
                Debug.Assert(faceModule != null);
                return;
            }

            PXCMFaceConfiguration moduleConfiguration = faceModule.CreateActiveConfiguration();

            if (moduleConfiguration == null)
            {
                Debug.Assert(moduleConfiguration != null);
                return;
            }

            var checkedProfile = m_form.GetCheckedProfile();
            var mode           = m_form.FaceModesMap.First(x => x.Value == checkedProfile).Key;

            moduleConfiguration.SetTrackingMode(mode);

            moduleConfiguration.strategy = PXCMFaceConfiguration.TrackingStrategyType.STRATEGY_RIGHT_TO_LEFT;

            moduleConfiguration.detection.maxTrackedFaces = m_form.NumDetection;
            moduleConfiguration.landmarks.maxTrackedFaces = m_form.NumLandmarks;
            moduleConfiguration.pose.maxTrackedFaces      = m_form.NumPose;

            PXCMFaceConfiguration.ExpressionsConfiguration econfiguration = moduleConfiguration.QueryExpressions();
            if (econfiguration == null)
            {
                throw new Exception("ExpressionsConfiguration null");
            }
            econfiguration.properties.maxTrackedFaces = m_form.NumExpressions;

            econfiguration.EnableAllExpressions();
            moduleConfiguration.detection.isEnabled = m_form.IsDetectionEnabled();
            moduleConfiguration.landmarks.isEnabled = m_form.IsLandmarksEnabled();
            moduleConfiguration.pose.isEnabled      = m_form.IsPoseEnabled();
            if (m_form.IsExpressionsEnabled())
            {
                econfiguration.Enable();
            }

            PXCMFaceConfiguration.PulseConfiguration pulseConfiguration = moduleConfiguration.QueryPulse();
            if (pulseConfiguration == null)
            {
                throw new Exception("pulseConfiguration null");
            }

            pulseConfiguration.properties.maxTrackedFaces = m_form.NumPulse;
            if (m_form.IsPulseEnabled())
            {
                pulseConfiguration.Enable();
            }

            qrecognition = moduleConfiguration.QueryRecognition();
            if (qrecognition == null)
            {
                throw new Exception("PXCMFaceConfiguration.RecognitionConfiguration null");
            }
            if (m_form.IsRecognitionChecked())
            {
                qrecognition.Enable();


                #region 臉部辨識資料庫讀取
                if (File.Exists(DatabasePath))
                {
                    m_form.UpdateStatus("正在讀取資料庫", MainForm.Label.StatusLabel);
                    List <RecognitionFaceData> faceData = null;
                    FaceDatabaseFile.Load(DatabasePath, ref faceData, ref NameMapping);
                    FaceData = faceData.ToArray();
                    qrecognition.SetDatabase(FaceData);
                }
                #endregion
            }



            moduleConfiguration.EnableAllAlerts();
            moduleConfiguration.SubscribeAlert(FaceAlertHandler);

            pxcmStatus applyChangesStatus = moduleConfiguration.ApplyChanges();

            m_form.UpdateStatus("Init Started", MainForm.Label.StatusLabel);

            if (applyChangesStatus < pxcmStatus.PXCM_STATUS_NO_ERROR || pp.Init() < pxcmStatus.PXCM_STATUS_NO_ERROR)
            {
                m_form.UpdateStatus("Init Failed", MainForm.Label.StatusLabel);
            }
            else
            {
                using (PXCMFaceData moduleOutput = faceModule.CreateOutput())
                {
                    Debug.Assert(moduleOutput != null);
                    PXCMCapture.Device.StreamProfileSet profiles;
                    PXCMCapture.Device device = captureMgr.QueryDevice();

                    if (device == null)
                    {
                        throw new Exception("device null");
                    }

                    device.QueryStreamProfileSet(PXCMCapture.StreamType.STREAM_TYPE_DEPTH, 0, out profiles);
                    CheckForDepthStream(profiles, faceModule);

                    m_form.UpdateStatus("Streaming", MainForm.Label.StatusLabel);
                    m_timer = new FPSTimer(m_form);

                    #region loop
                    while (!m_form.Stopped)
                    {
                        if (pp.AcquireFrame(true) < pxcmStatus.PXCM_STATUS_NO_ERROR)
                        {
                            break;
                        }
                        var isConnected = pp.IsConnected();
                        DisplayDeviceConnection(isConnected);
                        if (isConnected)
                        {
                            var sample = pp.QueryFaceSample();
                            if (sample == null)
                            {
                                pp.ReleaseFrame();
                                continue;
                            }
                            switch (mode)
                            {
                            case PXCMFaceConfiguration.TrackingModeType.FACE_MODE_IR:
                                if (sample.ir != null)
                                {
                                    DisplayPicture(sample.ir);
                                }
                                break;

                            default:
                                DisplayPicture(sample.color);
                                break;
                            }

                            moduleOutput.Update();
                            PXCMFaceConfiguration.RecognitionConfiguration recognition = moduleConfiguration.QueryRecognition();
                            if (recognition == null)
                            {
                                pp.ReleaseFrame();
                                continue;
                            }

                            if (recognition.properties.isEnabled)
                            {
                                UpdateRecognition(moduleOutput);
                            }

                            m_form.DrawGraphics(moduleOutput);
                            m_form.UpdatePanel();
                        }
                        pp.ReleaseFrame();
                    }
                    #endregion
                }

                //             moduleConfiguration.UnsubscribeAlert(FaceAlertHandler);
                //             moduleConfiguration.ApplyChanges();
                m_form.UpdateStatus("Stopped", MainForm.Label.StatusLabel);
            }

            #region 儲存臉部辨識資訊檔案
            if (DatabaseChanged)
            {
                FaceDatabaseFile.Save(DatabasePath, FaceData.ToList(), NameMapping);
            }
            #endregion

            var dbm = new FaceDatabaseManager(pp);


            moduleConfiguration.Dispose();
            pp.Close();
            pp.Dispose();
        }
Example #4
0
        public void SimplePipeline()
        {
            PXCMSenseManager pp = m_form.Session.CreateSenseManager();

            if (pp == null)
            {
                throw new Exception("PXCMSenseManager null");
            }

            // Set Source & Landmark Profile Index
            PXCMCapture.DeviceInfo info;
            if (m_form.GetRecordState())
            {
                pp.captureManager.SetFileName(m_form.GetFileName(), true);
                if (m_form.Devices.TryGetValue(m_form.GetCheckedDevice(), out info))
                {
                    pp.captureManager.FilterByDeviceInfo(info);
                }
            }
            else if (m_form.GetPlaybackState())
            {
                pp.captureManager.SetFileName(m_form.GetFileName(), false);
                PXCMCaptureManager cmanager = pp.QueryCaptureManager();
                if (cmanager == null)
                {
                    throw new Exception("PXCMCaptureManager null");
                }
                cmanager.SetRealtime(false);
            }
            else
            {
                if (m_form.Devices.TryGetValue(m_form.GetCheckedDevice(), out info))
                {
                    pp.captureManager.FilterByDeviceInfo(info);
                    Tuple <PXCMImage.ImageInfo, PXCMRangeF32> selectedRes = m_form.GetCheckedColorResolution();
                    var set = new PXCMCapture.Device.StreamProfileSet();
                    set.color.frameRate        = selectedRes.Item2;
                    set.color.imageInfo.format = selectedRes.Item1.format;
                    set.color.imageInfo.width  = selectedRes.Item1.width;
                    set.color.imageInfo.height = selectedRes.Item1.height;
                    pp.captureManager.FilterByStreamProfiles(set);
                }
            }

            // Set Module
            pp.EnableFace();
            PXCMFaceModule faceModule = pp.QueryFace();

            if (faceModule == null)
            {
                Debug.Assert(faceModule != null);
                return;
            }

            PXCMFaceConfiguration moduleConfiguration = faceModule.CreateActiveConfiguration();

            if (moduleConfiguration == null)
            {
                Debug.Assert(moduleConfiguration != null);
                return;
            }

            PXCMFaceConfiguration.TrackingModeType mode = m_form.GetCheckedProfile().Contains("3D")
                ? PXCMFaceConfiguration.TrackingModeType.FACE_MODE_COLOR_PLUS_DEPTH
                : PXCMFaceConfiguration.TrackingModeType.FACE_MODE_COLOR;

            moduleConfiguration.SetTrackingMode(mode);

            moduleConfiguration.strategy = PXCMFaceConfiguration.TrackingStrategyType.STRATEGY_RIGHT_TO_LEFT;

            moduleConfiguration.detection.maxTrackedFaces = m_form.NumDetection;
            moduleConfiguration.landmarks.maxTrackedFaces = m_form.NumLandmarks;
            moduleConfiguration.pose.maxTrackedFaces      = m_form.NumPose;
            PXCMFaceConfiguration.ExpressionsConfiguration econfiguration = moduleConfiguration.QueryExpressions();
            if (econfiguration == null)
            {
                throw new Exception("ExpressionsConfiguration null");
            }
            econfiguration.properties.maxTrackedFaces = m_form.NumExpressions;

            econfiguration.EnableAllExpressions();
            moduleConfiguration.detection.isEnabled = m_form.IsDetectionEnabled();
            moduleConfiguration.landmarks.isEnabled = m_form.IsLandmarksEnabled();
            moduleConfiguration.pose.isEnabled      = m_form.IsPoseEnabled();
            if (m_form.IsExpressionsEnabled())
            {
                econfiguration.Enable();
            }

            PXCMFaceConfiguration.RecognitionConfiguration qrecognition = moduleConfiguration.QueryRecognition();
            if (qrecognition == null)
            {
                throw new Exception("PXCMFaceConfiguration.RecognitionConfiguration null");
            }
            if (m_form.IsRecognitionChecked())
            {
                qrecognition.Enable();
            }

            moduleConfiguration.EnableAllAlerts();
            moduleConfiguration.SubscribeAlert(FaceAlertHandler);

            pxcmStatus applyChangesStatus = moduleConfiguration.ApplyChanges();

            m_form.UpdateStatus("Init Started", MainForm.Label.StatusLabel);

            if (applyChangesStatus < pxcmStatus.PXCM_STATUS_NO_ERROR || pp.Init() < pxcmStatus.PXCM_STATUS_NO_ERROR)
            {
                m_form.UpdateStatus("Init Failed", MainForm.Label.StatusLabel);
            }
            else
            {
                using (PXCMFaceData moduleOutput = faceModule.CreateOutput())
                {
                    Debug.Assert(moduleOutput != null);
                    PXCMCapture.Device.StreamProfileSet profiles;

                    PXCMCaptureManager cmanager = pp.QueryCaptureManager();
                    if (cmanager == null)
                    {
                        throw new Exception("capture manager null");
                    }
                    PXCMCapture.Device device = cmanager.QueryDevice();

                    if (device == null)
                    {
                        throw new Exception("device null");
                    }

                    device.QueryStreamProfileSet(PXCMCapture.StreamType.STREAM_TYPE_DEPTH, 0, out profiles);
                    CheckForDepthStream(profiles, faceModule);

                    ushort threshold      = device.QueryDepthConfidenceThreshold();
                    int    filter_option  = device.QueryIVCAMFilterOption();
                    int    range_tradeoff = device.QueryIVCAMMotionRangeTradeOff();

                    device.SetDepthConfidenceThreshold(1);
                    device.SetIVCAMFilterOption(6);
                    device.SetIVCAMMotionRangeTradeOff(21);

                    if (m_form.IsMirrored())
                    {
                        device.SetMirrorMode(PXCMCapture.Device.MirrorMode.MIRROR_MODE_HORIZONTAL);
                    }
                    else
                    {
                        device.SetMirrorMode(PXCMCapture.Device.MirrorMode.MIRROR_MODE_DISABLED);
                    }

                    m_form.UpdateStatus("Streaming", MainForm.Label.StatusLabel);
                    m_timer = new FPSTimer(m_form);

                    while (!m_form.Stopped)
                    {
                        if (pp.AcquireFrame(true) < pxcmStatus.PXCM_STATUS_NO_ERROR)
                        {
                            break;
                        }
                        bool isConnected = pp.IsConnected();
                        DisplayDeviceConnection(isConnected);
                        if (isConnected)
                        {
                            PXCMCapture.Sample sample = pp.QueryFaceSample();
                            if (sample == null)
                            {
                                pp.ReleaseFrame();
                                continue;
                            }
                            DisplayPicture(sample.color);

                            moduleOutput.Update();
                            if (moduleConfiguration.QueryRecognition().properties.isEnabled)
                            {
                                UpdateRecognition(moduleOutput);
                            }

                            m_form.DrawGraphics(moduleOutput);
                            m_form.UpdatePanel();
                        }
                        pp.ReleaseFrame();
                    }

                    device.SetDepthConfidenceThreshold(threshold);
                    device.SetIVCAMFilterOption(filter_option);
                    device.SetIVCAMMotionRangeTradeOff(range_tradeoff);
                }

                moduleConfiguration.UnsubscribeAlert(FaceAlertHandler);
                moduleConfiguration.ApplyChanges();
                m_form.UpdateStatus("Stopped", MainForm.Label.StatusLabel);
            }
            moduleConfiguration.Dispose();
            pp.Close();
            pp.Dispose();
        }
Example #5
0
        public void SimplePipeline()
        {
            bool             sts = true;
            PXCMSenseManager pp  = form.session.CreateSenseManager();

            if (pp == null)
            {
                throw new Exception("Failed to create sense manager");
            }
            disconnected = false;

            /* Set Source & Profile Index */
            PXCMCapture.DeviceInfo info = null;
            if (this.form.GetRecordState())
            {
                pp.captureManager.SetFileName(this.form.GetFileName(), true);
                form.PopulateDeviceMenu();
                if (this.form.Devices.TryGetValue(this.form.GetCheckedDevice(), out info))
                {
                    pp.captureManager.FilterByDeviceInfo(info);
                }
            }
            else if (this.form.GetPlaybackState())
            {
                pp.captureManager.SetFileName(this.form.GetFileName(), false);
            }
            else
            {
                if (this.form.Devices.TryGetValue(this.form.GetCheckedDevice(), out info))
                {
                    pp.captureManager.FilterByDeviceInfo(info);
                }
            }

            /* Set Module */
            pp.EnableEmotion(form.GetCheckedModule());

            /* Initialization */
            form.UpdateStatus("Init Started");

            PXCMSenseManager.Handler handler = new PXCMSenseManager.Handler()
            {
                //GZ onModuleQueryProfile = OnModuleQueryProfile
            };

            if (pp.Init(handler) >= pxcmStatus.PXCM_STATUS_NO_ERROR)
            {
                form.UpdateStatus("Streaming");
                this.timer = new FPSTimer(form);
                PXCMCaptureManager captureManager = pp.QueryCaptureManager();
                if (captureManager == null)
                {
                    throw new Exception("Failed to query capture manager");
                }
                PXCMCapture.Device device = captureManager.QueryDevice();

                if (device != null && !this.form.GetPlaybackState())
                {
                    device.SetDepthConfidenceThreshold(7);
                }
                //GZ device.SetProperty(PXCMCapture.Device.Property.PROPERTY_DEPTH_CONFIDENCE_THRESHOLD, 7);

                while (!form.stop)
                {
                    if (pp.AcquireFrame(true) < pxcmStatus.PXCM_STATUS_NO_ERROR)
                    {
                        break;
                    }
                    if (!DisplayDeviceConnection(!pp.IsConnected()))
                    {
                        /* Display Results */
                        PXCMEmotion ft = pp.QueryEmotion();

                        //GZ DisplayPicture(pp.QueryImageByType(PXCMImage.ImageType.IMAGE_TYPE_COLOR));
                        PXCMCapture.Sample sample = pp.QuerySample();

                        /* Start of modified code */
                        // Grab the first BMP in the folder, assume there is one for now
                        string   folder = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
                        string[] files  = Directory.GetFiles(folder, "*.bmp");
                        Bitmap   bitmap = new Bitmap(files[0]);
                        // Create a PXCMImage from the BMP
                        PXCMImage.ImageInfo iinfo = new PXCMImage.ImageInfo();
                        iinfo.width  = bitmap.Width;
                        iinfo.height = bitmap.Height;
                        iinfo.format = PXCMImage.PixelFormat.PIXEL_FORMAT_RGB32;
                        PXCMImage           imageTEST = form.session.CreateImage(iinfo);
                        PXCMImage.ImageData idata;
                        imageTEST.AcquireAccess(PXCMImage.Access.ACCESS_WRITE, out idata);
                        BitmapData bdata = new BitmapData();
                        bdata.Scan0       = idata.planes[0];
                        bdata.Stride      = idata.pitches[0];
                        bdata.PixelFormat = PixelFormat.Format32bppRgb;
                        bdata.Width       = bitmap.Width;
                        bdata.Height      = bitmap.Height;
                        BitmapData bdata2 = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height),
                                                            ImageLockMode.ReadOnly | ImageLockMode.UserInputBuffer,
                                                            PixelFormat.Format32bppRgb, bdata);
                        bitmap.UnlockBits(bdata2);
                        imageTEST.ReleaseAccess(idata);
                        // Save the BMP
                        Bitmap savebmp = idata.ToBitmap(0, bitmap.Width, bitmap.Height);
                        //savebmp.Save(@"O:\unix\projects\instr\production5\research\Francis\result.bmp");

                        // Put my own PXCMImage into the sample
                        PXCMCapture.Sample smp = new PXCMCapture.Sample();
                        smp.color = imageTEST;

                        // Get the video module from the emotion instance
                        PXCMVideoModule module = ft.QueryInstance <PXCMVideoModule>();
                        PXCMSyncPoint   sp;
                        // Process the sample
                        module.ProcessImageAsync(smp, out sp);
                        // Synchronize then get emotion data etc.
                        sp.Synchronize();
                        /* End of modified code */

                        DisplayPicture(sample.color);

                        DisplayLocation(ft);

                        form.UpdatePanel();
                    }
                    pp.ReleaseFrame();
                }
            }
            else
            {
                form.UpdateStatus("Init Failed");
                sts = false;
            }

            pp.Close();
            pp.Dispose();
            if (sts)
            {
                form.UpdateStatus("Stopped");
            }
        }
Example #6
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;
        }
Example #7
0
 public RSSDKContext()
 {
     this.sm = PXCMSenseManager.CreateInstance();
        	this.Session = sm.QuerySession();
        	if(this.Session == null) this.Session  = PXCMSession.CreateInstance();
        	this.cm = sm.QueryCaptureManager();
     if(this.cm  == null) this.cm = this.Session.CreateCaptureManager();
 }
        public pxcmStatus InitRecordPlay()
        {
            pxcmStatus status;

            _senseManager.Close();
            PXCMCaptureManager cm = _senseManager.QueryCaptureManager();

            if (Playback || Record)
            {
                status = cm.SetFileName(this.RecordedFile, this.Record);
                if (status != pxcmStatus.PXCM_STATUS_NO_ERROR)
                {
                    _logger.info("Unable to set file name:" + status.ToString());
                    // return status;
                    throw new Smithers.Reading.FrameData.ScannerNotFoundException("Unable to set file record name");
                }
            }
            PXCMVideoModule.DataDesc desc = new PXCMVideoModule.DataDesc();
            if (cm.QueryCapture() != null && Playback)
            {
                //recordedFile = null;
                cm.SetRealtime(RealTime);
                cm.QueryCapture().QueryDeviceInfo(0, out desc.deviceInfo);
                status = _senseManager.EnableStreams(desc);
                if (status != pxcmStatus.PXCM_STATUS_NO_ERROR)
                {
                    _logger.info("Unable to enable capture stream:" + status.ToString());
                    throw new Smithers.Reading.FrameData.ScannerNotFoundException("Unable to enable capture stream");
                }
            }
            else
            {
                status = _senseManager.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_COLOR, Frame.COLOR_WIDTH, Frame.COLOR_HEIGHT, Frame.COLOR_RATE);
                if (status != pxcmStatus.PXCM_STATUS_NO_ERROR)
                {
                    _logger.info("Unable to enable color stream:" + status.ToString());
                    throw new Smithers.Reading.FrameData.ScannerNotFoundException("Unable to enable color stream");
                }
                status = _senseManager.EnableStream(PXCMCapture.StreamType.STREAM_TYPE_DEPTH, Frame.DEPTH_WIDTH, Frame.DEPTH_HEIGHT, Frame.DEPTH_RATE);
                if (status != pxcmStatus.PXCM_STATUS_NO_ERROR)
                {
                    _logger.info("Unable to enable depth stream:" + status.ToString());
                    throw new Smithers.Reading.FrameData.ScannerNotFoundException("Unable to enable depth stream");
                }

                _logger.info("Depth Stream Enabled:" + status.ToString());
            }

            status = _senseManager.EnableScenePerception();
            if (status != pxcmStatus.PXCM_STATUS_NO_ERROR)
            {
                _logger.info("Unable to enable scene perception:" + status.ToString());
                throw new Smithers.Reading.FrameData.ScannerNotFoundException("Scene Perception failed");
            }
            _logger.info("Scene Perception Enabled:" + status.ToString());

            _perceptionHandle = _senseManager.QueryScenePerception();

            status = _senseManager.Init();
            if (status != pxcmStatus.PXCM_STATUS_NO_ERROR)
            {
                _logger.info("Unable to open sensor in the above mode:" + status.ToString());
                throw new Smithers.Reading.FrameData.ScannerNotFoundException("Init failed");
            }

            _logger.info("Sensor Initialized Successfully:" + status.ToString());
            return(status);
        }
Example #9
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;
            }

            PXCMCaptureManager captureManager = instance.captureManager;

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

                    if (form.Devices.TryGetValue(form.GetCheckedDevice(), out info))
                    {
                        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)
                {
                    device.QueryDeviceInfo(out dinfo);
                    _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;

                while (!form.stop)
                {
                    string gestureName = form.GetGestureName();
                    if (string.IsNullOrEmpty(gestureName) == false)
                    {
                        if (handConfiguration.IsGestureEnabled(gestureName) == false)
                        {
                            handConfiguration.DisableAllGestures();
                            handConfiguration.EnableGesture(gestureName, true);
                            handConfiguration.ApplyChanges();
                        }
                    }
                    else
                    {
                        handConfiguration.DisableAllGestures();
                        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();
                }
            }
            else
            {
                form.UpdateStatus("Init Failed");
                flag = false;
            }
            foreach (PXCMImage pxcmImage in m_images)
            {
                pxcmImage.Dispose();
            }

            // Clean Up
            if (handData != null)
            {
                handData.Dispose();
            }
            if (handConfiguration != null)
            {
                handConfiguration.Dispose();
            }
            instance.Close();
            instance.Dispose();

            if (flag)
            {
                form.UpdateStatus("Stopped");
            }
        }
Example #10
0
        private bool UpdateFace(AnimationTrigger animationTrigger)
        {
            animationTrigger.IsAnimationDataValid = false;

            // Get the closest face
            PXCMFaceData.Face pxcmFace = SenseToolkitManager.Instance.FaceModuleOutput.QueryFaceByIndex(0);

            if (pxcmFace == null)
            {
                return(false);
            }

            if (SenseToolkitManager.Instance.FaceModuleOutput.QueryNumberOfDetectedFaces() <= 0)
            {
                // PXCMFaceData.QueryFaceByIndex(0) failed.
                return(false);
            }

            PXCMFaceData.LandmarksData pxcmLandmarksData = pxcmFace.QueryLandmarks();
            if (pxcmLandmarksData == null)
            {
                // PXCMFaceData.Face.QueryLandmarks() failed.
                return(false);
            }

            Dictionary <PXCMFaceData.LandmarkType, PXCMFaceData.LandmarkPoint> landmarkPoints = new Dictionary <PXCMFaceData.LandmarkType, PXCMFaceData.LandmarkPoint>();

            PXCMFaceData.LandmarkType[] landmarkTypes = new PXCMFaceData.LandmarkType[]
            {
                PXCMFaceData.LandmarkType.LANDMARK_NOSE_TIP,
                PXCMFaceData.LandmarkType.LANDMARK_NOSE_TOP,
                PXCMFaceData.LandmarkType.LANDMARK_EYEBROW_LEFT_CENTER,
                PXCMFaceData.LandmarkType.LANDMARK_EYE_LEFT_CENTER,
                PXCMFaceData.LandmarkType.LANDMARK_EYEBROW_RIGHT_CENTER,
                PXCMFaceData.LandmarkType.LANDMARK_EYE_RIGHT_CENTER,
                PXCMFaceData.LandmarkType.LANDMARK_UPPER_LIP_CENTER,
                PXCMFaceData.LandmarkType.LANDMARK_LOWER_LIP_CENTER,
                PXCMFaceData.LandmarkType.LANDMARK_EYELID_LEFT_TOP,
                PXCMFaceData.LandmarkType.LANDMARK_EYELID_LEFT_BOTTOM,
                PXCMFaceData.LandmarkType.LANDMARK_EYELID_RIGHT_TOP,
                PXCMFaceData.LandmarkType.LANDMARK_EYELID_RIGHT_BOTTOM
            };

            foreach (PXCMFaceData.LandmarkType landmarkType in landmarkTypes)
            {
                PXCMFaceData.LandmarkPoint landmarkPoint = GetLandmarkPoint(pxcmLandmarksData, landmarkType);

                if (landmarkPoint == null)
                {
                    // PXCMFaceData.LandmarksData.QueryPointIndex() failed.
                    return(false);
                }

                landmarkPoints.Add(landmarkType, landmarkPoint);
            }

            PXCMFaceData.ExpressionsData pxcmExpressionsData = pxcmFace.QueryExpressions();
            if (pxcmExpressionsData == null)
            {
                // PXCMFaceData.Face.QueryExpressions() failed.
                return(false);
            }

            animationTrigger.IsAnimationDataValid = true;

            PXCMCapture.Device.MirrorMode mirrorMode = PXCMCapture.Device.MirrorMode.MIRROR_MODE_DISABLED;

            PXCMCaptureManager pxcmCaptureManager = SenseToolkitManager.Instance.SenseManager.QueryCaptureManager();

            if (pxcmCaptureManager != null)
            {
                PXCMCapture.Device pxcmCaptureDevice = pxcmCaptureManager.QueryDevice();
                if (pxcmCaptureDevice != null)
                {
                    mirrorMode = pxcmCaptureDevice.QueryMirrorMode();
                }
            }

            animationTrigger.Animations.Clear();

            float faceHeight = landmarkPoints[PXCMFaceData.LandmarkType.LANDMARK_NOSE_TIP].image.y - landmarkPoints[PXCMFaceData.LandmarkType.LANDMARK_NOSE_TOP].image.y;

            float leftEyebrowUp  = GetNormalizedLandmarksDistance(landmarkPoints[PXCMFaceData.LandmarkType.LANDMARK_EYE_LEFT_CENTER].image.y, landmarkPoints[PXCMFaceData.LandmarkType.LANDMARK_EYEBROW_LEFT_CENTER].image.y, OPTIMAL_RELATIVE_FACE_HEIGHT, faceHeight, EYEBROW_UP_INITIAL_DISTANCE, OPTIMAL_EYEBROW_UP_MAX_DISTANCE, NORMALIZE_MAX_FACIAL_EXPRESSION_VALUE, true);
            float rightEyebrowUp = GetNormalizedLandmarksDistance(landmarkPoints[PXCMFaceData.LandmarkType.LANDMARK_EYE_RIGHT_CENTER].image.y, landmarkPoints[PXCMFaceData.LandmarkType.LANDMARK_EYEBROW_RIGHT_CENTER].image.y, OPTIMAL_RELATIVE_FACE_HEIGHT, faceHeight, EYEBROW_UP_INITIAL_DISTANCE, OPTIMAL_EYEBROW_UP_MAX_DISTANCE, NORMALIZE_MAX_FACIAL_EXPRESSION_VALUE, true);

            float leftEyeClose  = GetNormalizedLandmarksDistance(landmarkPoints[PXCMFaceData.LandmarkType.LANDMARK_EYELID_LEFT_BOTTOM].image.y, landmarkPoints[PXCMFaceData.LandmarkType.LANDMARK_EYELID_LEFT_TOP].image.y, OPTIMAL_RELATIVE_FACE_HEIGHT, faceHeight, EYE_CLOSE_INITIAL_DISTANCE, OPTIMAL_EYE_CLOSE_MAX_DISTANCE, NORMALIZE_MAX_FACIAL_EXPRESSION_VALUE, true);
            float rightEyeClose = GetNormalizedLandmarksDistance(landmarkPoints[PXCMFaceData.LandmarkType.LANDMARK_EYELID_RIGHT_BOTTOM].image.y, landmarkPoints[PXCMFaceData.LandmarkType.LANDMARK_EYELID_RIGHT_TOP].image.y, OPTIMAL_RELATIVE_FACE_HEIGHT, faceHeight, EYE_CLOSE_INITIAL_DISTANCE, OPTIMAL_EYE_CLOSE_MAX_DISTANCE, NORMALIZE_MAX_FACIAL_EXPRESSION_VALUE, true);

            if (mirrorMode == PXCMCapture.Device.MirrorMode.MIRROR_MODE_HORIZONTAL)
            {
                animationTrigger.Animations.Add(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_BROW_RAISER_LEFT.ToString(), rightEyebrowUp);
                animationTrigger.Animations.Add(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_BROW_RAISER_RIGHT.ToString(), leftEyebrowUp);

                animationTrigger.Animations.Add(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_EYES_CLOSED_LEFT.ToString(), rightEyeClose);
                animationTrigger.Animations.Add(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_EYES_CLOSED_RIGHT.ToString(), leftEyeClose);
            }
            else
            {
                animationTrigger.Animations.Add(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_BROW_RAISER_LEFT.ToString(), leftEyebrowUp);
                animationTrigger.Animations.Add(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_BROW_RAISER_RIGHT.ToString(), rightEyebrowUp);

                animationTrigger.Animations.Add(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_EYES_CLOSED_LEFT.ToString(), leftEyeClose);
                animationTrigger.Animations.Add(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_EYES_CLOSED_RIGHT.ToString(), rightEyeClose);
            }

            // Instead of LANDMARK_LOWER_LIP_CENTER, we need landmark 51 (lower lip upper center)
            // Instead of LANDMARK_UPPER_LIP_CENTER, we need landmark 47 (upper lip lower center)
            animationTrigger.Animations.Add(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_MOUTH_OPEN.ToString(), GetNormalizedLandmarksDistance(landmarkPoints[PXCMFaceData.LandmarkType.LANDMARK_LOWER_LIP_CENTER].image.y, landmarkPoints[PXCMFaceData.LandmarkType.LANDMARK_UPPER_LIP_CENTER].image.y, OPTIMAL_RELATIVE_FACE_HEIGHT, faceHeight, MOUTH_OPEN_INITIAL_DISTANCE, OPTIMAL_MOUTH_OPEN_MAX_DISTANCE, NORMALIZE_MAX_FACIAL_EXPRESSION_VALUE, true));

            PXCMFaceData.ExpressionsData.FaceExpressionResult pxcmFaceExpressionResult = new PXCMFaceData.ExpressionsData.FaceExpressionResult();

            if (pxcmExpressionsData.QueryExpression(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_SMILE, out pxcmFaceExpressionResult))
            {
                animationTrigger.Animations.Add(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_SMILE.ToString(), (float)pxcmFaceExpressionResult.intensity);
            }
            else
            {
                // Error querying expression: EXPRESSION_SMILE.
                return(false);
            }

            return(true);
        }
Example #11
0
        public void SimplePipeline()
        {
            bool             sts = true;
            PXCMSenseManager pp  = form.session.CreateSenseManager();

            if (pp == null)
            {
                throw new Exception("Failed to create sense manager");
            }
            disconnected = false;

            /* Set Source & Profile Index */
            PXCMCapture.DeviceInfo info = null;
            if (this.form.GetRecordState())
            {
                pp.captureManager.SetFileName(this.form.GetFileName(), true);
                form.PopulateDeviceMenu();
                if (this.form.Devices.TryGetValue(this.form.GetCheckedDevice(), out info))
                {
                    pp.captureManager.FilterByDeviceInfo(info);
                }
            }
            else if (this.form.GetPlaybackState())
            {
                pp.captureManager.SetFileName(this.form.GetFileName(), false);
            }
            else
            {
                if (this.form.Devices.TryGetValue(this.form.GetCheckedDevice(), out info))
                {
                    pp.captureManager.FilterByDeviceInfo(info);
                }
            }

            /* Set Module */
            pp.EnableEmotion(form.GetCheckedModule());

            /* Initialization */
            form.UpdateStatus("Init Started");

            PXCMSenseManager.Handler handler = new PXCMSenseManager.Handler()
            {
                //GZ onModuleQueryProfile = OnModuleQueryProfile
            };

            if (pp.Init(handler) >= pxcmStatus.PXCM_STATUS_NO_ERROR)
            {
                form.UpdateStatus("Streaming");
                this.timer = new FPSTimer(form);
                PXCMCaptureManager captureManager = pp.QueryCaptureManager();
                if (captureManager == null)
                {
                    throw new Exception("Failed to query capture manager");
                }
                PXCMCapture.Device device = captureManager.QueryDevice();

                if (device != null && !this.form.GetPlaybackState())
                {
                    device.SetDepthConfidenceThreshold(7);
                }
                //GZ device.SetProperty(PXCMCapture.Device.Property.PROPERTY_DEPTH_CONFIDENCE_THRESHOLD, 7);

                while (!form.stop)
                {
                    if (pp.AcquireFrame(true) < pxcmStatus.PXCM_STATUS_NO_ERROR)
                    {
                        break;
                    }
                    if (!DisplayDeviceConnection(!pp.IsConnected()))
                    {
                        /* Display Results */
                        PXCMEmotion ft = pp.QueryEmotion();
                        if (ft == null)
                        {
                            pp.ReleaseFrame();
                            continue;
                        }



                        //GZ DisplayPicture(pp.QueryImageByType(PXCMImage.ImageType.IMAGE_TYPE_COLOR));
                        PXCMCapture.Sample sample = pp.QueryEmotionSample();
                        if (sample == null)
                        {
                            pp.ReleaseFrame();
                            continue;
                        }

                        DisplayPicture(sample.color);

                        DisplayLocation(ft);

                        form.UpdatePanel();
                    }
                    pp.ReleaseFrame();
                }
            }
            else
            {
                form.UpdateStatus("Init Failed");
                sts = false;
            }

            pp.Close();
            pp.Dispose();
            if (sts)
            {
                form.UpdateStatus("Stopped");
            }
        }
Example #12
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;
        }
Example #13
0
        public void SimplePipeline()
        {
            PXCMSenseManager pp = m_form.Session.CreateSenseManager();

            if (pp == null)
            {
                throw new Exception("PXCMSenseManager null");
            }

            PXCMCaptureManager captureMgr = pp.captureManager;

            if (captureMgr == null)
            {
                throw new Exception("PXCMCaptureManager null");
            }

            var selectedRes = m_form.GetCheckedColorResolution();

            if (selectedRes != null)
            {
                // Set active camera
                PXCMCapture.DeviceInfo deviceInfo;
                m_form.Devices.TryGetValue(m_form.GetCheckedDevice(), out deviceInfo);
                captureMgr.FilterByDeviceInfo(m_form.GetCheckedDeviceInfo());

                // activate filter only live/record mode , no need in playback mode
                var set = new PXCMCapture.Device.StreamProfileSet
                {
                    color =
                    {
                        frameRate = selectedRes.Item2,
                        imageInfo =
                        {
                            format = selectedRes.Item1.format,
                            height = selectedRes.Item1.height,
                            width  = selectedRes.Item1.width
                        }
                    }
                };
            }

            // Set Module
            pp.EnableFace();
            PXCMFaceModule faceModule = pp.QueryFace();

            if (faceModule == null)
            {
                Debug.Assert(faceModule != null);
                return;
            }

            PXCMFaceConfiguration moduleConfiguration = faceModule.CreateActiveConfiguration();

            if (moduleConfiguration == null)
            {
                Debug.Assert(moduleConfiguration != null);
                return;
            }

            var checkedProfile = m_form.GetCheckedProfile();
            var mode           = m_form.FaceModesMap.First(x => x.Value == checkedProfile).Key;

            moduleConfiguration.SetTrackingMode(mode);

            moduleConfiguration.strategy = PXCMFaceConfiguration.TrackingStrategyType.STRATEGY_RIGHT_TO_LEFT;

            PXCMFaceConfiguration.ExpressionsConfiguration econfiguration = moduleConfiguration.QueryExpressions();
            if (econfiguration == null)
            {
                throw new Exception("ExpressionsConfiguration null");
            }
            econfiguration.properties.maxTrackedFaces = 4; //Expressionの最大認識量

            econfiguration.EnableAllExpressions();
            //if (m_form.IsExpressionsEnabled())
            //{
            econfiguration.Enable(); //Expressionsの強制有効化
            //}
            moduleConfiguration.EnableAllAlerts();
            moduleConfiguration.SubscribeAlert(FaceAlertHandler);

            pxcmStatus applyChangesStatus = moduleConfiguration.ApplyChanges();

            m_form.UpdateStatus("Init Started", MainForm.Label.StatusLabel);
            m_form.UpdateStatus("カメラ起動中", MainForm.Label.ReportLabel);

            if (applyChangesStatus < pxcmStatus.PXCM_STATUS_NO_ERROR || pp.Init() < pxcmStatus.PXCM_STATUS_NO_ERROR)
            {
                m_form.UpdateStatus("Init Failed", MainForm.Label.StatusLabel);
                m_form.UpdateStatus("設定エラー:メニューから適切な設定をしてください。", MainForm.Label.ReportLabel);
            }
            else
            {
                using (PXCMFaceData moduleOutput = faceModule.CreateOutput())
                {
                    Debug.Assert(moduleOutput != null);
                    PXCMCapture.Device.StreamProfileSet profiles;
                    PXCMCapture.Device device = captureMgr.QueryDevice();

                    if (device == null)
                    {
                        m_form.UpdateStatus("カメラを接続してください。", MainForm.Label.ReportLabel);
                        throw new Exception("device null");
                    }

                    device.QueryStreamProfileSet(PXCMCapture.StreamType.STREAM_TYPE_DEPTH, 0, out profiles);
                    CheckForDepthStream(profiles, faceModule);

                    m_form.UpdateStatus("Streaming", MainForm.Label.StatusLabel);
                    m_timer = new FPSTimer(m_form);

                    while (!m_form.Stopped)
                    {
                        if (pp.AcquireFrame(true) < pxcmStatus.PXCM_STATUS_NO_ERROR)
                        {
                            break;
                        }
                        var isConnected = pp.IsConnected();
                        DisplayDeviceConnection(isConnected);
                        if (isConnected)
                        {
                            var sample = pp.QueryFaceSample();
                            if (sample == null)
                            {
                                pp.ReleaseFrame();
                                continue;
                            }
                            switch (mode)
                            {
                            case PXCMFaceConfiguration.TrackingModeType.FACE_MODE_IR:
                                if (sample.ir != null)
                                {
                                    DisplayPicture(sample.ir);
                                }
                                break;

                            default:
                                DisplayPicture(sample.color);
                                break;
                            }

                            moduleOutput.Update();
                            PXCMFaceConfiguration.RecognitionConfiguration recognition = moduleConfiguration.QueryRecognition();
                            if (recognition == null)
                            {
                                pp.ReleaseFrame();
                                continue;
                            }

                            m_form.DrawGraphics(moduleOutput);
                            m_form.UpdatePanel();
                        }
                        pp.ReleaseFrame();
                    }
                }

                //             moduleConfiguration.UnsubscribeAlert(FaceAlertHandler);
                //             moduleConfiguration.ApplyChanges();
                m_form.UpdateStatus("Stopped", MainForm.Label.StatusLabel);
            }
            moduleConfiguration.Dispose();
            pp.Close();
            pp.Dispose();
        }