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.運行結果如下: