我试图从2个Kinect传感器获得骨骼关节的X,Y,Z位置。到目前为止,我有一个简单的表格,有2个按钮和6个标签。点击第一个按钮,我想在label1,2,3中显示右手的x,y,z位置。同样我想用第二个按钮,但第二个按钮设备。
它与一个Kinect很好地工作,但当我为第二个Kinect添加代码时,NullReferenceException被抛出。有人可以告诉我,我有什么不对吗? 谢谢。
编辑:
观看窗口:
sensor.SkeletonStream.Enable(); ' sensor.SkeletonStream'为空
异常消息:未将对象引用设置为对象的实例。
CODE
public partial class Form1 : Form
{
Skeleton[] skeletons;
Skeleton[] skeletons2;
public Form1()
{
InitializeComponent();
// First Kinect Device
KinectSensor sensor = KinectSensor.KinectSensors[0];
sensor.SkeletonStream.Enable(); // Here is the exception thrown
sensor.SkeletonFrameReady += new EventHandler<SkeletonFrameReadyEventArgs>(SensorSkeletonFrameReady);
sensor.Start();
// Second Kinect Device
KinectSensor sensor2 = KinectSensor.KinectSensors[1];
sensor2.SkeletonStream.Enable();
sensor2.SkeletonFrameReady += new EventHandler<SkeletonFrameReadyEventArgs>(SensorSkeletonFrameReady2);
sensor2.Start();
}
private void SensorSkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
{
skeletons = new Skeleton[0];
using (SkeletonFrame skeletonFrame = e.OpenSkeletonFrame())
{
if (skeletonFrame != null)
{
skeletons = new Skeleton[skeletonFrame.SkeletonArrayLength];
skeletonFrame.CopySkeletonDataTo(skeletons);
}
}
}
private void SensorSkeletonFrameReady2(object sender, SkeletonFrameReadyEventArgs e)
{
skeletons2 = new Skeleton[0];
using (SkeletonFrame skeletonFrame2 = e.OpenSkeletonFrame())
{
if (skeletonFrame2 != null)
{
skeletons2 = new Skeleton[skeletonFrame2.SkeletonArrayLength];
skeletonFrame2.CopySkeletonDataTo(skeletons2);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
foreach(Skeleton skeleton in skeletons)
{
// get the joint
Joint rightHand = skeleton.Joints[JointType.HandRight];
// get the individual points of the right hand
double rightX = rightHand.Position.X;
double rightY = rightHand.Position.Y;
double rightZ = rightHand.Position.Z;
label1.Text = rightX.ToString();
label2.Text = rightY.ToString();
label3.Text = rightZ.ToString();
}
}
private void button2_Click(object sender, EventArgs e)
{
foreach (Skeleton skeleton in skeletons2)
{
// get the joint
Joint rightHand = skeleton.Joints[JointType.HandRight];
// get the individual points of the right hand
double rightX = rightHand.Position.X;
double rightY = rightHand.Position.Y;
double rightZ = rightHand.Position.Z;
label4.Text = rightX.ToString();
label5.Text = rightY.ToString();
label6.Text = rightZ.ToString();
}
}
}
答案 0 :(得分:0)
这是因为您的sensor
对象为空。要修复,您应该检查传感器之前是否为空。这可以很容易地完成:
KinectSensor sensor = KinectSensor.KinectSensors[0];
if (sensor != null)
{
sensor.SkeletonStream.Enable(); // Here is the exception not thrown:)
sensor.SkeletonFrameReady += new EventHandler<SkeletonFrameReadyEventArgs>(SensorSkeletonFrameReady);
sensor.Start();
}
开发人员工具包还提供了如何遍历每个可用传感器并选择第一个非空传感器的优秀示例。
在C#6.0中,出于这个目的,会有一个safe navigation operator!
sensor?.SkeletonStream.Enable();