Как записать кадры Leap Motion для отслеживания тремора рук в С#?

Я уже видел на Youtube информацию о распознавании тремора Leap Motion и начал создавать это приложение с использование Leap Motion для обработки сигналов в C#. У меня возникают проблемы на первом этапе. Я не знаю, как получить и записать несколько кадров движения рук в секунду. В этом случае я хочу записать его за 10 секунд. Я не знаю библиотеку, которую я должен использовать для записи этого.

надеюсь, кто-нибудь поможет мне объяснить и поделиться тем, как кодировать его на С#... спасибо

это код, который я пробовал, но я не собирал и не запускал его, поэтому я думаю, что он не работает. Может ли кто-нибудь проверить это для меня?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.Diagnostics;
using Leap;

namespace map3
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, ILeapEventDelegate
{

    private Controller controller = new Controller();
    Leap.Frame frame;

    //getting data from a frame
    HandList hands;
    PointableList pointables;
    FingerList fingers;
    ToolList tools;


    private LeapEventListener listener;
    private Gesture gesture = new Gesture();
    private String direction;
    Leap.Frame gestureFrame;
    Leap.Frame fingerFrame;

    private long timestamp;

    private Boolean isClosing = false;
    private Boolean isPlaying = false;

    private Int64 lastFrameID = 0;

    Thread finger_thread, gesture_thread;

    public MainWindow()
    {
        InitializeComponent();
        main_window.ResizeMode = ResizeMode.NoResize;

        this.controller = new Controller();
        this.listener = new LeapEventListener(this);
        controller.AddListener(listener);
        processFrame(frame);

        //get timestamp
        float framePeriod = controller.Frame(0).Timestamp - controller.Frame(1).Timestamp;
        lbl_debug.Content = "Gesture";
    }

    private void processFrame(Leap.Frame frame)
    {
        if (frame.Id == lastFrameID)
            return;
        lastFrameID = frame.Id;

       //for have an ID of an entity from a different frame
        Hand hand = frame.Hand(handID);
        Pointable pointable = frame.Pointable(pointableID);
        Finger finger = frame.Finger(fingerID);
        Tool tool = frame.Tool(toolID);

        Thread.Sleep(10000);

        //to save frame to file
        byte[] serializedFrame = frame.Serialize;
        System.IO.File.WriteAllBytes ("frame.data", serializedFrame);
    }

    public void Deserialize() //to read multiple frame  from the saved file
    {
        Controller leapController = new Controller();
        using (System.IO.BinaryReader br =
            new System.IO.BinaryReader(System.IO.File.Open("file.data", System.IO.FileMode.Open)))
        {
            while (br.BaseStream.Position < br.BaseStream.Length)
            {
                Int32 nextBlock = br.ReadInt32();
                byte[] frameData = br.ReadBytes(nextBlock);
                Leap.Frame newFrame = new Leap.Frame();
                newFrame.Deserialize(frameData);
            }
        }

    }

    private void btn_start_click(object sender, RoutedEventArgs e)
    {
        startDetect();
    }


    private void startDetect()
    {
        //maplayer.Play();
        if (controller.IsConnected)
        {
            Leap.Frame frame = controller.Frame(); //the latest frame
            Leap.Frame previous = controller.Frame(1); //the previous frame
        }
        isPlaying = true;
        btn_start.Content = FindResource("Start"); //connecting to gui
    }

    delegate void LeapEventDelegate(string EventName);
    public void LeapEventNotification(string EventName)
    {
        if (this.CheckAccess())
        {
            switch (EventName)
            {
                case "onInit":
                    Debug.WriteLine("Init");
                    break;
                case "onConnect":
                    this.connectHandler();
                    break;
                case "onFrame":
                    if (!this.isClosing)
                        this.processFrame(this.controller.Frame());
                    break;

            }
        }
        else
        {
            Dispatcher.Invoke(new LeapEventDelegate(LeapEventNotification), new object[] { EventName });
        }
    }

    void connectHandler()
    {
        this.controller.SetPolicy(Controller.PolicyFlag.POLICY_IMAGES);
        this.controller.EnableGesture(Gesture.GestureType.TYPE_SWIPE);
        this.controller.Config.SetFloat("Gesture.Swipe.MinLength", 200.0f);
        this.controller.Config.Save();
    }


    void MainWindow_Closing(object sender, EventArgs e)
    {
        this.isClosing = true;
        this.controller.RemoveListener(this.listener);
        this.controller.Dispose();
    }

    private void ListView_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
    {

    }

    public int handID { get; set; }

    public int pointableID { get; set; }

    public int toolID { get; set; }

    public int fingerID { get; set; }
}

