Matthias Shapiro

I need fewer hobbies

Get Started with Kinect For Windows (WPF)

Watching the Kinect for Windows v2 Jump Start. The code that they use in the videos is for Windows 8 apps but I’m trying to build my app in WPF. The problem is that WriteableBitmap for Windows 8 is substantially different from WriteableBitmap for WPF.

So here the WPF code for the first big demo… getting an infrared frame.

IRFrameBasics

The XAML needs to have just the image, but I put in a button to start reading the sensor

<Button Content="Start" Click="Button_Click" 
        VerticalAlignment="Top" />
<Image Name="image" Width="512" Height="424" 
    HorizontalAlignment="Center" VerticalAlignment="Center" />

The C# will handle the senor initiation and the frame reading. Then it will grab the pixel data and turn it into a WriteableBitmap that acts as the source of our Image.

private void Button_Click(object sender, RoutedEventArgs e)
{
    GetInfraredFrame();
}

KinectSensor sensor;
InfraredFrameReader irReader;
ushort[] irData;
byte[] irDataConverted;
WriteableBitmap irBitmap;

public void GetInfraredFrame()
{
    // Set up the sensor and reader
    sensor = KinectSensor.GetDefault();
    irReader = sensor.InfraredFrameSource.OpenReader();
    FrameDescription fd = sensor.InfraredFrameSource.FrameDescription;
    irData = new ushort[fd.LengthInPixels];
    irDataConverted = new byte[fd.LengthInPixels * 4];
    irBitmap = new WriteableBitmap(fd.Width, fd.Height, 96, 96, PixelFormats.Bgr32, null);
    image.Source = irBitmap;
    sensor.Open();
    irReader.FrameArrived += irReader_FrameArrived;
}

void irReader_FrameArrived(object sender, InfraredFrameArrivedEventArgs e)
{
    using (InfraredFrame irFrame = e.FrameReference.AcquireFrame()) 
    {
        if (irFrame != null)
        {
            irFrame.CopyFrameDataToArray(irData);

            double intensitySum = 0;
                    
            for (int i = 0; i < irData.Length; i++)
            {
                byte intensity = (byte)(irData[i] >> 8);
                irDataConverted[i * 4] = intensity;
                irDataConverted[i * 4 + 1] = intensity;
                irDataConverted[i * 4 + 2] = intensity;
                irDataConverted[i * 4 + 3] = intensity;
                intensitySum += (double)intensity;
            }
            Int32Rect rect = new Int32Rect(0,0, (int)irBitmap.Width, (int)irBitmap.Height);
            int stride = (int)irBitmap.Width * 4;
            irBitmap.WritePixels(rect, irDataConverted, stride, 0);
        }                
    }
}

 

This entry was posted in Windows Phone and tagged , . Bookmark the permalink.

One Response to Get Started with Kinect For Windows (WPF)

  1. Pingback: Dew Drop – January 23, 2015 (#1939) | Morning Dew

Leave a Comment

Your email address will not be published.