private void ColorImageReady(object sender, ColorImageFrameReadyEventArgs e)
{
using (ColorImageFrame imageFrame = e.OpenColorImageFrame())
{
if (imageFrame != null)
{
// We need to detect if the format has changed.
bool haveNewFormat = this.lastImageFormat != imageFrame.Format;
bool convertToRgb = false;
int bytesPerPixel = imageFrame.BytesPerPixel;
if (imageFrame.Format == ColorImageFormat.RawBayerResolution640x480Fps30 ||
imageFrame.Format == ColorImageFormat.RawBayerResolution1280x960Fps12)
{
convertToRgb = true;
bytesPerPixel = 4;
}
if (haveNewFormat)
{
if (convertToRgb)
{
this.rawPixelData = new byte[imageFrame.PixelDataLength];
this.pixelData = new byte[bytesPerPixel * imageFrame.Width * imageFrame.Height];
}
else
{
this.pixelData = new byte[imageFrame.PixelDataLength];
}
}
if (convertToRgb)
{
imageFrame.CopyPixelDataTo(this.rawPixelData);
ConvertBayerToRgb32(imageFrame.Width, imageFrame.Height);
}
else
{
imageFrame.CopyPixelDataTo(this.pixelData);
}
// A WriteableBitmap is a WPF construct that enables resetting the Bits of the image.
// This is more efficient than creating a new Bitmap every frame.
if (haveNewFormat)
{
PixelFormat format = PixelFormats.Bgr32;
if (imageFrame.Format == ColorImageFormat.InfraredResolution640x480Fps30)
{
format = PixelFormats.Gray16;
}
kinectColorImage.Visibility = Visibility.Visible;
this.outputImage = new WriteableBitmap(
imageFrame.Width,
imageFrame.Height,
96, // DpiX
96, // DpiY
format,
null);
this.kinectColorImage.Source = this.outputImage;
}
this.outputImage.WritePixels(
new Int32Rect(0, 0, imageFrame.Width, imageFrame.Height),
this.pixelData,
imageFrame.Width * bytesPerPixel,
0);
this.lastImageFormat = imageFrame.Format;
UpdateFrameRate();
}
}
}
}