1
import numpy as np
import pandas as pd
import matplotlib
# matplotlib.use("Agg")

from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.colors import cnames
from matplotlib import animation


t_start = 2   #start frame
t_end = 1711  #end frame

data = pd.read_csv('Sub6_cylinder0009_index_flex_processed.csv') 
df = data.loc[t_start:t_end,'FT1X':'CMC5Z']
 
df_minmax = pd.DataFrame(index=list('xyz'),columns=range(2))


for i in list('xyz'):
    c_max = df.max().max()
    c_min = df.min().min()
    df_minmax.loc[i] = np.array([c_min,c_max])

df_minmax = 3.3*df_minmax 


df.columns  = np.repeat(range(22),3) 

N_tag = int(df.shape[1]/3) # nr of tags used (all)

N_trajectories = N_tag

t = np.linspace(0,data.Time[t_end],df.shape[0])

x_t = np.zeros(shape=(N_tag,df.shape[0],3)) 

for tag in range(22):
 
    x_t[tag,:,:] = df[tag]

x_t = x_t[:, :, [0, 2, 1]]


fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1], projection='3d')
ax.axis('on')


#choose a different color for each trajectory
colors = plt.cm.jet(np.linspace(0, 1, N_trajectories))
# set up trajectory lines
lines = sum([ax.plot([], [], [], '-', c=c) for c in colors], [])
# set up points
pts = sum([ax.plot([], [], [], 'o', c=c) for c in colors], [])
#set up lines which create the stick figures

stick_defines = [
    (0, 13), 
    (13, 14),
    (14, 19),
    (1, 5), 
    (2, 6),
    (3, 7), 
    (4, 8), 
    (5, 9), 
    (6, 10),
    (7, 11),
    (8, 12),
    (9, 15),
    (10, 16),
    (11, 17),
    (12, 18),
    (18, 21),
    (15, 20) 
         
]

stick_lines = [ax.plot([], [], [], 'k-')[0] for _ in stick_defines]
print(stick_lines)
ax.set_xlim3d([np.nanmin(x_t[:, :, 0]), np.nanmax(x_t[:, :, 0])])
ax.set_ylim3d([np.nanmin(x_t[:, :, 1])-400, np.nanmax(x_t[:, :, 1])+400])
ax.set_zlim3d([np.nanmin(x_t[:, :, 2]), np.nanmax(x_t[:, :, 2])])
ax.set_xlabel('X [mm]')
ax.set_ylabel('Y [mm]')
ax.set_zlabel('Z [mm]')

# set point-of-view: specified by (altitude degrees, azimuth degrees)
#ax.view_init(30, 25)

# initialization function: plot the background of each frame
def init():
    for line, pt in zip(lines, pts):
        line.set_data(np.array([]), np.array([]))
        line.set_3d_properties(np.array([]))

        pt.set_data(np.array([]),np.array([]))
        pt.set_3d_properties(np.array([]))
    return lines + pts

# animation function.  This will be called sequentially with the frame number
def animate(i):
    
    i = (5 * i) % x_t.shape[1]

    for pt, xi in zip(pts, x_t):
        x, y, z = xi[:i].T 
        pt.set_data(x[-1:], y[-1:])
        pt.set_3d_properties(z[-1:])
        

    for stick_line, (sp, ep) in zip(stick_lines, stick_defines):
    stick_line._verts3d = x_t[[sp,ep], i, :].T.tolist()

    #ax.view_init(30, 0.3 * i)
    fig.canvas.draw()
    return lines + pts + stick_lines

anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=500, interval=30, blit=True, repeat=False)

# Save as mp4. This requires mplayer or ffmpeg to be installed
#anim.save('animation.mp4', progress_callback=lambda i, n: print(f'Saving frame {i} of {n}'))

plt.show()
anim.save('test.mp4', writer='ffmpeg')

这不会保存动画。然而,

 anim.save('animation.mp4', progress_callback=lambda i, n: print(f'Saving frame {i} of {n}'))

确实保存了动画,但渲染不是很清晰而且很模糊。我该如何改变呢?

其他要点是:

  1. 如何将所有散点更改为单一颜色?例如深灰色或黑色
  2. 如何仅将食指更改为不同的颜色?例如食指颜色红色

最良好的祝愿,

PS:附上动画在此处输入图像描述

4

1 回答 1

0
import numpy as np
import pandas as pd
import matplotlib
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.colors import cnames
from matplotlib import animation

#=============================================================================================

t_start = 2# start frame
t_end = 1711# end frame

data = pd.read_csv('Sub6_cylinder0009_index_flex_processed.csv') # only coordinate data
df = data.loc[t_start:t_end,'FT1X':'CMC5Z']


# Find max and min values for animation ranges

df_minmax = pd.DataFrame(index=list('xyz'),columns=range(2))


for i in list('xyz'):
    c_max = df.max().max()
    c_min = df.min().min()
    df_minmax.loc[i] = np.array([c_min,c_max])

df_minmax = 3.3*df_minmax # increase by 30% to make animation look better


df.columns  = np.repeat(range(22),3) # store cols like this for simplicity
print(df.columns)
N_tag = int(df.shape[1]/3) # nr of tags used (all)

