Python matplotlib.animation() Examples

The following are 30 code examples of matplotlib.animation(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module matplotlib , or try the search function .
Example #1
Source File: movie.py    From kvae with MIT License 10 votes vote down vote up
def save_frames(images, filename):
    num_sequences, n_steps, w, h = images.shape

    fig = plt.figure()
    im = plt.imshow(combine_multiple_img(images[:, 0]), cmap=plt.cm.get_cmap('Greys'), interpolation='none')
    plt.axis('image')

    def updatefig(*args):
        im.set_array(combine_multiple_img(images[:, args[0]]))
        return im,

    ani = animation.FuncAnimation(fig, updatefig, interval=500, frames=n_steps)

    # Either avconv or ffmpeg need to be installed in the system to produce the videos!
    try:
        writer = animation.writers['avconv']
    except KeyError:
        writer = animation.writers['ffmpeg']
    writer = writer(fps=3)
    ani.save(filename, writer=writer)
    plt.close(fig) 
Example #2
Source File: test_plots_matplotlib.py    From arviz with Apache License 2.0 6 votes vote down vote up
def test_plot_ppc_multichain(kind, jitter, animated):
    if animation and not animation.writers.is_available("ffmpeg"):
        pytest.skip("matplotlib animations within ArviZ require ffmpeg")
    data = from_dict(
        posterior_predictive={
            "x": np.random.randn(4, 100, 30),
            "y_hat": np.random.randn(4, 100, 3, 10),
        },
        observed_data={"x": np.random.randn(30), "y": np.random.randn(3, 10)},
    )
    animation_kwargs = {"blit": False}
    axes = plot_ppc(
        data,
        kind=kind,
        data_pairs={"y": "y_hat"},
        jitter=jitter,
        animated=animated,
        animation_kwargs=animation_kwargs,
        random_seed=3,
    )
    if animated:
        assert np.all(axes[0])
        assert np.all(axes[1])
    else:
        assert np.all(axes) 
Example #3
Source File: pyplot.py    From twitter-stock-recommendation with MIT License 6 votes vote down vote up
def pause(interval):
    """
    Pause for *interval* seconds.

    If there is an active figure, it will be updated and displayed before the
    pause, and the GUI event loop (if any) will run during the pause.

    This can be used for crude animation.  For more complex animation, see
    :mod:`matplotlib.animation`.

    Notes
    -----
    This function is experimental; its behavior may be changed or extended in a
    future release.
    """
    manager = _pylab_helpers.Gcf.get_active()
    if manager is not None:
        canvas = manager.canvas
        if canvas.figure.stale:
            canvas.draw_idle()
        show(block=False)
        canvas.start_event_loop(interval)
    else:
        time.sleep(interval) 
Example #4
Source File: pyplot.py    From CogAlg with MIT License 6 votes vote down vote up
def pause(interval):
    """
    Pause for *interval* seconds.

    If there is an active figure, it will be updated and displayed before the
    pause, and the GUI event loop (if any) will run during the pause.

    This can be used for crude animation.  For more complex animation, see
    :mod:`matplotlib.animation`.

    Notes
    -----
    This function is experimental; its behavior may be changed or extended in a
    future release.
    """
    manager = _pylab_helpers.Gcf.get_active()
    if manager is not None:
        canvas = manager.canvas
        if canvas.figure.stale:
            canvas.draw_idle()
        show(block=False)
        canvas.start_event_loop(interval)
    else:
        time.sleep(interval) 
Example #5
Source File: pyplot.py    From coffeegrindsize with MIT License 6 votes vote down vote up
def pause(interval):
    """
    Pause for *interval* seconds.

    If there is an active figure, it will be updated and displayed before the
    pause, and the GUI event loop (if any) will run during the pause.

    This can be used for crude animation.  For more complex animation, see
    :mod:`matplotlib.animation`.

    Notes
    -----
    This function is experimental; its behavior may be changed or extended in a
    future release.
    """
    manager = _pylab_helpers.Gcf.get_active()
    if manager is not None:
        canvas = manager.canvas
        if canvas.figure.stale:
            canvas.draw_idle()
        show(block=False)
        canvas.start_event_loop(interval)
    else:
        time.sleep(interval) 
Example #6
Source File: mpl_animate.py    From phoebe2 with GNU General Public License v3.0 6 votes vote down vote up
def anim_to_html(anim):
    """
    adapted from: http://jakevdp.github.io/blog/2013/05/12/embedding-matplotlib-animations/

    This function converts and animation object from matplotlib into HTML which can then
    be embedded in an IPython notebook.

    This requires ffmpeg to be installed in order to build the intermediate mp4 file

    To get these to display automatically, you need to set animation.Animation._repr_html_ = plotlib.anim_to_html
    (this is done on your behalf by PHOEBE)
    """
    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)

# setup hooks for inline animations in IPython notebooks 
Example #7
Source File: customqtwidgets.py    From Openroast with GNU General Public License v3.0 6 votes vote down vote up
def create_graph(self):
        # Create the graph widget.
        graphWidget = QtWidgets.QWidget()
        graphWidget.setObjectName("graph")

        # Style attributes of matplotlib.
        matplotlib.rcParams['lines.linewidth'] = 3
        matplotlib.rcParams['lines.color'] = '#2a2a2a'
        matplotlib.rcParams['font.size'] = 10.
        self.graphFigure = Figure(facecolor='#444952')
        self.graphCanvas = FigureCanvas(self.graphFigure)

        # Add graph widgets to layout for graph.
        graphVerticalBox = QtWidgets.QVBoxLayout()
        graphVerticalBox.addWidget(self.graphCanvas)
        graphWidget.setLayout(graphVerticalBox)

        # Animate the the graph with new data
        if self.animated:
            self.animateGraph = animation.FuncAnimation(self.graphFigure,
                self.graph_draw, interval=1000)
        else:
            self.graph_draw()

        return graphWidget 
Example #8
Source File: test_plots_matplotlib.py    From arviz with Apache License 2.0 6 votes vote down vote up
def test_plot_ppc(models, kind, alpha, animated):
    if animation and not animation.writers.is_available("ffmpeg"):
        pytest.skip("matplotlib animations within ArviZ require ffmpeg")
    animation_kwargs = {"blit": False}
    axes = plot_ppc(
        models.model_1,
        kind=kind,
        alpha=alpha,
        animated=animated,
        animation_kwargs=animation_kwargs,
        random_seed=3,
    )
    if animated:
        assert axes[0]
        assert axes[1]
    assert axes 
Example #9
Source File: pyplot.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def pause(interval):
    """
    Pause for *interval* seconds.

    If there is an active figure, it will be updated and displayed before the
    pause, and the GUI event loop (if any) will run during the pause.

    This can be used for crude animation.  For more complex animation, see
    :mod:`matplotlib.animation`.

    Notes
    -----
    This function is experimental; its behavior may be changed or extended in a
    future release.
    """
    manager = _pylab_helpers.Gcf.get_active()
    if manager is not None:
        canvas = manager.canvas
        if canvas.figure.stale:
            canvas.draw_idle()
        show(block=False)
        canvas.start_event_loop(interval)
    else:
        time.sleep(interval) 
Example #10
Source File: pyplot.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def pause(interval):
    """
    Pause for *interval* seconds.

    If there is an active figure, it will be updated and displayed before the
    pause, and the GUI event loop (if any) will run during the pause.

    This can be used for crude animation.  For more complex animation, see
    :mod:`matplotlib.animation`.

    Notes
    -----
    This function is experimental; its behavior may be changed or extended in a
    future release.
    """
    manager = _pylab_helpers.Gcf.get_active()
    if manager is not None:
        canvas = manager.canvas
        if canvas.figure.stale:
            canvas.draw_idle()
        show(block=False)
        canvas.start_event_loop(interval)
    else:
        time.sleep(interval) 
Example #11
Source File: scrapers.py    From sphinx-gallery with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _anim_rst(anim, image_path, gallery_conf):
    from matplotlib.animation import ImageMagickWriter
    # output the thumbnail as the image, as it will just be copied
    # if it's the file thumbnail
    fig = anim._fig
    image_path = image_path.replace('.png', '.gif')
    fig_size = fig.get_size_inches()
    thumb_size = gallery_conf['thumbnail_size']
    use_dpi = round(
        min(t_s / f_s for t_s, f_s in zip(thumb_size, fig_size)))
    # FFmpeg is buggy for GIFs
    if ImageMagickWriter.isAvailable():
        writer = 'imagemagick'
    else:
        writer = None
    anim.save(image_path, writer=writer, dpi=use_dpi)
    html = anim._repr_html_()
    if html is None:  # plt.rcParams['animation.html'] == 'none'
        html = anim.to_jshtml()
    html = indent(html, '         ')
    return _ANIMATION_RST.format(html) 
