我正在为第一个 kinect 项目尝试一个基本的“hello world”应用程序,将视频数据流式传输到流中。代码在这里:https ://github.com/fschwiet/HelloKinect/blob/8803b6b959ee6dba5f9284b9e732fb11a897dea4/HelloKinect/ShowCameraCommand.cs
我发现我可以在循环中轮询帧数据,但我没有收到帧就绪事件。源代码如下。当 UsePolling 为真时,帧数据被发送到表单。当 UsePolling 为 false 时,有控制台输出“Hit return to exit”。表示一切都已运行,但从未收到任何事件。
我感觉这与 Windows 消息泵有关,我需要在警报状态下等待和/或泵出消息队列。我一直无法使它工作,但有人有任何提示吗?
public class ShowCameraCommand : ConsoleCommand
{
static private Form EchoForm;
private bool UsePolling;
public ShowCameraCommand()
{
this.IsCommand("show-camera");
this.HasOption("p", "Use polling to check frame data", v => UsePolling = true);
}
public override int Run(string[] remainingArguments)
{
var sensor = KinectSensor.KinectSensors.Where(s => s.Status == KinectStatus.Connected).FirstOrDefault();
if (sensor == null)
{
Console.WriteLine("Kinect was not detected");
Console.WriteLine();
return -1;
}
EchoForm = new Form();
EchoForm.Width = 640;
EchoForm.Height = 480;
EchoForm.Show();
sensor.ColorStream.Enable(ColorImageFormat.RawYuvResolution640x480Fps15);
if (!UsePolling)
{
sensor.ColorFrameReady += sensor_ColorFrameReady;
}
sensor.Start();
if (UsePolling)
{
Console.WriteLine("Use any key to exit.");
while (!Console.KeyAvailable)
{
using (var frame = sensor.ColorStream.OpenNextFrame(10 * 1000))
{
HandleFrame(frame);
}
Thread.Sleep(50);
}
}
else
{
Console.WriteLine("Hit return to exit.");
Console.ReadLine();
}
return 0;
}
void sensor_ColorFrameReady(object sender, ColorImageFrameReadyEventArgs e)
{
Console.WriteLine("Frame received");
using (ColorImageFrame frame = e.OpenColorImageFrame())
{
HandleFrame(frame);
}
}
private void HandleFrame(ColorImageFrame frame)
{
var bitmap = ImageToBitmap(frame);
using (var g = EchoForm.CreateGraphics())
{
g.DrawImage(bitmap, 0, 0);
Console.WriteLine("Frame drawn");
}
}
// http://stackoverflow.com/questions/10848190/convert-kinect-colorframe-to-bitmap
Bitmap ImageToBitmap(ColorImageFrame Image)
{
byte[] pixeldata = new byte[Image.PixelDataLength];
Image.CopyPixelDataTo(pixeldata);
Bitmap bmap = new Bitmap(Image.Width, Image.Height, PixelFormat.Format32bppRgb);
BitmapData bmapdata = bmap.LockBits(
new Rectangle(0, 0, Image.Width, Image.Height),
ImageLockMode.WriteOnly,
bmap.PixelFormat);
IntPtr ptr = bmapdata.Scan0;
Marshal.Copy(pixeldata, 0, ptr, Image.PixelDataLength);
bmap.UnlockBits(bmapdata);
return bmap;
}
}