from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from PIL import Image
# import matplotlib.animation as animation
import numpy as np
from matplotlib.animation import FuncAnimation
img = Image.open('test.jpg')
grayImg = img.convert('L')
width, height = grayImg.size
X, Y = np.meshgrid(np.arange(0, width), np.arange(0, height))
# print(X)
Z = np.array(grayImg)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='viridis')
#plt.show()
def update(i):
label = 'timestep {0}'.format(i)
# 更新直线和x轴(用一个新的x轴的标签)。
# 用元组(Tuple)的形式返回在这一帧要被重新绘图的物体
horiAngle = (45 + 3 * i)%360#transition(i, 40)
vertAngle = (45 + 3 * i)%360#transition(i, 40)
print(label,horiAngle,vertAngle)
ax.view_init(vertAngle, horiAngle)
filename = 'animation/' + str('%03d' % i) + '.png'
plt.savefig(filename, dpi=96)
return ax
anim = FuncAnimation(fig, update, frames=np.arange(0, 120), interval=200)
anim.save('animation/line.gif', dpi=120, writer='imagemagick')
图像绘制完后,颠覆了我对2D图像的认知,下面是原图,test.jpg
恢复用pycharm的figure窗口就ok
1、“文件—>设置”,打开设置窗口。
2、找到最后一个工具
3、找到“Python Scientific”,去除右边Show plots in toolwindow
候选框中的勾号
以下代码为最新的,经过chatgpt改进的!稳定性更好
import os
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
from matplotlib.animation import FuncAnimation
# 打开图片并转换为灰度
img = Image.open('test.jpg')
gray_img = img.convert('L')
width, height = gray_img.size
X, Y = np.meshgrid(np.arange(0, width), np.arange(0, height))
Z = np.array(gray_img)
# 创建3D图形
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='viridis')
# 更新函数,用于动画的每一帧
def update(i):
# 计算水平和垂直角度
hori_angle = (45 + 3 * i) % 360
vert_angle = (45 + 3 * i) % 360
ax.view_init(vert_angle, hori_angle)
# 打印当前帧的信息
print(f'timestep {i}: hori_angle={hori_angle}, vert_angle={vert_angle}')
return ax
# 检查目录是否存在,如果不存在则创建
animation_directory = 'animation'
if not os.path.exists(animation_directory):
os.makedirs(animation_directory)
# 创建动画
anim = FuncAnimation(fig, update, frames=np.arange(0, 120), interval=200)
# 直接保存为GIF文件
anim.save(f'{animation_directory}/line.gif', dpi=120, writer='imagemagick')