Python 程序员大家好。
我正在尝试根据预定义的模式在 matplotlib 中旋转和平移图像。
我正在尝试使用
FuncAnimation
和 Affine2D
来实现这一目标。我的代码看起来像这样:
from matplotlib.animation import FumcAnimation
from matplotlib.transforms import Affine2D
from matplotlib import pyplot as plt
fig, ax = plt.subplots()
img = ax.imgshow(plt.imread("demo.png"),aspect="equal")
def update(i):
if i>0: img.set_transform(Affine2D().translate(1,0))
return img
anim=FuncAnimation(fig,update,frames=(0,1))
plt.show()
图像没有向右移动,而是消失了...
translate
图像(向右)和rotate_deg
,您可以执行如下操作:
import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
from matplotlib.animation import FuncAnimation
img = plt.imread("mpl_logo.png")
W, H, *_ = img.shape
fig, ax = plt.subplots(figsize=(10, 5))
# feel free to readapt..
ax.grid()
ax.set(xlim=(-W // 2, W * 7), ylim=(-H, H * 2))
ax.patch.set_facecolor("whitesmoke")
aximg = ax.imshow(img)
def move(frame):
transfo = mtransforms.Affine2D()
(
transfo.translate(-W / 2, -H / 2)
.rotate_deg(frame % 190)
.translate(W / 2, H / 2)
.translate(frame, 0)
)
aximg.set_transform(transfo + ax.transData)
return (aximg,)
anim = FuncAnimation(fig, move, frames=range(0, W * 7 - 1000, 100))
输出(
fps=10
):