Example #12
Source File: pursuit_evade.py    From MADRL with MIT License 5 votes vote down vote up
def animate(self, act_fn, nsteps, file_name, rate=1.5, verbose=False):
        """
            Save an animation to an mp4 file.
        """
        plt.figure(0)
        # run sim loop
        o = self.reset()
        file_path = "/".join(file_name.split("/")[0:-1])
        temp_name = join(file_path, "temp_0.png")
        # generate .pngs
        self.save_image(temp_name)
        removed = 0
        for i in range(nsteps):
            a = act_fn(o)
            o, r, done, info = self.step(a)
            temp_name = join(file_path, "temp_" + str(i + 1) + ".png")
            self.save_image(temp_name)
            removed += info['removed']
            if verbose:
                print(r, info)
            if done:
                break
        if verbose:
            print("Total removed:", removed)
        # use ffmpeg to create .pngs to .mp4 movie
        ffmpeg_cmd = "ffmpeg -framerate " + str(rate) + " -i " + join(
            file_path, "temp_%d.png") + " -c:v libx264 -pix_fmt yuv420p " + file_name
        call(ffmpeg_cmd.split())
        # clean-up by removing .pngs
        map(os.remove, glob.glob(join(file_path, "temp_*.png"))) 
Example #13
Source File: viz.py    From dgl with Apache License 2.0 5 votes vote down vote up
def att_animation(maps_array, mode, src, tgt, head_id):
    weights = [maps[mode2id[mode]][head_id] for maps in maps_array]
    fig, axes = plt.subplots(1, 2)

    def weight_animate(i):
        global colorbar
        if colorbar:
            colorbar.remove()
        plt.cla()
        axes[0].set_title('heatmap')
        axes[0].set_yticks(np.arange(len(src)))
        axes[0].set_xticks(np.arange(len(tgt)))
        axes[0].set_yticklabels(src)
        axes[0].set_xticklabels(tgt)
        plt.setp(axes[0].get_xticklabels(), rotation=45, ha="right",
                 rotation_mode="anchor")

        fig.suptitle('epoch {}'.format(i))
        weight = weights[i].transpose(-1, -2)
        heatmap = axes[0].pcolor(weight, vmin=0, vmax=1, cmap=plt.cm.Blues)
        colorbar = plt.colorbar(heatmap, ax=axes[0], fraction=0.046, pad=0.04)
        axes[0].set_aspect('equal')
        axes[1].axis("off")
        graph_att_head(src, tgt, weight, axes[1], 'graph')


    ani = animation.FuncAnimation(fig, weight_animate, frames=len(weights), interval=500, repeat_delay=2000)
    return ani 
Example #14
Source File: pyplot.py    From Computable with MIT License 5 votes vote down vote up
def pause(interval):
    """
    Pause for *interval* seconds.

    If there is an active figure it will be updated and displayed,
    and the GUI event loop will run during the pause.

    If there is no active figure, or if a non-interactive backend
    is in use, this executes time.sleep(interval).

    This can be used for crude animation. For more complex
    animation, see :mod:`matplotlib.animation`.

    This function is experimental; its behavior may be changed
    or extended in a future release.

    """
    backend = rcParams['backend']
    if backend in _interactive_bk:
        figManager = _pylab_helpers.Gcf.get_active()
        if figManager is not None:
            canvas = figManager.canvas
            canvas.draw()
            show(block=False)
            canvas.start_event_loop(interval)
            return

    # No on-screen figure is active, so sleep() is all we need.
    import time
    time.sleep(interval) 
Example #15
Source File: starwarps.py    From eht-imaging with GNU General Public License v3.0 5 votes vote down vote up
def movie(im_List, out='movie.mp4', fps=10, dpi=120):
    import matplotlib
    matplotlib.use('agg')
    import matplotlib.pyplot as plt
    import matplotlib.animation as animation

    fig = plt.figure()
    frame = im_List[0].imvec #read_auto(filelist[len(filelist)/2])
    fov = im_List[0].psize*im_List[0].xdim
    extent = fov * np.array((1,-1,-1,1)) / 2.
    maxi = np.max(frame)
    im = plt.imshow( np.reshape(frame,[im_List[0].xdim, im_List[0].xdim]) , cmap='hot', extent=extent) #inferno
    plt.colorbar()
    im.set_clim([0,maxi])
    fig.set_size_inches([5,5])
    plt.tight_layout()

    def update_img(n):
        sys.stdout.write('\rprocessing image %i of %i ...' % (n,len(im_List)) )
        sys.stdout.flush()
        im.set_data(np.reshape(im_List[n].imvec, [im_List[n].xdim, im_List[n].xdim]) )
        return im

    ani = animation.FuncAnimation(fig,update_img,len(im_List),interval=1e3/fps)
    writer = animation.writers['ffmpeg'](fps=max(20, fps), bitrate=1e6)
    ani.save(out,writer=writer,dpi=dpi) 
