Skip to content

Instantly share code, notes, and snippets.

@kaorun55
Created August 1, 2012 04:05
Show Gist options
  • Save kaorun55/3223539 to your computer and use it in GitHub Desktop.
Save kaorun55/3223539 to your computer and use it in GitHub Desktop.
Kinect&OpenCV
using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Microsoft.Kinect;
using OpenCvSharp;
using OpenCvSharp.Extensions;
namespace KinectOpenCV
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
private WriteableBitmap bitmap;
private Int32Rect bitmapRect;
private int stride;
public MainWindow()
{
InitializeComponent();
try {
var kinect = KinectSensor.KinectSensors[0];
kinect.ColorStream.Enable();
kinect.ColorFrameReady +=
new EventHandler<ColorImageFrameReadyEventArgs>( kinect_ColorFrameReady );
kinect.Start();
// 本来のフォーマットはBgr32だけど、OpenCVSharpのToIplImageが対応してないので、Bgra32にした
// ただし、ColorStreamのα値相当のデータは0なので、WPF上には表示されない
// Bgr32にすると、WPF上には表示されるが、OpenCVのほうはエラーになる
bitmap = new WriteableBitmap( kinect.ColorStream.FrameWidth, kinect.ColorStream.FrameHeight,
96, 96, PixelFormats.Bgra32, null );
//96, 96, PixelFormats.Bgr32, null );
bitmapRect = new Int32Rect( 0, 0,
kinect.ColorStream.FrameWidth, kinect.ColorStream.FrameHeight );
stride = kinect.ColorStream.FrameWidth * kinect.ColorStream.FrameBytesPerPixel;
image.Source = bitmap;
}
catch ( Exception ex ) {
MessageBox.Show( ex.Message );
Close();
}
}
void kinect_ColorFrameReady( object sender, ColorImageFrameReadyEventArgs e )
{
try {
using ( var frame = e.OpenColorImageFrame() ) {
if ( frame != null ) {
byte[] pixel = new byte[frame.PixelDataLength];
frame.CopyPixelDataTo( pixel );
bitmap.WritePixels( bitmapRect, pixel, stride, 0 );
// OpenCvSharp.Extensionsにある、WritableBitmapからIplImageへの変換関数
IplImage image = bitmap.ToIplImage();
Cv.ShowImage( "OpenCV", image );
}
}
}
catch ( Exception ) {
// Bgr32にしたときは「IplImage image = bitmap.ToIplImage();」でフォーマットエラーの例外が出る
// http://code.google.com/p/opencvsharp/source/browse/trunk/2.3.1/OpenCvSharp.Extensions/WriteableBitmapConverter.cs
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment