visualization.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. # Copyright (c) 2018-present, Facebook, Inc.
  2. # All rights reserved.
  3. #
  4. # This source code is licensed under the license found in the
  5. # LICENSE file in the root directory of this source tree.
  6. #
  7. import matplotlib
  8. matplotlib.use('Agg')
  9. import matplotlib.pyplot as plt
  10. from matplotlib.animation import FuncAnimation, writers
  11. from mpl_toolkits.mplot3d import Axes3D
  12. import numpy as np
  13. import subprocess as sp
  14. def get_resolution(filename):
  15. command = ['ffprobe', '-v', 'error', '-select_streams', 'v:0',
  16. '-show_entries', 'stream=width,height', '-of', 'csv=p=0', filename]
  17. with sp.Popen(command, stdout=sp.PIPE, bufsize=-1) as pipe:
  18. for line in pipe.stdout:
  19. w, h = line.decode().strip().split(',')
  20. return int(w), int(h)
  21. def get_fps(filename):
  22. command = ['ffprobe', '-v', 'error', '-select_streams', 'v:0',
  23. '-show_entries', 'stream=r_frame_rate', '-of', 'csv=p=0', filename]
  24. with sp.Popen(command, stdout=sp.PIPE, bufsize=-1) as pipe:
  25. for line in pipe.stdout:
  26. a, b = line.decode().strip().split('/')
  27. return int(a) / int(b)
  28. def read_video(filename, skip=0, limit=-1):
  29. w, h = get_resolution(filename)
  30. command = ['ffmpeg',
  31. '-i', filename,
  32. '-f', 'image2pipe',
  33. '-pix_fmt', 'rgb24',
  34. '-vsync', '0',
  35. '-vcodec', 'rawvideo', '-']
  36. i = 0
  37. with sp.Popen(command, stdout = sp.PIPE, bufsize=-1) as pipe:
  38. while True:
  39. data = pipe.stdout.read(w*h*3)
  40. if not data:
  41. break
  42. i += 1
  43. if i > limit and limit != -1:
  44. continue
  45. if i > skip:
  46. yield np.frombuffer(data, dtype='uint8').reshape((h, w, 3))
  47. def downsample_tensor(X, factor):
  48. length = X.shape[0]//factor * factor
  49. return np.mean(X[:length].reshape(-1, factor, *X.shape[1:]), axis=1)
  50. def render_animation(keypoints, keypoints_metadata, poses, skeleton, fps, bitrate, azim, output, viewport,
  51. limit=-1, downsample=1, size=6, input_video_path=None, input_video_skip=0):
  52. """
  53. TODO
  54. Render an animation. The supported output modes are:
  55. -- 'interactive': display an interactive figure
  56. (also works on notebooks if associated with %matplotlib inline)
  57. -- 'html': render the animation as HTML5 video. Can be displayed in a notebook using HTML(...).
  58. -- 'filename.mp4': render and export the animation as an h264 video (requires ffmpeg).
  59. -- 'filename.gif': render and export the animation a gif file (requires imagemagick).
  60. """
  61. plt.ioff()
  62. fig = plt.figure(figsize=(size*(1 + len(poses)), size))
  63. ax_in = fig.add_subplot(1, 1 + len(poses), 1)
  64. ax_in.get_xaxis().set_visible(False)
  65. ax_in.get_yaxis().set_visible(False)
  66. ax_in.set_axis_off()
  67. ax_in.set_title('Input')
  68. ax_3d = []
  69. lines_3d = []
  70. trajectories = []
  71. radius = 1.7
  72. for index, (title, data) in enumerate(poses.items()):
  73. ax = fig.add_subplot(1, 1 + len(poses), index+2, projection='3d')
  74. ax.view_init(elev=15., azim=azim)
  75. ax.set_xlim3d([-radius/2, radius/2])
  76. ax.set_zlim3d([0, radius])
  77. ax.set_ylim3d([-radius/2, radius/2])
  78. try:
  79. ax.set_aspect('equal')
  80. except NotImplementedError:
  81. ax.set_aspect('auto')
  82. ax.set_xticklabels([])
  83. ax.set_yticklabels([])
  84. ax.set_zticklabels([])
  85. ax.dist = 7.5
  86. ax.set_title(title) #, pad=35
  87. ax_3d.append(ax)
  88. lines_3d.append([])
  89. trajectories.append(data[:, 0, [0, 1]])
  90. poses = list(poses.values())
  91. # Decode video
  92. if input_video_path is None:
  93. # Black background
  94. all_frames = np.zeros((keypoints.shape[0], viewport[1], viewport[0]), dtype='uint8')
  95. else:
  96. # Load video using ffmpeg
  97. all_frames = []
  98. for f in read_video(input_video_path, skip=input_video_skip, limit=limit):
  99. all_frames.append(f)
  100. effective_length = min(keypoints.shape[0], len(all_frames))
  101. all_frames = all_frames[:effective_length]
  102. keypoints = keypoints[input_video_skip:] # todo remove
  103. for idx in range(len(poses)):
  104. poses[idx] = poses[idx][input_video_skip:]
  105. if fps is None:
  106. fps = get_fps(input_video_path)
  107. if downsample > 1:
  108. keypoints = downsample_tensor(keypoints, downsample)
  109. all_frames = downsample_tensor(np.array(all_frames), downsample).astype('uint8')
  110. for idx in range(len(poses)):
  111. poses[idx] = downsample_tensor(poses[idx], downsample)
  112. trajectories[idx] = downsample_tensor(trajectories[idx], downsample)
  113. fps /= downsample
  114. initialized = False
  115. image = None
  116. lines = []
  117. points = None
  118. if limit < 1:
  119. limit = len(all_frames)
  120. else:
  121. limit = min(limit, len(all_frames))
  122. parents = skeleton.parents()
  123. def update_video(i):
  124. nonlocal initialized, image, lines, points
  125. for n, ax in enumerate(ax_3d):
  126. ax.set_xlim3d([-radius/2 + trajectories[n][i, 0], radius/2 + trajectories[n][i, 0]])
  127. ax.set_ylim3d([-radius/2 + trajectories[n][i, 1], radius/2 + trajectories[n][i, 1]])
  128. # Update 2D poses
  129. joints_right_2d = keypoints_metadata['keypoints_symmetry'][1]
  130. colors_2d = np.full(keypoints.shape[1], 'black')
  131. colors_2d[joints_right_2d] = 'red'
  132. if not initialized:
  133. image = ax_in.imshow(all_frames[i], aspect='equal')
  134. for j, j_parent in enumerate(parents):
  135. if j_parent == -1:
  136. continue
  137. if len(parents) == keypoints.shape[1] and keypoints_metadata['layout_name'] != 'coco':
  138. # Draw skeleton only if keypoints match (otherwise we don't have the parents definition)
  139. lines.append(ax_in.plot([keypoints[i, j, 0], keypoints[i, j_parent, 0]],
  140. [keypoints[i, j, 1], keypoints[i, j_parent, 1]], color='pink'))
  141. col = 'red' if j in skeleton.joints_right() else 'black'
  142. for n, ax in enumerate(ax_3d):
  143. pos = poses[n][i]
  144. lines_3d[n].append(ax.plot([pos[j, 0], pos[j_parent, 0]],
  145. [pos[j, 1], pos[j_parent, 1]],
  146. [pos[j, 2], pos[j_parent, 2]], zdir='z', c=col))
  147. points = ax_in.scatter(*keypoints[i].T, 10, color=colors_2d, edgecolors='white', zorder=10)
  148. initialized = True
  149. else:
  150. image.set_data(all_frames[i])
  151. for j, j_parent in enumerate(parents):
  152. if j_parent == -1:
  153. continue
  154. if len(parents) == keypoints.shape[1] and keypoints_metadata['layout_name'] != 'coco':
  155. lines[j-1][0].set_data([keypoints[i, j, 0], keypoints[i, j_parent, 0]],
  156. [keypoints[i, j, 1], keypoints[i, j_parent, 1]])
  157. for n, ax in enumerate(ax_3d):
  158. pos = poses[n][i]
  159. lines_3d[n][j-1][0].set_xdata(np.array([pos[j, 0], pos[j_parent, 0]]))
  160. lines_3d[n][j-1][0].set_ydata(np.array([pos[j, 1], pos[j_parent, 1]]))
  161. lines_3d[n][j-1][0].set_3d_properties(np.array([pos[j, 2], pos[j_parent, 2]]), zdir='z')
  162. points.set_offsets(keypoints[i])
  163. print('{}/{} '.format(i, limit), end='\r')
  164. fig.tight_layout()
  165. anim = FuncAnimation(fig, update_video, frames=np.arange(0, limit), interval=1000/fps, repeat=False)
  166. if output.endswith('.mp4'):
  167. Writer = writers['ffmpeg']
  168. writer = Writer(fps=fps, metadata={}, bitrate=bitrate)
  169. anim.save(output, writer=writer)
  170. elif output.endswith('.gif'):
  171. anim.save(output, dpi=80, writer='imagemagick')
  172. else:
  173. raise ValueError('Unsupported output format (only .mp4 and .gif are supported)')
  174. plt.close()