Example #16
Source File: maps.py    From starry with MIT License 5 votes vote down vote up
def render(self, **kwargs):
        """
        Compute and return the intensity of the map on a grid.

        Returns an image of shape ``(res, res)``, unless ``theta`` is a vector,
        in which case returns an array of shape ``(nframes, res, res)``, where
        ``nframes`` is the number of values of ``theta``. However, if this is
        a spectral map, ``nframes`` is the number of wavelength bins and
        ``theta`` must be a scalar.

        Args:
            res (int, optional): The resolution of the map in pixels on a
                side. Defaults to 300.
            projection (string, optional): The map projection. Accepted
                values are ``ortho``, corresponding to an orthographic
                projection (as seen on the sky), ``rect``, corresponding
                to an equirectangular latitude-longitude projection,
                and ``moll``, corresponding to a Mollweide equal-area
                projection. Defaults to ``ortho``.
            theta (scalar or vector, optional): The map rotation phase in
                units of :py:attr:`angle_unit`. If this is a vector, an
                animation is generated. Defaults to ``0.0``.
            rv (bool, optional): If True, computes the velocity-weighted
                intensity instead. Defaults to True.
        """
        # Render the velocity map if `rv==True`
        # Override the `projection` kwarg if we're
        # plotting the radial velocity.
        rv = kwargs.pop("rv", True)
        if rv:
            kwargs.pop("projection", None)
            self._set_RV_filter()
        res = super(RVBase, self).render(**kwargs)
        if rv:
            self._unset_RV_filter()
        return res 
Example #17
Source File: movie.py    From kvae with MIT License 5 votes vote down vote up
def save_true_generated_frames(true, generated, filename):
    num_sequences, n_steps, w, h = true.shape

    # Background is 0, foreground as 1
    true = np.copy(true[:16])
    true[true > 0.1] = 1

    # Set foreground be near 0.5
    generated = generated * .5

    # Background is 1, foreground is near 0.5
    generated = 1 - generated[:16, :n_steps]

    # Subtract true from generated so background is 1, true foreground is 0,
    # and generated foreground is around 0.5
    images = generated - true
    # images[images > 0.5] = 1.

    fig = plt.figure()
    im = plt.imshow(combine_multiple_img(images[:, 0]), cmap=plt.cm.get_cmap('gist_heat'),
                    interpolation='none', vmin=0, vmax=1)
    plt.axis('image')

    def updatefig(*args):
        im.set_array(combine_multiple_img(images[:, args[0]]))
        return im,

    ani = animation.FuncAnimation(fig, updatefig, interval=500, frames=n_steps)

    try:
        writer = animation.writers['avconv']
    except KeyError:
        writer = animation.writers['ffmpeg']
    writer = writer(fps=3)
    ani.save(filename, writer=writer)
    plt.close(fig) 
Example #18
Source File: test_plots_matplotlib.py    From arviz with Apache License 2.0 5 votes vote down vote up
def test_plot_ppc_discrete(kind, animated):
    if animation and not animation.writers.is_available("ffmpeg"):
        pytest.skip("matplotlib animations within ArviZ require ffmpeg")
    data = from_dict(
        observed_data={"obs": np.random.randint(1, 100, 15)},
        posterior_predictive={"obs": np.random.randint(1, 300, (1, 20, 15))},
    )

    animation_kwargs = {"blit": False}
    axes = plot_ppc(data, kind=kind, animated=animated, animation_kwargs=animation_kwargs)
    if animated:
        assert np.all(axes[0])
        assert np.all(axes[1])
    assert axes 
Example #19
Source File: asthama_search.py    From pepper-robot-programming with MIT License 5 votes vote down vote up
def run(self):
        self._printLogs("Waiting for the robot to be in wake up position", "OKBLUE")

        self.motion_service.wakeUp()
        self.posture_service.goToPosture("StandInit", 0.1)

        self.create_callbacks()
        # self.startDLServer()
        self._addTopic()

        # graphplots
        self._initialisePlot()
        ani = animation.FuncAnimation(self.fig, self._animate, blit=False, interval=500 ,repeat=False)


        # loop on, wait for events until manual interruption
        try:
            # while True:
            #     time.sleep(1)
            # starting graph plot
            plt.show() # blocking call hence no need for while(True)

        except KeyboardInterrupt:
            self._printLogs("Interrupted by user, shutting down", "FAIL")
            self._cleanUp()

            self._printLogs("Waiting for the robot to be in rest position", "FAIL")
            # self.motion_service.rest()
            sys.exit(0)

        return 
