In [55]:
# Imports
import numpy as np
import nilearn as nil
import nibabel as nib
from matplotlib import gridspec
from nilearn import plotting as nlp
from matplotlib import pyplot as plt
import matplotlib.animation as animation

In [56]:
%pylab inline


Populating the interactive namespace from numpy and matplotlib

In [3]:
from tempfile import NamedTemporaryFile

VIDEO_TAG = """<video controls>
 <source src="data:video/x-m4v;base64,{0}" type="video/mp4">
 Your browser does not support the video tag.
</video>"""

def anim_to_html(anim):
    if not hasattr(anim, '_encoded_video'):
        with NamedTemporaryFile(suffix='.mp4') as f:
            anim.save(f.name, fps=20, extra_args=['-vcodec', 'libx264'])
            video = open(f.name, "rb").read()
        anim._encoded_video = video.encode("base64")
    
    return VIDEO_TAG.format(anim._encoded_video)

In [7]:
from IPython.display import HTML

def display_animation(anim):
    plt.close(anim._fig)
    return HTML(anim_to_html(anim))

In [22]:
window = np.arange(0,200-50)

In [23]:
def visu(i, tmp, ax, ay):
    ay.plot([window[i], window[i]+50], [2, 2], color='blue', linewidth=5, alpha=0.5)
    ax.plot([window[i], window[i]+50], [2, 2], color='red', linewidth=5, alpha=0.5)

In [54]:
fig = plt.figure(figsize=(7,4))
ax = fig.add_subplot(121)
ax.set_xlim([0, 200])
ay = fig.add_subplot(122)
ay.set_xlim([0, 200])
iml = list()
for i in np.arange(50):
    a = ay.axvspan(window[i], window[i]+50, color='blue', alpha=0.5) 
    #b = ax.axvspan(window[i], window[i]+50, color='red', alpha=0.5) 
    iml.append((a,))
ani = animation.ArtistAnimation(fig, iml, interval=50, blit=True,
    repeat_delay=1000)
#ani = animation.FuncAnimation(fig, visu, interval=50, blit=False, fargs=(np.arange(50), ax, ay))
display_animation(ani)


Out[54]:

In [16]:
ani.save('dynamic_images.mp4')

In [39]:
a, = ('hello', 'huhu')


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-39-8583e1bcccb7> in <module>()
----> 1 a, = ('hello', 'huhu')

ValueError: too many values to unpack

In [57]:
# Paths
mask_path = '/data1/abide/Mask/mask_data_specific.nii.gz'
prior_path = '/data1/cambridge/template/template_cambridge_basc_multiscale_sym_scale012.nii.gz'
pheno_path = '/data1/abide/Pheno/merged_pheno.csv'
sub_path = '/data1/abide/Full/abide_release_sym_gsc0_lp01/Stanford/fmri_0051198_session_1_run1.nii.gz'

In [59]:
# Get the subject
s_img = nib.load(sub_path)

In [64]:
fig = plt.figure(figsize=(7,4))
ax = fig.add_subplot(121)
ax.set_xlim([0, 200])
ay = fig.add_subplot(122)
iml = list()

for i in np.arange(50):
    a = ax.axvspan(window[i], window[i]+50, color='blue', alpha=0.5)
    b = nlp.plot_stat_map(nil.image.index_img(s_img, i), axes=ax)
    iml.append((a,b))
ani = animation.ArtistAniTruemation(fig, iml, interval=50, blit=False,
    repeat_delay=1000)
#ani = animation.FuncAnimation(fig, visu, interval=50, blit=False, fargs=(np.arange(50), ax, ay))
display_animation(ani)


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-64-9e5233993b54> in <module>()
     11     iml.append((a,b))
     12 ani = animation.ArtistAnimation(fig, iml, interval=50, blit=False,
---> 13     repeat_delay=1000)
     14 #ani = animation.FuncAnimation(fig, visu, interval=50, blit=False, fargs=(np.arange(50), ax, ay))
     15 display_animation(ani)

/home/surchs/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/matplotlib/animation.pyc in __init__(self, fig, artists, *args, **kwargs)
    967         # over by the machinery.
    968         self._framedata = artists
--> 969         TimedAnimation.__init__(self, fig, *args, **kwargs)
    970 
    971     def _init_draw(self):

/home/surchs/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/matplotlib/animation.pyc in __init__(self, fig, interval, repeat_delay, repeat, event_source, *args, **kwargs)
    911 
    912         Animation.__init__(self, fig, event_source=event_source,
--> 913                            *args, **kwargs)
    914 
    915     def _step(self, *args):

/home/surchs/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/matplotlib/animation.pyc in __init__(self, fig, event_source, blit)
    589 
    590         # Clear the initial frame
--> 591         self._init_draw()
    592 
    593         # Instead of starting the event source now, we connect to the figure's

/home/surchs/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/matplotlib/animation.pyc in _init_draw(self)
    974         for f in self.new_frame_seq():
    975             for artist in f:
--> 976                 artist.set_visible(False)
    977                 # Assemble a list of unique axes that need flushing
    978                 if artist.axes not in axes:

AttributeError: 'OrthoSlicer' object has no attribute 'set_visible'

In [72]:
fig = plt.figure(figsize=(7,4))
ax = fig.add_subplot(121)
ax.set_xlim([0, 200])
ax.axvspan(window[i], window[i]+50, color='blue', alpha=0.5)

ay = fig.add_subplot(122)
nlp.plot_stat_map(nil.image.index_img(s_img, i), axes=ay, colorbar=False, display_mode='x', cut_coords=(0,))


Out[72]:
<nilearn.plotting.displays.XSlicer at 0x114d1b50>

In [76]:
def show_things(i, window, ax, ay):
    ax.axvspan(window[i], window[i]+50, color='blue', alpha=0.5)
    nlp.plot_stat_map(nil.image.index_img(s_img, i), axes=ay, colorbar=False, display_mode='x', cut_coords=(0,))

In [77]:
fig = plt.figure(figsize=(7,4))
ax = fig.add_subplot(121)
ax.set_xlim([0, 200])
ay = fig.add_subplot(122)

ani = animation.FuncAnimation(fig, show_things, interval=10, blit=False, fargs=(window, ax, ay))
display_animation(ani)


Out[77]:

In [ ]: