Search code examples
visual-studiokinectkinect-sdk

Kinect Record Only When One Body/Skeleton Is in the Frame


I need to write a program that records the frames, but only when one skeleton/body is in the frame. I looked at the bodyCount method, but it always gives a value of 6 (useless). One thing I tried to do is shown below. This code basically shows the index at which the body being tracked is stored. But, I still can't figure out how to know if there is one or more bodies in the frame. I would really appreciate any help. Thanks in advance.

private void Reader_FrameArrived(object sender, BodyFrameArrivedEventArgs e){
   using (BodyFrame bodyFrame=e.FrameReference.AquireFrame()){
          if (bodyFrame!=null){
                if(this.bodies==null){
                this.bodies=new Body[bodyFrame.BodyCount];
                }
          body.Frame.GetAndRefreshBodyData(this.bodies) 

          for(int i=0; i<6;i++){
              if(this.bodies[i].IsTracked){
              Console.WriteLine("Tracked"+i)
               }
           }

      }

   }

}

Solution

  • Just check the IsTracked property of each body, and store the number of tracked skeleton in a single variable. If this number is equal to 1, there is just one single skeleton tracked, and you can start your recording.

        private Body[] bodies = null;
    
        [...]
    
        private void Reader_FrameArrived(object sender, BodyFrameArrivedEventArgs e)
        {
            bool dataReceived = false;
    
            using (BodyFrame bodyFrame = e.FrameReference.AcquireFrame())
            {
                if (bodyFrame != null)
                {
                    if (this.bodies == null)
                    {
                        this.bodies = new Body[bodyFrame.BodyCount];
                    }
    
                    // The first time GetAndRefreshBodyData is called, Kinect will allocate each Body in the array.
                    // As long as those body objects are not disposed and not set to null in the array,
                    // those body objects will be re-used.
                    bodyFrame.GetAndRefreshBodyData(this.bodies);
                    dataReceived = true;
                }
            }
    
            if (dataReceived)
            {
                int trackedBodyCount = 0;
                for (int i=0; i<this.bodies.Length; ++i)
                {
                    if(this.bodies[i].IsTracked) {
                        trackedBodyCount += 1;
                    }
                }
    
                if (trackedBodyCount == 1)
                {
                    // One skeleton is tracked
                }
            }
        }