Example #20
Source File: pyplot.py    From matplotlib-4-abaqus with MIT License 5 votes vote down vote up
def pause(interval):
    """
    Pause for *interval* seconds.

    If there is an active figure it will be updated and displayed,
    and the GUI event loop will run during the pause.

    If there is no active figure, or if a non-interactive backend
    is in use, this executes time.sleep(interval).

    This can be used for crude animation. For more complex
    animation, see :mod:`matplotlib.animation`.

    This function is experimental; its behavior may be changed
    or extended in a future release.

    """
    backend = rcParams['backend']
    if backend in _interactive_bk:
        figManager = _pylab_helpers.Gcf.get_active()
        if figManager is not None:
            canvas = figManager.canvas
            canvas.draw()
            show(block=False)
            canvas.start_event_loop(interval)
            return

    # No on-screen figure is active, so sleep() is all we need.
    import time
    time.sleep(interval) 
Example #21
Source File: quakeplot.py    From QuakeMigrate with MIT License 5 votes vote down vote up
def coalescence_video(self, file_str):
        """
        Generate a video over the marginal window showing the coalescence map
        and expected arrival times overlain on the station traces.

        Parameters
        ----------
        file_str : str
            String {run_name}_{event_name}

        """

        # Find index of start and end of marginal window
        idx0 = np.where(self.times == self.event_mw_data["DT"].iloc[0])[0][0]
        idx1 = np.where(self.times == self.event_mw_data["DT"].iloc[-1])[0][0]

        Writer = animation.writers["ffmpeg"]
        writer = Writer(fps=4, metadata=dict(artist="Ulvetanna"), bitrate=1800)

        fig = self._coalescence_frame(idx0)
        ani = animation.FuncAnimation(fig, self._video_update,
                                      frames=np.linspace(idx0+1, idx1, 200),
                                      blit=False, repeat=False)

        subdir = "videos"
        util.make_directories(self.run_path, subdir=subdir)
        out_str = self.run_path / subdir / file_str
        ani.save("{}_CoalescenceVideo.mp4".format(out_str),
                 writer=writer) 
Example #22
Source File: status.py    From copycat with MIT License 5 votes vote down vote up
def __init__(self, parent, status, title):
        ttk.Frame.__init__(self, parent)
        self.status = status

        self.canvas = FigureCanvasTkAgg(status.figure, self)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)

        self.animation = animation.FuncAnimation(status.figure, lambda i : status.update_plots(i), interval=1000) 
Example #23
Source File: pyplot.py    From neural-network-animation with MIT License 5 votes vote down vote up
def pause(interval):
    """
    Pause for *interval* seconds.

    If there is an active figure it will be updated and displayed,
    and the GUI event loop will run during the pause.

    If there is no active figure, or if a non-interactive backend
    is in use, this executes time.sleep(interval).

    This can be used for crude animation. For more complex
    animation, see :mod:`matplotlib.animation`.

    This function is experimental; its behavior may be changed
    or extended in a future release.

    """
    backend = rcParams['backend']
    if backend in _interactive_bk:
        figManager = _pylab_helpers.Gcf.get_active()
        if figManager is not None:
            canvas = figManager.canvas
            canvas.draw()
            show(block=False)
            canvas.start_event_loop(interval)
            return

    # No on-screen figure is active, so sleep() is all we need.
    import time
    time.sleep(interval) 
Example #24
Source File: generate_videos.py    From multilabel-image-classification-tensorflow with MIT License 4 votes vote down vote up
def MakeImitationVideo(
    outdir, vidname, query_im_strs, knn_im_strs, height=640, width=360):
  """Creates a KNN imitation video.

  For each frame in vid0, pair with the frame at index in knn_indices in
  vids1. Write video to disk.

  Args:
    outdir: String, directory to write videos.
    vidname: String, name of video.
    query_im_strs: Numpy array holding query image strings.
    knn_im_strs: Numpy array holding knn image strings.
    height: Int, height of raw images.
    width: Int, width of raw images.
  """
  if not tf.gfile.Exists(outdir):
    tf.gfile.MakeDirs(outdir)
  vid_path = os.path.join(outdir, vidname)
  combined = zip(query_im_strs, knn_im_strs)

  # Create and write the video.
  fig = plt.figure()
  ax = fig.add_subplot(111)
  ax.set_aspect('equal')
  ax.get_xaxis().set_visible(False)
  ax.get_yaxis().set_visible(False)
  im = ax.imshow(
      np.zeros((height, width*2, 3)), cmap='gray', interpolation='nearest')
  im.set_clim([0, 1])
  plt.tight_layout(pad=0, w_pad=0, h_pad=0)
  # pylint: disable=invalid-name
  def update_img(pair):
    """Decode pairs of image strings, update a video."""
    im_i, im_j = pair
    nparr_i = np.fromstring(str(im_i), np.uint8)
    img_np_i = cv2.imdecode(nparr_i, 1)
    img_np_i = img_np_i[..., [2, 1, 0]]
    nparr_j = np.fromstring(str(im_j), np.uint8)
    img_np_j = cv2.imdecode(nparr_j, 1)
    img_np_j = img_np_j[..., [2, 1, 0]]

    # Optionally reshape the images to be same size.
    frame = np.concatenate([img_np_i, img_np_j], axis=1)
    im.set_data(frame)
    return im
  ani = animation.FuncAnimation(fig, update_img, combined, interval=15)
  writer = animation.writers['ffmpeg'](fps=15)
  dpi = 100
  tf.logging.info('Writing video to:\n %s \n' % vid_path)
  ani.save('%s.mp4' % vid_path, writer=writer, dpi=dpi) 