N_trajectories = N_tag

t = np.linspace(0,data.Time[t_end],df.shape[0]) # pseudo time-vector for first walking activity

x_t = np.zeros(shape=(N_tag,df.shape[0],3)) # empty animation array (3D)

for tag in range(22):
 #     # store data in numpy 3D array: (tag,time-stamp,xyz-coordinates)
    x_t[tag,:,:] = df[tag]

x_t = x_t[:, :, [0, 2, 1]]


fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1], projection='3d')
ax.axis('on')


#choose a different color for each trajectory
#colors1 = plt.cm.Reds(np.linspace(0, 1, N_trajectories))
#colors2 = plt.cm.gray(np.linspace(0, 1, N_trajectories))
# set up trajectory lines
#lines = sum([ax.plot([], [], [], '-', c=c) for c in colors1], [])
# set up points
#pts = sum([ax.plot([], [], [], 'o--', c=c) for c in colors2], [])
#pts = ax.plot([], [], [], 'o', c=colors2[0])
#pts = ax.plot([], [], [], 'o-', c=colors2[8])
#set up lines which create the stick figures

stick_defines = [
    (0, 13), # Thumb Tip
    (13, 14),
    (14, 19),
    (1, 5), #Index Tip
    (2, 6), # Middle Tip
    (3, 7), # Ring Tip
    (4, 8), # Pinky Tip
    (5, 9), 
    (6, 10),
    (7, 11),
    (8, 12),
    (9, 15),
    (10, 16),
    (11, 17),
    (12, 18),
    (18, 21),
    (15, 20)
    # (22, 23),
    # (23, 24),
    # (22, 26),
    # (25,26)
]

stick_defines1 = [
    # (0, 13), # Thumb Tip
    # (13, 14),
    # (14, 19),
    (1, 5), #Index Tip
    # (2, 6), # Middle Tip
    # (3, 7), # Ring Tip
    # (4, 8), # Pinky Tip
    (5, 9), 
    # (6, 10),
    # (7, 11),
    # (8, 12),
    (9, 15),
    # (10, 16),
    # (11, 17),
    # (12, 18),
    # (18, 21),
    (15, 20)
    # (22, 23),
    # (23, 24),
    # (22, 26),
    # (25,26)
]

stick_lines = [ax.plot([], [], [], 'ko--', alpha=0.5)[0] for _ in stick_defines]
stick_lines1 = [ax.plot([], [], [], 'ro-')[0] for _ in stick_defines1]
print(stick_lines)
ax.set_xlim3d([np.nanmin(x_t[:, :, 0]), np.nanmax(x_t[:, :, 0])])
ax.set_ylim3d([np.nanmin(x_t[:, :, 1])-400, np.nanmax(x_t[:, :, 1])+400])
ax.set_zlim3d([np.nanmin(x_t[:, :, 2]), np.nanmax(x_t[:, :, 2])])
ax.set_xlabel('X [mm]')
ax.set_ylabel('Y [mm]')
ax.set_zlabel('Z [mm]')

# set point-of-view: specified by (altitude degrees, azimuth degrees)
#ax.view_init(30, 25)

# initialization function: plot the background of each frame
# def init():
#     for pt in pts:#zip(pts):
#         # line.set_data(np.array([]), np.array([]))
#         # line.set_3d_properties(np.array([]))
#         pt.set_data(np.array([]), np.array([]))
#         pt.set_3d_properties(np.array([]))
#     return pts

# animation function.  This will be called sequentially with the frame number
def animate(i):
    # we'll step two time-steps per frame.  This leads to nice results.
    i = (5 * i) % x_t.shape[1]
    pts = []
    for pt, xi in zip(pts, x_t):
        x, y, z = xi[:i].T # note ordering of points to line up with true exogenous registration (x,z,y)
        pt.set_data(x[-1:], y[-1:])
        pt.set_3d_properties(z[-1:])
        

    for stick_line, (sp, ep) in zip(stick_lines, stick_defines):
        stick_line._verts3d = x_t[[sp,ep], i, :].T.tolist()
    
    for stick_line1, (sp, ep) in zip(stick_lines1, stick_defines1):
        stick_line1._verts3d = x_t[[sp,ep], i, :].T.tolist()
 
    #ax.view_init(30, 0.3 * i)
    fig.canvas.draw()
    return pts + stick_lines+stick_lines1

# instantiate the animator.
anim = animation.FuncAnimation(fig, animate, frames=500, interval=30, blit=True, repeat=False)
plt.show()
# Save as mp4. This requires mplayer or ffmpeg to be installed
anim.save('animation.mp4', progress_callback=lambda i, n: print(f'Saving frame {i} of {n}'))


#anim.save('test.mp4', writer='ffmpeg')

我已经设法回答了我的问题,但是,动画的保存仍然是一个问题,当前版本有效,但视频模糊且不是特别清晰。注释掉的最后一行代码由于未知原因根本不起作用。

如果您有更好的方法以更好的分辨率保存动画,请告诉我。

附上动画。

最良好的祝愿, 在此处输入图像描述

于 2020-08-27T15:40:04.503 回答