Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
499 views
in Technique[技术] by (71.8m points)

python - 3D animation with matplotlib to visualize moving stick figure

I'm trying to make moving stick figure 3D animation with matplotlib, using npy file made from VideoPose3D. And I find this topic and use the same code, but it made this log. "Module 'matplotlib.cm' has no 'jet' member"

I tried to resolve this problem and made the following code. But the next error occurred. So please tell me why this happens and fix this code and show animation?

details : matplotlib==3.3.3, python3==3.6.9, numpy==1.19.5

npy file is here. https://drive.google.com/file/d/1PJME78STVCPgKZdxpC3KOeP39SRJAx00/view?usp=sharing[][1]

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

arrayMarker3Dcoordinates = np.load('/home/shime/posesimulate/pose.npy')
arrayMarker3Dcoordinates.shape
size = arrayMarker3Dcoordinates.size
df = pd.DataFrame(arrayMarker3Dcoordinates.reshape(size//51, 17*3),
                  columns=['pelvisX', 'pelvisY', 'pelvisZ', 'R-troX', 'R-troY', 'R-troZ', 'R-kneeX', 'R-kneeY', 'R-kneeZ', 'R-ankleX', 'R-ankleY', 'R-ankleZ',  'L-troX', 'L-troY', 'L-troZ', 'L-kneeX', 'L-kneeY', 'L-kneeZ', 'L-ankleX', 'L-ankleY', 'L-ankleZ', 'centerX', 'centerY', 'centerZ', 'neckX', 'neckY', 'neckZ', 'noseX', 'noseY', 'noseZ', 'headX', 'headY', 'headZ',  'L-shoX', 'L-shoY', 'L-shoZ', 'L-elbX', 'L-elbY', 'L-elbZ', 'L-wristX', 'L-wristY', 'L-wristZ', 'R-shoX', 'R-shoY', 'R-shoZ', 'R-elbX', 'R-elbY', 'R-elbZ', 'R-wristX', 'R-wristY', 'R-wristZ'])

t_start = 0  # start frame
t_end = df.shape[0] #frame数
N_tag = df.shape[1]  # nr of tags used (all)
N_trajectories = N_tag
# pseudo time-vector for first walking activity
t = np.linspace(0, t_end/30, df.shape[0])
# empty animation array (3D) 3*3のarray
x_t = np.zeros(shape=(int(N_tag), df.shape[0], 3))

for tag in range(17):
    # store data in numpy 3D array: (tag,time-stamp,xyz-coordinates)
    x_t[tag,:,:] = df.iloc[:, tag * 3:tag * 3 + 3]
    # ===STICK-LINES========================================================================================
    # xx = [x_t[1,:,0],x_t[2,:,0]]
    # yy = [x_t[1,:,1],x_t[2,:,1]]
    # zz = [x_t[1,:,2],x_t[2,:,2]]
    # ======================================================================================================

# Set up figure & 3D axis for animation
fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1], projection='3d')
ax.axis('on')

"""#this is original code
# choose a different color for each trajectory
colors = plt.cm.jet(np.linspace(0, 1, int(N_trajectories)))
#colors
# 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], [])
"""

lines = sum([ax.plot([], [], [], '-', color='C3')for i in range(N_trajectories)], [])
pts = sum([ax.plot([], [], [], 'o', color='C3') for i in range(N_trajectories)], [])

# set up lines which create the stick figures
stick_defines = [
    (0, 1),
    (0, 4),
    (4, 5),
    (5, 6),
    (0, 7),
    (1, 2),
    (2, 3),
    (7, 8),
    (8, 9),
    (9, 10),
    (8, 14),
    (8, 11),
    (11, 12),
    (12, 13),
    (14, 15),
    (15, 16)
]

# 上で定義されたstick_definesにある点の間に線をひく "draw line between 2 points"
stick_lines = [ax.plot([], [], [], 'k-')[0] for _ in stick_defines]
    # Automatically set axes limits
    # prepare the axes limits
    # ax.set_xlim(df_minmax.loc['x'].values)
    # ax.set_ylim(df_minmax.loc['y'].values)
    # ax.set_zlim(df_minmax.loc['z'].values)

    # Setting the axes properties
    # https://matplotlib.org/2.1.2/gallery/animation/simple_3danim.html
    
mid_x = 0
x_range = 1
ax.set_xlim3d(mid_x - x_range, mid_x + x_range)
ax.set_xlabel('X')

mid_y =0
y_range = 1
ax.set_ylim3d(mid_y - x_range, mid_y + x_range)
ax.set_ylabel('Y')

mid_z = 0.5
z_range = 1
ax.set_zlim3d(mid_z - z_range, 1.5)
ax.set_zlabel('Z')

ax.set_title('markers in 3D')

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

# initialization function: plot the background of each frame
def init():
    for line, pt in zip(lines, pts): # lines, ptsのリストから,同時にi番目のデータを取得する.linesからline, pts からpt "at the same time,get number i date, line from lines, pt from pts"
        # trajectory lines
        line.set_data([], [])
        line.set_3d_properties([], [])
        # points
        pt.set_data([], [])
        pt.set_3d_properties([], [])
    return lines + pts + stick_lines