Example #25
Source File: generate_videos.py    From models with Apache License 2.0 4 votes vote down vote up
def MakeImitationVideo(
    outdir, vidname, query_im_strs, knn_im_strs, height=640, width=360):
  """Creates a KNN imitation video.

  For each frame in vid0, pair with the frame at index in knn_indices in
  vids1. Write video to disk.

  Args:
    outdir: String, directory to write videos.
    vidname: String, name of video.
    query_im_strs: Numpy array holding query image strings.
    knn_im_strs: Numpy array holding knn image strings.
    height: Int, height of raw images.
    width: Int, width of raw images.
  """
  if not tf.gfile.Exists(outdir):
    tf.gfile.MakeDirs(outdir)
  vid_path = os.path.join(outdir, vidname)
  combined = zip(query_im_strs, knn_im_strs)

  # Create and write the video.
  fig = plt.figure()
  ax = fig.add_subplot(111)
  ax.set_aspect('equal')
  ax.get_xaxis().set_visible(False)
  ax.get_yaxis().set_visible(False)
  im = ax.imshow(
      np.zeros((height, width*2, 3)), cmap='gray', interpolation='nearest')
  im.set_clim([0, 1])
  plt.tight_layout(pad=0, w_pad=0, h_pad=0)
  # pylint: disable=invalid-name
  def update_img(pair):
    """Decode pairs of image strings, update a video."""
    im_i, im_j = pair
    nparr_i = np.fromstring(str(im_i), np.uint8)
    img_np_i = cv2.imdecode(nparr_i, 1)
    img_np_i = img_np_i[..., [2, 1, 0]]
    nparr_j = np.fromstring(str(im_j), np.uint8)
    img_np_j = cv2.imdecode(nparr_j, 1)
    img_np_j = img_np_j[..., [2, 1, 0]]

    # Optionally reshape the images to be same size.
    frame = np.concatenate([img_np_i, img_np_j], axis=1)
    im.set_data(frame)
    return im
  ani = animation.FuncAnimation(fig, update_img, combined, interval=15)
  writer = animation.writers['ffmpeg'](fps=15)
  dpi = 100
  tf.logging.info('Writing video to:\n %s \n' % vid_path)
  ani.save('%s.mp4' % vid_path, writer=writer, dpi=dpi) 
Example #26
Source File: generate_videos.py    From g-tensorflow-models with Apache License 2.0 4 votes vote down vote up
def MakeImitationVideo(
    outdir, vidname, query_im_strs, knn_im_strs, height=640, width=360):
  """Creates a KNN imitation video.

  For each frame in vid0, pair with the frame at index in knn_indices in
  vids1. Write video to disk.

  Args:
    outdir: String, directory to write videos.
    vidname: String, name of video.
    query_im_strs: Numpy array holding query image strings.
    knn_im_strs: Numpy array holding knn image strings.
    height: Int, height of raw images.
    width: Int, width of raw images.
  """
  if not tf.gfile.Exists(outdir):
    tf.gfile.MakeDirs(outdir)
  vid_path = os.path.join(outdir, vidname)
  combined = zip(query_im_strs, knn_im_strs)

  # Create and write the video.
  fig = plt.figure()
  ax = fig.add_subplot(111)
  ax.set_aspect('equal')
  ax.get_xaxis().set_visible(False)
  ax.get_yaxis().set_visible(False)
  im = ax.imshow(
      np.zeros((height, width*2, 3)), cmap='gray', interpolation='nearest')
  im.set_clim([0, 1])
  plt.tight_layout(pad=0, w_pad=0, h_pad=0)
  # pylint: disable=invalid-name
  def update_img(pair):
    """Decode pairs of image strings, update a video."""
    im_i, im_j = pair
    nparr_i = np.fromstring(str(im_i), np.uint8)
    img_np_i = cv2.imdecode(nparr_i, 1)
    img_np_i = img_np_i[..., [2, 1, 0]]
    nparr_j = np.fromstring(str(im_j), np.uint8)
    img_np_j = cv2.imdecode(nparr_j, 1)
    img_np_j = img_np_j[..., [2, 1, 0]]

    # Optionally reshape the images to be same size.
    frame = np.concatenate([img_np_i, img_np_j], axis=1)
    im.set_data(frame)
    return im
  ani = animation.FuncAnimation(fig, update_img, combined, interval=15)
  writer = animation.writers['ffmpeg'](fps=15)
  dpi = 100
  tf.logging.info('Writing video to:\n %s \n' % vid_path)
  ani.save('%s.mp4' % vid_path, writer=writer, dpi=dpi) 
