Вы можете использовать StreamWriter
, инициализировать его по выбранному пути, затем для каждого кадра увеличивать счетчик кадров, записывать его в файл, записывать метку времени в файл, затем перебирать соединения и записывать их в файл. Я бы сделал это следующим образом:
using System.IO;
StreamWriter writer = new StreamWriter(@path);
int frames = 0;
...
void AllFramesReady(object sender, AllFramesReadyEventArgs e)
{
frames++;
using (SkeletonFrame sFrame = e.OpenSkeletonFrameData())
{
if (sFrame == null)
return;
skeletonFrame.CopySkeletonDataTo(skeletons);
Skeleton skeleton = (from s in skeletons
where s.TrackingState == SkeletonTrackingState.Tracked
select s);
if (skeleton == null)
return;
if (skeleton.TrackingState == SkeletonTrackingState.Tracked)
{
writer.Write("{0} {1}@", frames, timestamp);//I dont know how you want to do this
foreach (Joint joint in skeleton.Joints)
{
writer.Write(joint.Position.X + "," + joint.Position.Y + "," joint.Position.Z + ",");
}
writer.Write(Environment.NewLine);
}
}
}
Затем, чтобы прочитать из файла:
StreamReader reader = new StreamReader(@path);
int frame = -1;
JointCollection joints;
...
string[] lines = reader.ReadAllLines();
...
void AllFramesReady(object sender, AllFramesReadyEventArgs e)
{
canvas.Children.Clear();
string[] coords = lines[frame].Split('@')[1].Split(',');
int jointIndex = 0;
for (int i = 0; i < coords.Length; i += 3)
{
joints[jointIndex].Position.X = int.Parse(coords[i]);
joints[jointIndex].Position.Y = int.Parse(coords[i + 1]);
joints[jointIndex].Position.X = int.Parse(coords[i + 2]);
jointIndex++;
}
DepthImageFrame depthFrame = e.OpenDepthImageFrame();
canvas.Children.Add(GetBodySegment(joints, brush, new JointType[] { JointType.HipCenter, JointType.Spine, JointType.ShoulderCenter, JointType.Head }, depthFrame, canvas));
canvas.Children.Add(GetBodySegment(joints, brush, new JointType[] { JointType.ShoulderCenter, JointType.ShoulderLeft, JointType.ElbowLeft, JointType.WristLeft, JointType.HandLeft }, depthFrame, canvas));
canvas.Children.Add(GetBodySegment(joints, brush, new JointType[] { JointType.ShoulderCenter, JointType.ShoulderRight, JointType.ElbowRight, JointType.WristRight, JointType.HandRight }, depthFrame, canvas));
canvas.Children.Add(GetBodySegment(joints, brush, new JointType[] { JointType.HipCenter, JointType.HipLeft, JointType.KneeLeft, JointType.AnkleLeft, JointType.FootLeft }, depthFrame, canvas));
canvas.Children.Add(GetBodySegment(joints, brush, new JointType[] { JointType.HipCenter, JointType.HipRight, JointType.KneeRight, JointType.AnkleRight, JointType.FootRight }, depthFrame, canvas));
depthFrame.Dispose();
frame++;
}
Point GetDisplayPosition(Joint joint, DepthImageFrame depthFrame, Canvas skeleton)
{
float depthX, depthY;
KinectSensor sensor = KinectSensor.KinectSensors[0];
DepthImageFormat depthImageFormat = sensor.DepthStream.Format;
DepthImagePoint depthPoint = sensor.CoordinateMapper.MapSkeletonPointToDepthPoint(joint.Position, depthImageFormat);
depthX = depthPoint.X;
depthY = depthPoint.Y;
depthX = Math.Max(0, Math.Min(depthX * 320, 320));
depthY = Math.Max(0, Math.Min(depthY * 240, 240));
int colorX, colorY;
ColorImagePoint colorPoint = sensor.CoordinateMapper.MapDepthPointToColorPoint(depthImageFormat, depthPoint, ColorImageFormat.RgbResolution640x480Fps30);
colorX = colorPoint.X;
colorY = colorPoint.Y;
return new System.Windows.Point((int)(skeleton.Width * colorX / 640.0), (int)(skeleton.Height * colorY / 480));
}
Polyline GetBodySegment(Joint[] joints, Brush brush, JointType[] ids, DepthImageFrame depthFrame, Canvas canvas)
{
PointCollection points = new PointCollection(ids.Length);
for (int i = 0; i < ids.Length; ++i)
{
points.Add(GetDisplayPosition(joints[i], depthFrame, canvas));
}
Polyline polyline = new Polyline();
polyline.Points = points;
polyline.Stroke = brush;
polyline.StrokeThickness = 5;
return polyline;
}
Конечно, это работает только в wpf. Вам просто нужно перейти от использования кода:
DepthImageFrame depthFrame = e.OpenDepthImageFrame();
canvas.Children.Add(GetBodySegment(joints, brush, new JointType[] { JointType.HipCenter, JointType.Spine, JointType.ShoulderCenter, JointType.Head }, depthFrame, canvas));
canvas.Children.Add(GetBodySegment(joints, brush, new JointType[] { JointType.ShoulderCenter, JointType.ShoulderLeft, JointType.ElbowLeft, JointType.WristLeft, JointType.HandLeft }, depthFrame, canvas));
canvas.Children.Add(GetBodySegment(joints, brush, new JointType[] { JointType.ShoulderCenter, JointType.ShoulderRight, JointType.ElbowRight, JointType.WristRight, JointType.HandRight }, depthFrame, canvas));
canvas.Children.Add(GetBodySegment(joints, brush, new JointType[] { JointType.HipCenter, JointType.HipLeft, JointType.KneeLeft, JointType.AnkleLeft, JointType.FootLeft }, depthFrame, canvas));
canvas.Children.Add(GetBodySegment(joints, brush, new JointType[] { JointType.HipCenter, JointType.HipRight, JointType.KneeRight, JointType.AnkleRight, JointType.FootRight }, depthFrame, canvas));
depthFrame.Dispose();
Чтобы узнать, как анимационный образец анимирует модель, вы можете даже создать новый Skeleton
и скопировать joints
в Skeleton.Joints
, а затем просто передать этот скелет как «обнаруженный» скелет. Обратите внимание, что вам потребуется изменить любые другие необходимые переменные, необходимые для функций, используемых в этом примере. Я не знаком с примером, поэтому не могу назвать конкретные имена методов, но вы можете просто заменить глобальный Skeleton
на тот, который вы создали в начале, и обновлять каждый кадр. Поэтому я бы рекомендовал это:
//in the game class (AvateeringXNA.cs)
StreamReader reader = new StreamReader(@path);
int frame = -1;
JointCollection joints;
Skeleton recorded = new Skeleton();
...
string[] lines = reader.ReadAllLines();
...
void Update(...)
{
string[] coords = lines[frame].Split('@')[1].Split(',');
int jointIndex = 0;
for (int i = 0; i < coords.Length; i += 3)
{
joints[jointIndex].Position.X = int.Parse(coords[i]);
joints[jointIndex].Position.Y = int.Parse(coords[i + 1]);
joints[jointIndex].Position.X = int.Parse(coords[i + 2]);
jointIndex++;
}
recorded.Joints = joints;
...
//preform necessary methods, except with recorded skeleton instead of detected, I think it is:
this.animator.CopySkeleton(recorded);
this.animator.FloorClipPlane = skeletonFrame.FloorClipPlane;
// Reset the filters if the skeleton was not seen before now
if (this.skeletonDetected == false)
{
this.animator.Reset();
}
this.skeletonDetected = true;
this.animator.SkeletonVisible = true;
...
frame++;
}
ИЗМЕНИТЬ
Когда вы читаете начальную плоскость отсечения пола (clipPlanes[0]
), она получает всю информацию о кадре до первого пробела. См. ниже, чтобы увидеть, как он будет разделяться и как я буду его читать:
var newFloorClipPlane = Tuple.Create(Single.Parse(clipPlanes[2]), Single.Parse(clipPlanes[3]), Single.Parse(clipPlanes[4]), Single.Parse(clipPlanes[5]));
Вот как вы размещаете кадры:
frame# timestam@joint1Posx,joint1posy,joint1posz,...jointNPosx,jointNposy,jointNposz floorX floorY floorZ floorW
Вот массив, созданный `.Split(' ')
["frame#", "timestam@joint1Posx,joint1posy,joint1posz,...jointNPosx,jointNposy,jointNposz", "floorX", "floorY", "floorZ", "floorW"]
Следовательно, с примером ввода:
00000002 10112@10,10,10... 11 12 13 14
С вашим кодом вы получите:
[2, 10112101010..., 11, 12]
С исправленными индексами из моего кода:
[11, 12, 13, 14]
Поместите эту строку в консольное приложение очень быстро и посмотрите, что она выводит:
Console.WriteLine(Convert.ToSingle("10,10"));
Вывод 1010
Для того, что вы пытаетесь выполнить, это создает неправильную плоскость отсечения пола. Вам нужны правильные индексы для того, чего вы пытаетесь достичь.
примечание: я изменил Convert.ToSingle
на Single.Parse
, потому что это лучшая практика, и в трассировке стека они оба выполняют одни и те же функции.
person
Liam McInroy
schedule
15.02.2014