使用 imageio 保存 3D 图
Save 3D plot with imageio
我想将 3D 绘图另存为 gif。但是,由于我无法解释的原因,以下代码不起作用。当我使用 imageio.mimsave(...)
时收到错误消息:Image must be 2D (grayscale, RGB, or RGBA)
,但我将图像保存为 RGB:
import numpy as np
import matplotlib.pyplot as plt
import imageio
x = [0,1,0,0]
y = [0,0,1,0]
z = [0,0,0,1]
fig = plt.figure(figsize=(15,9))
ax = fig.add_subplot(projection='3d')
ax.scatter(x,y,z,s=1500)
images = []
for n in range(0, 100):
if n >= 20:
ax.azim = ax.azim+1.1
fig.canvas.draw()
image = np.frombuffer(fig.canvas.tostring_rgb(), dtype='uint8')
images.append(image)
imageio.mimsave('test.gif', images)
np.frombuffer
returns一个平面数组,它的形状(X*Y*3,)
,相反imageio
需要一个Y×X × 3(或者对于 RGBA 缓冲区可能是 × 4)。您必须 reshape
您的 image
In [43]: import numpy as np
...: import matplotlib.pyplot as plt
...: import imageio
...:
...: x = [0,1,0,0]
...: y = [0,0,1,0]
...: z = [0,0,0,1]
...:
...: fig = plt.figure(figsize=(5, 3)) # @100 dpi it's 500×300 pixels
...: ax = fig.add_subplot(projection='3d')
...: ax.scatter(x,y,z,s=500)
...:
...: images = []
...: for n in range(0, 25):
...: if n >= 15:
...: ax.azim = ax.azim+1.1
...: fig.canvas.draw()
...: image = np.frombuffer(fig.canvas.tostring_rgb(), dtype='uint8')
...: images.append(image.reshape(300, 500, 3)) ## Y×X
...:
...: imageio.mimsave('test.gif', images)
...:
In [44]: ls -l test.gif
-rw-r--r-- 1 boffi boffi 825988 May 21 19:46 test.gif
In [45]:
请注意,我已经修改了尺寸和帧数以获得更小的 GIF。
我想将 3D 绘图另存为 gif。但是,由于我无法解释的原因,以下代码不起作用。当我使用 imageio.mimsave(...)
时收到错误消息:Image must be 2D (grayscale, RGB, or RGBA)
,但我将图像保存为 RGB:
import numpy as np
import matplotlib.pyplot as plt
import imageio
x = [0,1,0,0]
y = [0,0,1,0]
z = [0,0,0,1]
fig = plt.figure(figsize=(15,9))
ax = fig.add_subplot(projection='3d')
ax.scatter(x,y,z,s=1500)
images = []
for n in range(0, 100):
if n >= 20:
ax.azim = ax.azim+1.1
fig.canvas.draw()
image = np.frombuffer(fig.canvas.tostring_rgb(), dtype='uint8')
images.append(image)
imageio.mimsave('test.gif', images)
np.frombuffer
returns一个平面数组,它的形状(X*Y*3,)
,相反imageio
需要一个Y×X × 3(或者对于 RGBA 缓冲区可能是 × 4)。您必须 reshape
您的 image
In [43]: import numpy as np
...: import matplotlib.pyplot as plt
...: import imageio
...:
...: x = [0,1,0,0]
...: y = [0,0,1,0]
...: z = [0,0,0,1]
...:
...: fig = plt.figure(figsize=(5, 3)) # @100 dpi it's 500×300 pixels
...: ax = fig.add_subplot(projection='3d')
...: ax.scatter(x,y,z,s=500)
...:
...: images = []
...: for n in range(0, 25):
...: if n >= 15:
...: ax.azim = ax.azim+1.1
...: fig.canvas.draw()
...: image = np.frombuffer(fig.canvas.tostring_rgb(), dtype='uint8')
...: images.append(image.reshape(300, 500, 3)) ## Y×X
...:
...: imageio.mimsave('test.gif', images)
...:
In [44]: ls -l test.gif
-rw-r--r-- 1 boffi boffi 825988 May 21 19:46 test.gif
In [45]:
请注意,我已经修改了尺寸和帧数以获得更小的 GIF。