Skip to main content

3D Animation Matlab

 import matplotlib.pyplot as plt

import matplotlib.animation as animation

%matplotlib inline


fig = plt.figure(dpi=200)

ims = []

for t in range(0, img1.shape[0]):

    imx = img1[t,:,:]

    im = plt.imshow(imx, cmap='gray', animated=True)

    ims.append([im])

ani = animation.ArtistAnimation(fig, ims, interval=200, blit=True,

                                repeat_delay=1000)

plt.close()

from IPython.display import HTML

HTML(ani.to_jshtml())

# if you want to keep inside function you can use display(HTML(ani.to_jshtml()))

Example:

def playVideo(input_sample):

    numFrames = input_sample.shape[0]

    fig = plt.figure()

    fig.set_size_inches(10, 10, True)

    im = plt.imshow(input_sample[0,:,:])

    plt.close()


    def update(i):

        img = input_sample[i,:,:]

        im.set_data(img)

        return im


    ani = animation.FuncAnimation(fig, update, frames=numFrames, repeat=True)  

    # display(HTML(ani.to_html5_video()))

    display(HTML(ani.to_jshtml()))


logger.info('Saving input and prediction as video files...')

            fig = plt.figure(dpi=200)

            plt.rcParams['animation.ffmpeg_path'] = ffmpegpath # "ffmpeg.exe" #"/Storage/ramesh/mrmdata/ffmpeg.exe"

            n_cols = 3

            fig, axs = plt.subplots(1, n_cols, dpi=200)

            ims = []


            for t in range(0, t_seqs):

                ima = imginp_valid[t,:,:]

                imb = imgprd_valid[t,:,:]

                imc = imgbhd_valid[t,:,:]


                im1 = axs[0].imshow(ima, cmap='gray', animated=True)

                im2 = axs[1].imshow(imb, cmap='gray', animated=True)

                im3 = axs[2].imshow(imc, cmap='gray', animated=True)


                axs[0].set_title('Free Breathing')

                axs[1].set_title('Corrected')

                axs[2].set_title('Sample Breath Hold')


                for i in range(n_cols):

                    axs[i].get_xaxis().set_visible(False)

                    axs[i].get_yaxis().set_visible(False)


                ims.append([im1, im2, im3])


            ani = animation.ArtistAnimation(fig, ims, interval=200, blit=True,

                                    repeat_delay=1000)


            out_prefix = os.path.join(out_video_dir, path_leaf(test_file)) #test_file.replace(datadir, out_video_dir)

            outfn = out_prefix.replace('.npy', '.mp4')  # .mp4

            # Set up formatting for the movie files

            Writer = animation.writers['ffmpeg'] # ffmpeg

            writer = Writer(fps=5, metadata=dict(artist='Me'), bitrate=1800)

            ani.save(outfn, writer=writer)

            plt.close()

            logger.info(f'Video saved as: {outfn}')