Example #27
Source File: generate_videos.py    From yolo_v2 with Apache License 2.0 4 votes vote down vote up
def MakeImitationVideo(
    outdir, vidname, query_im_strs, knn_im_strs, height=640, width=360):
  """Creates a KNN imitation video.

  For each frame in vid0, pair with the frame at index in knn_indices in
  vids1. Write video to disk.

  Args:
    outdir: String, directory to write videos.
    vidname: String, name of video.
    query_im_strs: Numpy array holding query image strings.
    knn_im_strs: Numpy array holding knn image strings.
    height: Int, height of raw images.
    width: Int, width of raw images.
  """
  if not tf.gfile.Exists(outdir):
    tf.gfile.MakeDirs(outdir)
  vid_path = os.path.join(outdir, vidname)
  combined = zip(query_im_strs, knn_im_strs)

  # Create and write the video.
  fig = plt.figure()
  ax = fig.add_subplot(111)
  ax.set_aspect('equal')
  ax.get_xaxis().set_visible(False)
  ax.get_yaxis().set_visible(False)
  im = ax.imshow(
      np.zeros((height, width*2, 3)), cmap='gray', interpolation='nearest')
  im.set_clim([0, 1])
  plt.tight_layout(pad=0, w_pad=0, h_pad=0)
  # pylint: disable=invalid-name
  def update_img(pair):
    """Decode pairs of image strings, update a video."""
    im_i, im_j = pair
    nparr_i = np.fromstring(str(im_i), np.uint8)
    img_np_i = cv2.imdecode(nparr_i, 1)
    img_np_i = img_np_i[..., [2, 1, 0]]
    nparr_j = np.fromstring(str(im_j), np.uint8)
    img_np_j = cv2.imdecode(nparr_j, 1)
    img_np_j = img_np_j[..., [2, 1, 0]]

    # Optionally reshape the images to be same size.
    frame = np.concatenate([img_np_i, img_np_j], axis=1)
    im.set_data(frame)
    return im
  ani = animation.FuncAnimation(fig, update_img, combined, interval=15)
  writer = animation.writers['ffmpeg'](fps=15)
  dpi = 100
  tf.logging.info('Writing video to:\n %s \n' % vid_path)
  ani.save('%s.mp4' % vid_path, writer=writer, dpi=dpi) 