# animation function.  This will be called sequentially with the frame number
def animate(i):
    # 1 * i means show every frame, 2*i means one frame show one frame no-show
    i = (1 * i) % x_t.shape[1] 

    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()

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

# instantiate the animator.
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=t_end, interval=100, repeat = False, blit=True)

# save GIF animation
# anim.save('3Dplotanimation.gif', writer='pillow', fps=10)

plt.show()

And log is this.

/usr/bin/python3 /home/shime/posesimulate/simulate.py
Traceback (most recent call last):
  File "/home/shime/.local/lib/python3.6/site-packages/matplotlib/backends/backend_gtk3.py", line 258, in size_allocate
    FigureCanvasBase.resize_event(self)
  File "/home/shime/.local/lib/python3.6/site-packages/matplotlib/backend_bases.py", line 1767, in resize_event
    self.callbacks.process(s, event)
  File "/home/shime/.local/lib/python3.6/site-packages/matplotlib/cbook/__init__.py", line 229, in process
    self.exception_handler(exc)
  File "/home/shime/.local/lib/python3.6/site-packages/matplotlib/cbook/__init__.py", line 81, in _exception_printer
    raise exc
  File "/home/shime/.local/lib/python3.6/site-packages/matplotlib/cbook/__init__.py", line 224, in process
    func(*args, **kwargs)
  File "/home/shime/.local/lib/python3.6/site-packages/matplotlib/animation.py", line 1259, in _on_resize
    self._init_draw()
  File "/home/shime/.local/lib/python3.6/site-packages/matplotlib/animation.py", line 1706, in _init_draw
    self._drawn_artists = self._init_func()
  File "/home/shime/posesimulate/simulate.py", line 109, in init
    line.set_3d_properties([], [])
  File "/home/shime/.local/lib/python3.6/site-packages/mpl_toolkits/mplot3d/art3d.py", line 143, in set_3d_properties
    zs = np.broadcast_to(zs, xs.shape)
AttributeError: 'list' object has no attribute 'shape'
Traceback (most recent call last):
  File "/home/shime/posesimulate/simulate.py", line 139, in <module>
    plt.show()
  File "/home/shime/.local/lib/python3.6/site-packages/matplotlib/pyplot.py", line 353, in show
    return _backend_mod.show(*args, **kwargs)
  File "/home/shime/.local/lib/python3.6/site-packages/matplotlib/backend_bases.py", line 3524, in show
    manager.show()  # Emits a warning for non-interactive backend.
  File "/home/shime/.local/lib/python3.6/site-packages/matplotlib/backends/backend_gtk3.py", line 446, in show
    self.canvas.draw()
  File "/home/shime/.local/lib/python3.6/site-packages/matplotlib/backends/backend_gtk3agg.py", line 70, in draw
    backend_agg.FigureCanvasAgg.draw(self)
  File "/home/shime/.local/lib/python3.6/site-packages/matplotlib/backends/backend_agg.py", line 407, in draw
    self.figure.draw(self.renderer)
  File "/home/shime/.local/lib/python3.6/site-packages/matplotlib/artist.py", line 41, in draw_wrapper
    return draw(artist, renderer, *args, **kwargs)
  File "/home/shime/.local/lib/python3.6/site-packages/matplotlib/figure.py", line 1870, in draw
    self.canvas.draw_event(renderer)
  File "/home/shime/.local/lib/python3.6/site-packages/matplotlib/backend_bases.py", line 1759, in draw_event
    self.callbacks.process(s, event)
  File "/home/shime/.local/lib/python3.6/site-packages/matplotlib/cbook/__init__.py", line 229, in process
    self.exception_handler(exc)
  File "/home/shime/.local/lib/python3.6/site-packages/matplotlib/cbook/__init__.py", line 81, in _exception_printer
    raise exc
  File "/home/shime/.local/lib/python3.6/site-packages/matplotlib/cbook/__init__.py", line 224, in process
    func(*args, **kwargs)
  File "/home/shime/.local/lib/python3.6/site-packages/matplotlib/animation.py", line 959, in _start
    self._init_draw()
  File "/home/shime/.local/lib/python3.6/site-packages/matplotlib/animation.py", line 1706, in _init_draw
    self._drawn_artists = self._init_func()
  File "/home/shime/posesimulate/simulate.py", line 109, in init
    line.set_3d_properties([], [])
  File "/home/shime/.local/lib/python3.6/site-packages/mpl_toolkits/mplot3d/art3d.py", line 143, in set_3d_properties
    zs = np.broadcast_to(zs, xs.shape)
AttributeError: 'list' object has no attribute 'shape'

My writing is probably difficult to read. I'm sorry. As ever, any help is much appreciated.

question from:https://stackoverflow.com/questions/65872499/3d-animation-with-matplotlib-to-visualize-moving-stick-figure

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Inside the init function, simply replace line.set_3d_properties([], []) with line.set_3d_properties([])


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...