public interface ILeapEventDelegate
{
    void LeapEventNotification(string EventName);
}

public class FrameListener : Listener
{
    public void onFrame(Controller controller)
    {
        Leap.Frame frame = controller.Frame();
        Leap.Frame previous = controller.Frame(1);
    }
}

public class LeapEventListener : Listener
{
    ILeapEventDelegate eventDelegate;

    public LeapEventListener(ILeapEventDelegate delegateObject)
    {
        this.eventDelegate = delegateObject;
    }
    public override void OnInit(Controller controller)
    {
        this.eventDelegate.LeapEventNotification("onInit");
    }
    public override void OnConnect(Controller controller)
    {
        controller.SetPolicy(Controller.PolicyFlag.POLICY_IMAGES);
        controller.EnableGesture(Gesture.GestureType.TYPE_SWIPE);
        this.eventDelegate.LeapEventNotification("onConnect");
    }

    public override void OnFrame(Controller controller)
    {
        this.eventDelegate.LeapEventNotification("onFrame");
    }
    public override void OnExit(Controller controller)
    {
        this.eventDelegate.LeapEventNotification("onExit");
    }
    public override void OnDisconnect(Controller controller)
    {
        this.eventDelegate.LeapEventNotification("onDisconnect");
    }

}

}

person RahmaFida    schedule 16.02.2016    source источник
comment
Покажи, что ты пробовал   -  person mumair    schedule 16.02.2016
comment
я отредактировал этот пост   -  person RahmaFida    schedule 16.02.2016
comment
Внутри LeapMotion SDK есть образец для записи движения вашей руки и воспроизведения. Я думаю, это то, что вы ищете. Я нашел их в C# на ресурсах unity3d.   -  person Chop Labalagun    schedule 31.05.2016


Ответы (1)


У меня была та же проблема, и я нашел следующее решение в Frame.cs.

Чтобы сериализовать кадр:

public byte[] Serialize
{
    get
    {
        BinaryFormatter bf = new BinaryFormatter();
        using (var ms = new MemoryStream())
        {
            bf.Serialize(ms, this);
            return ms.ToArray();
        }
    }
}

Чтобы десериализовать кадр:

public void Deserialize(byte[] arg)
{
    using (var ms = new MemoryStream())
    {
        BinaryFormatter bf = new BinaryFormatter();
        ms.Write(arg, 0, arg.Length);
        ms.Seek(0, SeekOrigin.Begin);
        Frame objArray = (Frame)bf.Deserialize(ms);
        this.Id = objArray.Id;
        this.Timestamp = objArray.Timestamp;
        this.CurrentFramesPerSecond = objArray.CurrentFramesPerSecond;
        this.InteractionBox = objArray.InteractionBox;
        this.Hands = objArray.Hands;
    }

}

Поэтому InteractionBox должен быть сериализуемым в InteractionBox.cs:

[System.Serializable]
public struct InteractionBox{...}

Проблема сохраняется, если вы используете файлы *.cs из исходной папки в проекте. Если вы хотите десериализовать фрейм в другом приложении, вам следует создать DLL из исходной папки с обновленным исходным кодом. Например. записывать кадры в одной программе и воспроизводить в другой.

csc /t:library /out:Leap.dll LeapC.cs Arm.cs Bone.cs CircularObjectBuffer.cs ClockCorrelator.cs Config.cs Connection.cs Controller.cs CopyFromLeapCExtensions.cs CopyFromOtherExtensions.cs CSharpExtensions.cs Device.cs DeviceList.cs DistortionData.cs DistortionDictionary.cs Events.cs FailedDevice.cs FailedDeviceList.cs Finger.cs Frame.cs Hand.cs IController.cs Image.cs ImageData.cs ImageFuture.cs InteractionBox.cs LeapQuaternion.cs LeapTransform.cs Logger.cs Matrix.cs MessageSeverity.cs ObjectPool.cs PendingImages.cs PooledObject.cs StructMarshal.cs TimeBracket.cs TransformExtensions.cs Vector.cs

Оригинальная LeapC.dll по-прежнему должна быть включена в соответствии с документацией SDK.

Надеюсь, это поможет.

person Sedowan    schedule 04.10.2019