1988博客园

无需羡慕,不需狗血,耐得住寂寞,经得起推敲,我们自会拥有最有安全感的人生。

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

   1.在WPF界面上添加的控件

 <StackPanel Orientation="Horizontal">
            <Image x:Name="DepthImage" MouseLeftButtonUp="DepthImage_MouseLeftButtonUp" Width="512" Height="424"/>
            <TextBlock x:Name="PixelDepth" FontSize="48" HorizontalAlignment="Right"/>           
        </StackPanel>

 

2.后台代码如下:

     private KinectSensor sensor;
        private DepthFrameReader depthReader;
        private FrameDescription depthDescription;
        private WriteableBitmap depthBitmap;
        private Int32Rect depthRect;
        private int depthStride;
        ushort[] pixelData;

        public MainWindow()
        {
            InitializeComponent();
            sensor = KinectSensor.GetDefault();
            depthReader = sensor.DepthFrameSource.OpenReader();
            depthReader.FrameArrived += depthFrame_FrameArrived;
            depthDescription = sensor.DepthFrameSource.FrameDescription;
            //位图初始化,宽度,高度,96.0表示分辨率,像素格式
            depthBitmap = new WriteableBitmap(depthDescription.Width, depthDescription.Height, 96.0, 96.0, PixelFormats.Gray16, null);
            //存放图像像素的矩形框
            depthRect = new Int32Rect(0, 0, depthBitmap.PixelWidth, depthBitmap.PixelHeight);
            //存放深度图像的字节数组的长度=帧长度*帧高度
            pixelData = new ushort[depthDescription.LengthInPixels];
            //步长:宽度*2(字节/像素)
            depthStride = depthDescription.Width * 2;
            DepthImage.Source = depthBitmap;
            sensor.Open();
        }

        private void depthFrame_FrameArrived(object sender, DepthFrameArrivedEventArgs e)
        {
            using (DepthFrame depthFrame = e.FrameReference.AcquireFrame())
            {
                if (depthFrame != null)
                {
                    depthFrame.CopyFrameDataToArray(pixelData);
                    depthBitmap.WritePixels(depthRect, pixelData, depthStride, 0);
                }
            }
        }

        private void DepthImage_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Point p = e.GetPosition(DepthImage);
            if (pixelData != null && pixelData.Length > 0)
            {
                //计算出是第多少个像素点
                Int32 pixelIndex = (Int32)(p.X + ((Int32)p.Y * depthDescription.Width));
                Int32 depth = pixelData[pixelIndex] >> 3; //前三位是游戏者索引,向右移3位,剩下的才是深度值
                Int32 depthInches = (Int32)(depth * 0.0393700787);
                Int32 depthFt = depthInches / 12;
                depthInches = depthInches % 12;
                //官方给出的能测深度范围为:0.5-4.5m
                PixelDepth.Text = String.Format("\n深度为:{0}mm~{1}'{2}\n坐标为:({3},{4})", depth, depthFt, depthInches,p.X,p.Y);
            }
        }

3.值得注意的是:

Image控制的大小最好固定好,防止鼠标点击事件的范围超出图像边界,而出现异常

 

4.运行结果如下:

 

posted on 2016-11-14 16:48  1988kxj  阅读(1775)  评论(1编辑  收藏  举报