Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib save animaiton as video but get empty content

I am trying to make an animation with continue rotating an image, but the output video file has empty content(Only axis left), how to fix it?

import math

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import scipy.misc
from scipy import ndimage

my_image="img.png"
out_file="myvideo.mp4"

class UpdateDist:
    def __init__(self, ax):
        self.ax = ax
        self.img = mpimg.imread(my_image)
        self.ax.imshow(self.img)
        self.degree = 1


    def __call__(self, i):
        rotated_img = ndimage.rotate(img, self.degree*10)
        self.ax.imshow(rotated_img)
        self.degree += 1
        return self.ax,


plt.axis(False)
plt.grid(False)
fig, ax = plt.subplots()


ud = UpdateDist(ax)
anim = FuncAnimation(fig, ud, frames=100, interval=10, blit=True)
plt.show()
ani.save(out_file, fps=30, extra_args=['-vcodec', 'libx264'])
like image 268
prehistoricpenguin Avatar asked Apr 29 '26 23:04

prehistoricpenguin


1 Answers

I applied some edits to your code:

  • replaced self.degree with i: i increases by 1 in each iteration, no need for another counter
  • moved ax.grid(False) and ax.axis(False) (and added ax.clear()) within __call__ method, in order to use them in each frame
  • removed blit parameter from FuncAnimation
  • replaced .mp4 output file format with .gif
  • used imagemagik as writer

Let me know if this code achieves your goal or if you need any further modifications.

Complete Code

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from scipy import ndimage
import numpy as np


my_image='img.png'
out_file='myvideo.gif'


class UpdateDist:

    def __init__(self, ax, rotational_speed):
        self.ax = ax
        self.img = plt.imread(my_image)
        self.rotational_speed = rotational_speed

    def __call__(self, i):
        rotated_img = ndimage.rotate(self.img, self.rotational_speed*i, reshape=False)
        self.ax.clear()
        self.ax.grid(False)
        self.ax.axis(False)
        self.ax.imshow((rotated_img*255).astype(np.uint8))
        return self.ax,


fig, ax = plt.subplots()

ud = UpdateDist(ax = ax, rotational_speed = 1)
anim = FuncAnimation(fig, ud, frames = 91, interval = 1)
anim.save(filename = out_file, writer = 'pillow', fps = 30)

Animation

enter image description here

like image 109
Zephyr Avatar answered May 02 '26 12:05

Zephyr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!