Example #28
Source File: generate_videos.py    From object_detection_with_tensorflow with MIT License 4 votes vote down vote up
def MakeImitationVideo(
    outdir, vidname, query_im_strs, knn_im_strs, height=640, width=360):
  """Creates a KNN imitation video.

  For each frame in vid0, pair with the frame at index in knn_indices in
  vids1. Write video to disk.

  Args:
    outdir: String, directory to write videos.
    vidname: String, name of video.
    query_im_strs: Numpy array holding query image strings.
    knn_im_strs: Numpy array holding knn image strings.
    height: Int, height of raw images.
    width: Int, width of raw images.
  """
  if not tf.gfile.Exists(outdir):
    tf.gfile.MakeDirs(outdir)
  vid_path = os.path.join(outdir, vidname)
  combined = zip(query_im_strs, knn_im_strs)

  # Create and write the video.
  fig = plt.figure()
  ax = fig.add_subplot(111)
  ax.set_aspect('equal')
  ax.get_xaxis().set_visible(False)
  ax.get_yaxis().set_visible(False)
  im = ax.imshow(
      np.zeros((height, width*2, 3)), cmap='gray', interpolation='nearest')
  im.set_clim([0, 1])
  plt.tight_layout(pad=0, w_pad=0, h_pad=0)
  # pylint: disable=invalid-name
  def update_img(pair):
    """Decode pairs of image strings, update a video."""
    im_i, im_j = pair
    nparr_i = np.fromstring(str(im_i), np.uint8)
    img_np_i = cv2.imdecode(nparr_i, 1)
    img_np_i = img_np_i[..., [2, 1, 0]]
    nparr_j = np.fromstring(str(im_j), np.uint8)
    img_np_j = cv2.imdecode(nparr_j, 1)
    img_np_j = img_np_j[..., [2, 1, 0]]

    # Optionally reshape the images to be same size.
    frame = np.concatenate([img_np_i, img_np_j], axis=1)
    im.set_data(frame)
    return im
  ani = animation.FuncAnimation(fig, update_img, combined, interval=15)
  writer = animation.writers['ffmpeg'](fps=15)
  dpi = 100
  tf.logging.info('Writing video to:\n %s \n' % vid_path)
  ani.save('%s.mp4' % vid_path, writer=writer, dpi=dpi) 
Example #29
Source File: bang.py    From pyclustering with GNU General Public License v3.0 4 votes vote down vote up
def animate(self, animation_velocity=75, movie_fps=25, movie_filename=None):
        """!
        @brief Animates clustering process that is performed by BANG algorithm.

        @param[in] animation_velocity (uint): Interval between frames in milliseconds (for run-time animation only).
        @param[in] movie_fps (uint): Defines frames per second (for rendering movie only).
        @param[in] movie_filename (string): If it is specified then animation will be stored to file that is specified in this parameter.

        """
        def init_frame():
            self.__figure.clf()
            self.__ax = self.__figure.add_subplot(1, 1, 1)
            self.__figure.suptitle("BANG algorithm", fontsize=18, fontweight='bold')

            for point in self.__directory.get_data():
                self.__ax.plot(point[0], point[1], color='red', marker='.')

            return frame_generation(0)


        def frame_generation(index_iteration):
            if self.__current_level < self.__directory.get_height():
                block = self.__level_blocks[self.__current_block]
                self.__draw_block(block)
                self.__increment_block()

            else:
                if self.__special_frame == 0:
                    self.__draw_leaf_density()

                elif self.__special_frame == 15:
                    self.__draw_clusters()

                elif self.__special_frame == 30:
                    self.__figure.clf()
                    self.__ax = self.__figure.add_subplot(1, 1, 1)
                    self.__figure.suptitle("BANG algorithm", fontsize=18, fontweight='bold')

                    self.__draw_clusters()

                self.__special_frame += 1



        iterations = len(self.__directory) + 60
        # print("Total number of iterations: %d" % iterations)
        cluster_animation = animation.FuncAnimation(self.__figure, frame_generation, iterations,
                                                    interval=animation_velocity,
                                                    init_func=init_frame,
                                                    repeat_delay=5000)

        if movie_filename is not None:
            cluster_animation.save(movie_filename, writer = 'ffmpeg', fps = movie_fps, bitrate = 3500)
        else:
            plt.show() 
Example #30
Source File: variable_describe.py    From convis with GNU General Public License v3.0 4 votes vote down vote up
def animate_to_html(ar,skip=10,interval=100,scrolling_plot=False,window_length=200):
    """animates a 3d or 5d array in a jupyter notebook

    Returns a Jupyter HTML object containing an embedded 
    javascript animated plot.

    Parameters
    ----------
    ar (np.array):
        3d or 5d array to animate
    skip (int):
        the animation skips this many timesteps
        between two frames.
        When generating an html plot or video for long
        sequences, this should be set to a higher value
        to keep the video short
    interval (int):
        number of milliseconds between two animation
        frames
    scrolling_plot (bool):
        whether to plot the spatial and temporal plots
        or only the spatial animation
    window_length (int):
        if `scrolling_plot` is `True`, specifies
        the length of the time window displayed

    Examples
    --------

        >>> %matplotlib notebook
        >>> import convis
        >>> inp = convis.samples.moving_grating(5000)
        >>> convis.variable_describe.animate_to_html(inp)
        <HTML javascript plot embedded in the notebook>

    See Also
    --------
    convis.variable_describe.animate
    """
    if scrolling_plot:
        anim = animate_double_plot(ar,skip=skip,interval=interval,window_length=window_length)
    else:
        anim = animate(ar,skip=skip,interval=interval)
    from IPython.display import HTML
    return HTML(anim.to_jshtml())