Beispiel #1
0
def render_video(width, height, duration, filename, bg_color=(0, 0, 0, 1)):
    """Render a video."""
    import numpy as np
    from moviepy.editor import VideoClip

    def make_frame(frame_num):

        surface = build_frame(
            width,
            height,
            height * 0.4,
            num_iters=11,
            num_points=3,
            r_mult=0.5,
            c_mult=0.5,
            d_angle=frame_num * 25 * 2 * math.pi / 300,
            bg_color=bg_color,
        )
        buf = surface.get_data()
        frame_uint32 = np.ndarray(shape=(height, width),
                                  dtype=np.uint32,
                                  buffer=buf)

        frame = np.zeros(shape=(height, width, 3), dtype=np.uint8)
        frame[:, :, 0] = ((frame_uint32 >> 16) & 0xff).astype(np.uint8)
        frame[:, :, 1] = ((frame_uint32 >> 8) & 0xff).astype(np.uint8)
        frame[:, :, 2] = (frame_uint32 & 0xff).astype(np.uint8)

        return frame

    # render video
    animation = VideoClip(make_frame, duration=duration)
    animation.write_gif(filename, fps=25)
Beispiel #2
0
    def make_gif(self, filename):
        def make_frame(t):
            fig = self.iterate(t)
            return mplfig_to_npimage(fig)

        animation = VideoClip(make_frame, duration=self.T_max)
        animation.write_gif(filename, fps=20)
Beispiel #3
0
def test_matplotlib():
    if PYTHON_VERSION in ('2.7', '3.3'):
        return

    #for now, python 3.5 installs a version of matplotlib that complains
    #about $DISPLAY variable, so lets just ignore for now.
    if PYTHON_VERSION == '3.5' and TRAVIS:
        return

    import matplotlib.pyplot as plt
    import numpy as np
    from moviepy.editor import VideoClip
    from moviepy.video.io.bindings import mplfig_to_npimage

    x = np.linspace(-2, 2, 200)

    duration = 2

    fig, ax = plt.subplots()

    def make_frame(t):
        ax.clear()
        ax.plot(x, np.sinc(x**2) + np.sin(x + 2 * np.pi / duration * t), lw=3)
        ax.set_ylim(-1.5, 2.5)
        return mplfig_to_npimage(fig)

    animation = VideoClip(make_frame, duration=duration)
    animation.write_gif(os.path.join(TMP_DIR, 'matplotlib.gif'), fps=20)
Beispiel #4
0
def test_matplotlib():
    #for now, python 3.5 installs a version of matplotlib that complains
    #about $DISPLAY variable, so lets just ignore for now.
    if sys.version_info < (3, 4):
        return

    if sys.version_info.major == 3 and sys.version_info.minor == 5:
        return

    import matplotlib.pyplot as plt
    import numpy as np
    from moviepy.editor import VideoClip
    from moviepy.video.io.bindings import mplfig_to_npimage

    x = np.linspace(-2, 2, 200)

    duration = 2

    fig, ax = plt.subplots()

    def make_frame(t):
        ax.clear()
        ax.plot(x, np.sinc(x**2) + np.sin(x + 2 * np.pi / duration * t), lw=3)
        ax.set_ylim(-1.5, 2.5)
        return mplfig_to_npimage(fig)

    animation = VideoClip(make_frame, duration=duration)
    animation.write_gif('/tmp/matplotlib.gif', fps=20)
Beispiel #5
0
def render_gif(pov_file, args):
    prog_args = []
    FPS = None
    initial_clock = 0
    final_clock = None
    for arg in args:
        if '=' in arg:
            key, value = arg.split('=')
            key = key.strip().lower()
            if key == 'initial_clock':
                initial_clock = float(value)
            elif key == 'final_clock':
                final_clock = float(value)
            elif key == 'fps':
                FPS = float(value)
            else:
                prog_args.append(arg)
        else:
            prog_args.append(arg)

    if final_clock is None:
        raise ValueError('Final_Clock must be set at top of file')

    if FPS is None:
        raise ValueError('FPS must be set at top of file')

    make_frame = frame_gen(pov_file, prog_args, initial_clock)
    clip = VideoClip(make_frame, duration=final_clock - initial_clock)
    output_gif = pov_file.replace('.pov', '.gif')
    clip.write_gif(output_gif, fps=FPS, program='ffmpeg')
Beispiel #6
0
    def make_gif(self, file_name):
        def make_frame(t):
            fig = self.iterate(t)
            img = mplfig_to_npimage(fig)
            plt.close(fig)
            return img

        animation = VideoClip(make_frame, duration=self.duration)
        animation.write_gif(file_name, fps=self.fps)
Beispiel #7
0
def plot_voxels(gridLabels,
                suncg_labels,
                vox_min,
                vox_unit,
                save_path=None,
                animate=False):
    nbr_classes = len(suncg_labels)

    canvas = scene.SceneCanvas(keys='interactive',
                               bgcolor='w',
                               size=(1920, 1080))
    view = canvas.central_widget.add_view()
    azimuth = 30
    view.camera = scene.TurntableCamera(up='y',
                                        distance=4,
                                        fov=70,
                                        azimuth=azimuth,
                                        elevation=30.)

    # Sample colormap and adjust alpha
    colormap = get_colormap('cubehelix')
    cm_sampled = []
    for i, (iclass, sample_f) in enumerate(
            zip(suncg_labels, np.linspace(0, 1, nbr_classes))):
        if iclass.lower() in ('free', 'ceiling'):
            alpha = 0
        elif iclass.lower() in ('floor', 'wall', 'window'):
            alpha = 0.6
        else:
            alpha = 1.0
        cm_sampled.append(Color(color=colormap[sample_f].rgb, alpha=alpha))
    my_cm = AlphaAwareCM(cm_sampled)

    volume = scene.visuals.Volume(gridLabels,
                                  relative_step_size=0.1,
                                  method='mip',
                                  parent=view.scene,
                                  cmap=my_cm,
                                  clim=[0, nbr_classes - 1],
                                  emulate_texture=False)
    volume.transform = scene.transforms.MatrixTransform()
    volume.transform.scale(3 * [vox_unit])
    volume.transform.translate(3 * [-vox_unit * gridLabels.shape[0] / 2.0])

    if save_path is None:
        return

    def make_frame(t):
        view.camera.set_state({'azimuth': azimuth + t * 90})
        return canvas.render()

    if animate:
        animation = VideoClip(make_frame, duration=3)
        animation.write_gif('voxel.gif', fps=8, opt='OptimizePlus')
    else:
        img = canvas.render()
        cv2.imwrite('voxel.png', img[::-1])
Beispiel #8
0
def save_movie(make_frame, duration, filename, fps=20):
    """Writes an animation to disk"""
    anim = VideoClip(make_frame, duration=duration)

    if filename.endswith('.gif'):
        anim.write_gif(filename, fps=fps)

    elif filename.endswith('.mp4'):
        anim.write_videofile(filename, fps=fps)

    else:
        raise ValueError(
            f'Invalid file type for {filename}. Must be .gif or .mp4')

    return anim
Beispiel #9
0
class Animation(object):
    def __init__(self, fps=24):
        self.fps = fps
        self.reset()

    def reset(self):
        self.frames = []
        self._iter = -1

    def add_frame(self, image):
        """
        image should be a (height, width, 3) np.ndarry
        """
        self.frames.append(np.copy(image))

    def anim_fn(self, fn, data):
        """
        fn: a function that returns a plot
        data: an iterable
        """
        for i in range(len(data)):
            p = fn(data[:i])
            self.add_frame(p.numpy())

    def rotate_3d(self, plot, duration=8):
        nframes = duration * self.fps
        change_angle = 360.0 / nframes
        azim = plot.canvas.azim
        for i in range(nframes):
            plot.set_camera(azim=azim + i * change_angle)
            self.frames.append(plot.numpy())

    def _make(self, t):
        self._iter += 1
        # Weird bug where idx might be = len(self.frames)
        idx = min(self._iter, len(self.frames) - 1)
        return self.frames[idx]

    def save(self, path):
        from moviepy.editor import VideoClip
        fname, ext = os.path.splitext(path)
        duration = (len(self.frames) - 1) / float(self.fps)
        self.animation = VideoClip(self._make, duration=duration)
        if 'gif' in ext:
            self.animation.write_gif(path, fps=self.fps)
        else:
            self.animation.write_videofile(path, fps=self.fps)
        self._iter = -1
Beispiel #10
0
    def generate_movie(self, file_name, file_type, **kwargs):
        """

        :param file_name:
        :param file_type: Either "gif" or "mp4"
        :param kwargs: Varying params for Fractal class
        :return: None
        """
        gen_movie = self.__generate_movie()

        def make_frame(t):
            """ returns a numpy array of the frame at time t """
            mat_points = next(gen_movie)
            return mat_to_color(point_to_image_mat(mat_points))

        clip = VideoClip(make_frame, duration=self.duration)  # duration-second clip
        # clip.write_videofile("my_animation.mp4", fps=24) # export as video
        clip.write_gif(file_name, fps=self.fps)  # export as GIF
def video_to_shortcuts(infile: str, outfile: str):
    video_cap = VideoFileClip(infile)
    frame_size = video_cap.size
    video_basic_info = {
        "frame_rate": video_cap.fps,
        "size": {
            "width": frame_size[0],
            "height": frame_size[1],
        },
        "time": video_cap.duration
    }
    with open(outfile + ".json", "w") as fp:
        json.dump(video_basic_info, fp)
    vc = VideoClip(make_frame=lambda t: video_cap.get_frame(
        (video_cap.duration - 3) * t / (img_count * duration)),
                   duration=img_count * duration)
    vc = vc.set_fps(math.ceil(1 / duration))
    vc.write_gif(outfile + ".gif")
Beispiel #12
0
    def show_animation(
            self,
            a_function_which_returns_an_image_according_to_a_time_variable,
            duration=3,
            fps=24,
            saving_path=None):
        """
        the function looks like `func(t)`.
        t is a float variable in seconds, for example, 1.2 = 1 second + 0.2 second
        """
        def wrap_function(t):
            array = a_function_which_returns_an_image_according_to_a_time_variable(
                t)
            assert isinstance(
                array,
                np.ndarray), "this function should return an numpy array"
            if array.shape[2] == 4:
                array = array[:, :, 0:3]

            return array

        animation = VideoClip(wrap_function, duration=duration)
        if self._notebook:
            result = animation.ipython_display(fps=fps,
                                               loop=True,
                                               autoplay=True)
            self._IPython.display.display(result)
        else:
            animation.preview(fps=fps)

        if saving_path != None:
            if len(saving_path.split(".")) > 0:
                extension = saving_path.split(".")[-1]
                if extension.lower() == "gif":
                    animation.write_gif(saving_path, fps=fps)
                elif extension.lower() == "mp4":
                    animation.write_videofile(saving_path, fps=fps)
                else:
                    print("you can only save gif or mp4!")
                    exit()
Beispiel #13
0
def play_svm():
    from sklearn import svm  # sklearn = scikit-learn
    from sklearn.datasets import make_moons

    X, Y = make_moons(50, noise=0.1, random_state=2)  # 半随机数据

    fig, ax = plt.subplots(1, figsize=(4, 4), facecolor=(1, 1, 1))
    fig.subplots_adjust(left=0, right=1, bottom=0)
    xx, yy = np.meshgrid(np.linspace(-2, 3, 500), np.linspace(-1, 2, 500))

    def make_frame(t):
        ax.clear()
        ax.axis('off')
        ax.set_title("SVC classification", fontsize=16)

        classifier = svm.SVC(gamma=2, C=1)

        # 不断变化的权重让数据点一个接一个的出现
        weights = np.minimum(1, np.maximum(0, t**2 + 10 - np.arange(50)))
        classifier.fit(X, Y, sample_weight=weights)
        Z = classifier.decision_function(np.c_[xx.ravel(), yy.ravel()])
        Z = Z.reshape(xx.shape)
        ax.contourf(xx,
                    yy,
                    Z,
                    cmap=plt.cm.bone,
                    alpha=0.8,
                    vmin=-2.5,
                    vmax=2.5,
                    levels=np.linspace(-2, 2, 20))
        ax.scatter(X[:, 0], X[:, 1], c=Y, s=50 * weights, cmap=plt.cm.bone)

        return mplfig_to_npimage(fig)

    animation = VideoClip(make_frame, duration=7)
    animation.write_gif("svm.gif", fps=15)
Beispiel #14
0
def scatter_plot_voxels(gridLabels,
                        suncg_labels,
                        vox_min,
                        vox_unit,
                        save_path=None,
                        animate=False):
    nbr_classes = len(suncg_labels)

    occMask = gridLabels > 0
    xyz = np.nonzero(occMask)
    positions = np.vstack([xyz[0], xyz[1], xyz[2]])
    gridLabelsMasked = gridLabels[occMask]

    canvas = scene.SceneCanvas(keys='interactive',
                               bgcolor='w',
                               size=(1920, 1080))
    view = canvas.central_widget.add_view()
    azimuth = 30
    view.camera = scene.TurntableCamera(up='y',
                                        distance=4,
                                        fov=70,
                                        azimuth=azimuth,
                                        elevation=30.)

    # Sample colormap and adjust alpha
    colormap = get_colormap('hsl',
                            value=1.0,
                            saturation=0.8,
                            ncolors=nbr_classes)
    pos_color = np.zeros((positions.shape[1], 4))
    cm_sampled = []
    for i, (iclass, sample_f) in enumerate(
            zip(suncg_labels[1:], np.linspace(0, 1, nbr_classes - 1))):
        if iclass.lower() in ('floor', 'wall', 'window'):
            alpha = 0.5
        elif iclass.lower() == 'ceiling':
            alpha = 0.0
        else:
            alpha = 1.0
        base_color = colormap[sample_f].rgba.flatten()
        base_color[3] = alpha
        pos_color[i == gridLabelsMasked] = base_color

    Scatter3D = scene.visuals.create_visual_node(visuals.MarkersVisual)
    p1 = Scatter3D(parent=view.scene)
    p1.set_gl_state('translucent', blend=True, depth_test=True)
    p1.set_data(positions.T,
                face_color=pos_color,
                symbol='disc',
                size=10,
                edge_width=0.5,
                edge_color='k')

    p1.transform = scene.transforms.MatrixTransform()
    p1.transform.scale(3 * [vox_unit])
    p1.transform.translate(3 * [-vox_unit * gridLabels.shape[0] / 2.0])

    if save_path is None:
        return

    def make_frame(t):
        view.camera.set_state({'azimuth': azimuth + t * 90})
        return canvas.render()

    if animate:
        animation = VideoClip(make_frame, duration=3)
        animation.write_gif('voxel.gif', fps=8, opt='OptimizePlus')
    else:
        img = canvas.render()
        cv2.imwrite('voxel.png', img[::-1])
	T01,Joint1 = PlanarTransformationMatrix(Angle1,[0,0],np.identity(4))
	T12,Joint2 = PlanarTransformationMatrix(Angle2,[0,-Length1],T01)
	T23,Endpoint = PlanarTransformationMatrix(0,[0,-Length2],T12)
	
	Radius = 0.5
	plt.figure()
	ax = plt.gca()
	plt.plot([0],[0],'ko')
	plt.plot([Joint1[0], Joint2[0], Endpoint[0]],[Joint1[1], Joint2[1], Endpoint[1]],"0.75",lw=3)
	plot_link(ax, Joint1, Radius, Length1, Angle1, Joint2,"0.55")
	plot_link(ax, Joint2, Radius, Length2, Angle1+Angle2, Endpoint, "0.55")
	quick_2D_plot_tool(ax,'x','y','Drawing Rotating Links')
	return(ax)

ax1 = plot_2_link_planar_model(np.pi/6,np.pi/6,5,5)
ax2 = plot_2_link_planar_model(np.pi/2,np.pi/2,4,3)
plt.imshow((ax1,ax2))

from moviepy.editor import VideoClip

def make_frame(t):
    frame_for_time_t = plot_2_link_planar_model(Angle1[t],Angle2[t],5,5)
    return frame_for_time_t # (Height x Width x 3) Numpy array
Angle1 = np.arange(0,np.pi,0.001)
Angle2 = np.arange(0,np.pi/2,0.0005)
animation = VideoClip(make_frame, duration=3) # 3-second clip

# For the export, many options/formats/optimizations are supported
animation.write_videofile("my_animation.mp4", fps=24) # export as video
animation.write_gif("my_animation.gif", fps=24) # export as GIF (slow)
def main(argv):
    
  
    animation = VideoClip(make_frame, duration=60) # durration is seconds
    animation.write_videofile("my_animation.mp4", fps=6) # export as video
    animation.write_gif("my_animation.gif", fps=6) # export as GIF (slow
Beispiel #17
0

def make_frame(t):
    """Deklarace callback funkce zavolane pri renderingu kazdeho snimku videa."""
    axis.clear()

    # vykreslení původní funkce
    axis.plot(x, y, label='sin(x)')

    # aproximace
    global order
    approx = ys(x, order)

    axis.plot(x, approx, label='order {o}'.format(o=order))
    order += 1

    # limity na ose y
    axis.set_ylim([-3, 3])
    axis.legend()

    # konverze na objekt typu "frame"
    return mplfig_to_npimage(fig)


# vytvoreni video klipu
animation = VideoClip(make_frame, duration=DURATION)

# export videa do formatu GIF
animation.write_gif('taylor_sinus.gif', fps=FPS)
# animation.write_videofile('taylor_sinus.ogv', fps=FPS)
Beispiel #18
0
def save_animation(filename,
                   pianoroll,
                   window,
                   hop=1,
                   fps=None,
                   is_drum=False,
                   beat_resolution=None,
                   downbeats=None,
                   preset="default",
                   cmap="Blues",
                   xtick="auto",
                   ytick="octave",
                   xticklabel=True,
                   yticklabel="auto",
                   tick_loc=None,
                   tick_direction="in",
                   label="both",
                   grid="both",
                   grid_linestyle=":",
                   grid_linewidth=0.5,
                   **kwargs):
    """
    Save a pianoroll to an animation in video or GIF format.

    Parameters
    ----------
    filename : str
        The filename to which the animation is saved.
    pianoroll : np.ndarray
        A pianoroll to be plotted. The values should be in [0, 1] when data type
        is float, and in [0, 127] when data type is integer.

        - For a 2D array, shape=(num_time_step, num_pitch).
        - For a 3D array, shape=(num_time_step, num_pitch, num_channel),
          where channels can be either RGB or RGBA.

    window : int
        The window size to be applied to `pianoroll` for the animation.
    hop : int
        The hop size to be applied to `pianoroll` for the animation.
    fps : int
        The number of frames per second in the resulting video or GIF file.
    is_drum : bool
        A boolean number that indicates whether it is a percussion track.
        Defaults to False.
    beat_resolution : int
        The number of time steps used to represent a beat. Required and only
        effective when `xtick` is 'beat'.
    downbeats : list
        An array that indicates whether the time step contains a downbeat (i.e.,
        the first time step of a bar).

    preset : {'default', 'plain', 'frame'}
        A string that indicates the preset theme to use.

        - In 'default' preset, the ticks, grid and labels are on.
        - In 'frame' preset, the ticks and grid are both off.
        - In 'plain' preset, the x- and y-axis are both off.

    cmap :  `matplotlib.colors.Colormap`
        The colormap to use in :func:`matplotlib.pyplot.imshow`. Defaults to
        'Blues'. Only effective when `pianoroll` is 2D.
    xtick : {'auto', 'beat', 'step', 'off'}
        A string that indicates what to use as ticks along the x-axis. If 'auto'
        is given, automatically set to 'beat' if `beat_resolution` is also given
        and set to 'step', otherwise. Defaults to 'auto'.
    ytick : {'octave', 'pitch', 'off'}
        A string that indicates what to use as ticks along the y-axis.
        Defaults to 'octave'.
    xticklabel : bool
        Whether to add tick labels along the x-axis. Only effective when `xtick`
        is not 'off'.
    yticklabel : {'auto', 'name', 'number', 'off'}
        If 'name', use octave name and pitch name (key name when `is_drum` is
        True) as tick labels along the y-axis. If 'number', use pitch number. If
        'auto', set to 'name' when `ytick` is 'octave' and 'number' when `ytick`
        is 'pitch'. Defaults to 'auto'. Only effective when `ytick` is not
        'off'.
    tick_loc : tuple or list
        The locations to put the ticks. Availables elements are 'bottom', 'top',
        'left' and 'right'. Defaults to ('bottom', 'left').
    tick_direction : {'in', 'out', 'inout'}
        A string that indicates where to put the ticks. Defaults to 'in'. Only
        effective when one of `xtick` and `ytick` is on.
    label : {'x', 'y', 'both', 'off'}
        A string that indicates whether to add labels to the x-axis and y-axis.
        Defaults to 'both'.
    grid : {'x', 'y', 'both', 'off'}
        A string that indicates whether to add grids to the x-axis, y-axis, both
        or neither. Defaults to 'both'.
    grid_linestyle : str
        Will be passed to :meth:`matplotlib.axes.Axes.grid` as 'linestyle'
        argument.
    grid_linewidth : float
        Will be passed to :meth:`matplotlib.axes.Axes.grid` as 'linewidth'
        argument.

    """
    if not HAS_MOVIEPY:
        raise ImportError(
            "moviepy package is required for animation supports.")

    def make_frame(t):
        """Return an image of the frame for time t."""
        fig = plt.gcf()
        ax = plt.gca()
        f_idx = int(t * fps)
        start = hop * f_idx
        end = start + window
        to_plot = transposed[:, start:end]
        extent = (start, end - 1, 0, 127)
        ax.imshow(
            to_plot,
            cmap=cmap,
            aspect="auto",
            vmin=vmin,
            vmax=vmax,
            origin="lower",
            interpolation="none",
            extent=extent,
        )

        if xtick == "beat":
            next_major_idx = beat_resolution - start % beat_resolution
            if start % beat_resolution < beat_resolution // 2:
                next_minor_idx = beat_resolution // 2 - start % beat_resolution
            else:
                next_minor_idx = (beat_resolution // 2 -
                                  start % beat_resolution + beat_resolution)
            xticks_major = np.arange(next_major_idx, window, beat_resolution)
            xticks_minor = np.arange(next_minor_idx, window, beat_resolution)
            if end % beat_resolution < beat_resolution // 2:
                last_minor_idx = beat_resolution // 2 - end % beat_resolution
            else:
                last_minor_idx = (beat_resolution // 2 -
                                  end % beat_resolution + beat_resolution)
            xtick_labels = np.arange(
                (start + next_minor_idx) // beat_resolution,
                (end + last_minor_idx) // beat_resolution,
            )
            ax.set_xticks(xticks_major)
            ax.set_xticklabels("")
            ax.set_xticks(xticks_minor, minor=True)
            ax.set_xticklabels(xtick_labels, minor=True)
            ax.tick_params(axis="x", which="minor", width=0)

        return mplfig_to_npimage(fig)

    if xtick == "auto":
        xtick = "beat" if beat_resolution is not None else "step"

    _, ax = plt.subplots()
    plot_pianoroll(
        ax,
        pianoroll[:window],
        is_drum,
        beat_resolution,
        downbeats,
        preset=preset,
        cmap=cmap,
        xtick=xtick,
        ytick=ytick,
        xticklabel=xticklabel,
        yticklabel=yticklabel,
        tick_loc=tick_loc,
        tick_direction=tick_direction,
        label=label,
        grid=grid,
        grid_linestyle=grid_linestyle,
        grid_linewidth=grid_linewidth,
    )

    num_frame = int((pianoroll.shape[0] - window) / hop)
    duration = int(num_frame / fps)

    if np.issubdtype(pianoroll.dtype, np.bool_) or np.issubdtype(
            pianoroll.dtype, np.floating):
        vmax = 1
    elif np.issubdtype(pianoroll.dtype, np.integer):
        vmax = 127
    else:
        raise TypeError("Unsupported data type for `pianoroll`.")
    vmin = 0

    transposed = pianoroll.T
    animation = VideoClip(make_frame, duration=duration)
    if filename.endswith(".gif"):
        animation.write_gif(filename, fps, **kwargs)
    else:
        animation.write_videofile(filename, fps, **kwargs)
    plt.close()
class _Scatter(object):
    """relative frame length is the length of each single frame measured as a fraction of
    the whole experiment duration. """
    def __init__(self,
                 visualizer=None,
                 dimension=3,
                 relative_frame_length=0.01,
                 rotate=False,
                 speedup_factor=1.0,
                 smoothness_factor=0.5,
                 export_format='mp4'):

        self.visualizer = visualizer
        self.dimension = dimension

        self.relative_frame_length = relative_frame_length  # should be within (0.0, 1.0]

        self.duration = self.visualizer.spikes[-1][0]  # in ms
        self.angle = -90
        self.rotate = rotate
        self.speedup = speedup_factor

        self.scatter_plot = None

        self.window_size = self.duration * relative_frame_length  # some quantity in ms
        self.window_step = self.window_size * smoothness_factor  # some quantity in ms
        self.window_start = 0
        self.window_end = self.window_start + self.window_size

        self.frame_count = int(
            (self.duration - self.window_size) / self.window_step) + 1
        self.fps = int(
            (self.frame_count / (self.duration / 1000)) * self.speedup)

        if self.fps == 0:
            self.fps = 1

        # initialise figure and axes and setup other details
        self.cbar_not_added = True
        self._setup_plot()

        self.file_format = export_format
        # print("duration", int((self.duration/1000+1)/speedup_factor))
        from moviepy.editor import VideoClip
        self.anim = VideoClip(self._update_frame,
                              duration=int(
                                  (self.duration / 1000 + 1) / speedup_factor))

    def _change_angle(self):
        self.angle = (self.angle + 0.5) % 360

    def _setup_plot(self):
        self.fig = plt.figure()
        if self.dimension == 3:
            self.ax = self.fig.add_subplot(111, projection='3d')
            self.ax.set_xlim3d(0, self.visualizer.network_dimensions['dim_x'])
            self.ax.set_xlabel('x')
            self.ax.set_ylim3d(self.visualizer.network_dimensions['max_d'],
                               self.visualizer.network_dimensions['min_d'])
            self.ax.set_ylabel('depth')
            self.ax.set_zlim3d(0, self.visualizer.network_dimensions['dim_y'])
            self.ax.set_zlabel('y')

        else:
            self.ax = self.fig.add_subplot(111)
            self.ax.set_xlim(0, self.visualizer.network_dimensions['dim_x'])
            self.ax.set_xlabel('x')
            self.ax.set_ylim(0, self.visualizer.network_dimensions['dim_y'])
            self.ax.set_ylabel('y')

        self.ax.set_title("Network's subjective sense of reality", fontsize=16)
        self.ax.set_autoscale_on(False)

    def _update_frame(self, time):
        from moviepy.video.io.bindings import mplfig_to_npimage
        if self.dimension == 3:
            if self.rotate:
                self._change_angle()
            self.ax.view_init(30, self.angle)

        # clear the plot from the old data
        if self.scatter_plot is not None:
            self.scatter_plot.remove()

        # reimplement in a more clever way so that movie generation is in total O(n) not O(nm)
        current_frame = []
        for s in self.visualizer.spikes:
            if s[0] > self.window_end:
                self.window_start += self.window_step
                self.window_end = self.window_start + self.window_size
                break
            if s[0] > self.window_start:
                current_frame.append((s[1], s[2], s[3]))
        current_frame = np.asarray(current_frame)

        if current_frame.size > 0:

            # be careful of the coordinate-axes orientation. up/down should be x!
            if self.dimension == 3:
                self.scatter_plot = self.ax.scatter(
                    current_frame[:, 0],
                    current_frame[:, 2],
                    current_frame[:, 1],
                    s=25,
                    marker='s',
                    lw=0,
                    c=current_frame[:, 2],
                    cmap=plt.cm.get_cmap(
                        "brg",
                        self.visualizer.network_dimensions['max_d'] + 1),
                    vmin=self.visualizer.network_dimensions['min_d'],
                    vmax=self.visualizer.network_dimensions['max_d'])
                if self.cbar_not_added:
                    cbar = self.fig.colorbar(self.scatter_plot)
                    cbar.set_label('Perceived disparity in pixel units',
                                   rotation=270)
                    cbar.ax.get_yaxis().labelpad = 15
                    self.cbar_not_added = False
            else:
                self.scatter_plot = self.ax.scatter(
                    current_frame[:, 0],
                    current_frame[:, 1],
                    s=25,
                    marker='s',
                    lw=0,
                    c=current_frame[:, 2],
                    cmap=plt.cm.get_cmap(
                        "brg",
                        self.visualizer.network_dimensions['max_d'] + 1),
                    vmin=self.visualizer.network_dimensions['min_d'],
                    vmax=self.visualizer.network_dimensions['max_d'])
                # find some better solution than this flag hack
                if self.cbar_not_added:
                    cbar = self.fig.colorbar(self.scatter_plot)
                    cbar.set_label('Perceived disparity in pixel units',
                                   rotation=270)
                    cbar.ax.get_yaxis().labelpad = 15
                    self.cbar_not_added = False
        else:
            self.scatter_plot = self.ax.scatter([], [])

        return mplfig_to_npimage(self.fig)

    def show(self):
        plt.show(
        )  # or better use plt.draw()?, not sure but I think this might freeze when updating...

    def save(self):
        dim = "3D" if self.dimension == 3 else "2D"

        if not os.path.exists("./animations"):
            os.makedirs("./animations")
        i = 0
        while os.path.exists("./animations/{0}_{2}_{1}.gif"
                                     .format(self.visualizer.experiment_name, i, dim)) or \
                os.path.exists("./animations/{0}_{2}_{1}.mp4"
                                       .format(self.visualizer.experiment_name, i, dim)):
            i += 1
        if self.file_format == 'gif':
            self.anim.write_gif(filename="./animations/{0}_{2}_{1}.gif".format(
                self.visualizer.experiment_name, i, dim),
                                fps=self.fps,
                                verbose=self.visualizer.verbose)
        elif self.file_format == 'mp4':
            print("INFO: Generating movie with duration of {0}s at {1}fps.".
                  format(int((self.duration / 1000 + 1) / self.speedup),
                         self.fps))
            self.anim.write_videofile(
                filename="./animations/{0}_{2}_{1}.mp4".format(
                    self.visualizer.experiment_name, i, dim),
                fps=self.fps,
                codec='mpeg4',
                bitrate='2000k',
                audio=False,
                verbose=self.visualizer.verbose)
        else:
            print("ERROR: The export format is not supported.")
Beispiel #20
0
import numpy as np
from moviepy.editor import VideoClip

def make_frame(t):
    """ returns an image of the frame at time t """
    # ... create the frame with any library
    return np.zeros((300, 400, 3)) # (Height x Width x 3) Numpy array

animation = VideoClip(make_frame, duration=3) # 3-second clip

# For the export, many options/formats/optimizations are supported
animation.write_videofile("my_animation.mp4", fps=24) # export as video
animation.write_gif("my_animation.gif", fps=24) # export as GIF (slow)
Beispiel #21
0
def save_animation(filepath,
                   pianoroll,
                   window,
                   hop=1,
                   fps=None,
                   is_drum=False,
                   beat_resolution=None,
                   downbeats=None,
                   normalization='standard',
                   preset='default',
                   cmap='Blues',
                   tick_loc=None,
                   xtick='auto',
                   ytick='octave',
                   xticklabel='on',
                   yticklabel='auto',
                   direction='in',
                   label='both',
                   grid='both',
                   grid_linestyle=':',
                   grid_linewidth=.5,
                   **kwargs):
    """
    Save a piano-roll to an animation in video or GIF format.

    Parameters
    ----------
    filepath : str
        Path to save the video file.
    pianoroll : np.ndarray
        The piano-roll to be plotted. The values should be in [0, 1] when
        `normalized` is False.

        - For 2D array, shape=(num_time_step, num_pitch).
        - For 3D array, shape=(num_time_step, num_pitch, num_channel), where
          channels can be either RGB or RGBA.

    window : int
        Window size to be applied to `pianoroll` for the animation.
    hop : int
        Hop size to be applied to `pianoroll` for the animation.
    fps : int
        Number of frames per second in the resulting video or GIF file.
    is_drum : bool
        Drum indicator. True for drums. False for other instruments. Default
        to False.
    beat_resolution : int
        Resolution of a beat (in time step). Required and only effective
        when `xticklabel` is 'beat'.
    downbeats : list
        Indices of time steps that contain downbeats., i.e. the first time
        step of a bar.
    normalization : {'standard', 'auto', 'none'}
        The normalization method to apply to the piano-roll. Default to
        'standard'. If `pianoroll` is binarized, use 'none' anyway.

        - For 'standard' normalization, the normalized values are given by
          N = P / 128, where P, N is the original and normalized piano-roll,
          respectively
        - For 'auto' normalization, the normalized values are given by
          N = (P - m) / (M - m), where P, N is the original and normalized
          piano-roll, respectively, and M, m is the maximum and minimum of the
          original piano-roll, respectively.
        - If 'none', no normalization will be applied to the piano-roll. In
          this case, the values of `pianoroll` should be in [0, 1] in order to
          plot it correctly.

    preset : {'default', 'plain', 'frame'}
        Preset themes for the plot.

        - In 'default' preset, the ticks, grid and labels are on.
        - In 'frame' preset, the ticks and grid are both off.
        - In 'plain' preset, the x- and y-axis are both off.

    cmap :  `matplotlib.colors.Colormap`
        Colormap to use in :func:`matplotlib.pyplot.imshow`. Default to
        'Blues'. Only effective when `pianoroll` is 2D.
    tick_loc : tuple or list
        List of locations to put ticks. Availables elements are 'bottom',
        'top', 'left' and 'right'. If None, default to ('bottom', 'left').
    xtick : {'auto', 'beat', 'step', 'off'}
        Use beat number or step number as ticks along the x-axis, or
        automatically set to 'beat' when `beat_resolution` is given and set
        to 'step', otherwise. Default to 'auto'.
    ytick : {'octave', 'pitch', 'off'}
        Use octave or pitch as ticks along the y-axis. Default to 'octave'.
    xticklabel : {'on', 'off'}
        Indicate whether to add tick labels along the x-axis. Only effective
        when `xtick` is not 'off'.
    yticklabel : {'auto', 'name', 'number', 'off'}
        If 'name', use octave name and pitch name (key name when `is_drum`
        is True) as tick labels along the y-axis. If 'number', use pitch
        number. If 'auto', set to 'name' when `ytick` is 'octave' and
        'number' when `ytick` is 'pitch'. Default to 'auto'. Only effective
        when `ytick` is not 'off'.
    direction : {'in', 'out', 'inout'}
        Put ticks inside the axes, outside the axes, or both. Default to
        'in'. Only effective when `xtick` and `ytick` are not both 'off'.
    label : {'x', 'y', 'both', 'off'}
        Add label to the x-axis, y-axis, both or neither. Default to 'both'.
    grid : {'x', 'y', 'both', 'off'}
        Add grid to the x-axis, y-axis, both or neither. Default to 'both'.
    grid_linestyle : str
        Will be passed to :meth:`matplotlib.axes.Axes.grid` as 'linestyle'
        argument.
    grid_linewidth : float
        Will be passed to :meth:`matplotlib.axes.Axes.grid` as 'linewidth'
        argument.

    """
    def make_frame(t):
        """Return an image of the frame for time t"""
        fig = plt.gcf()
        ax = plt.gca()
        f_idx = int(t * fps)
        start = hop * f_idx
        end = start + window
        to_plot = pianoroll[start:end].T / 128.
        extent = (start, end - 1, 0, 127)
        ax.imshow(to_plot,
                  cmap=cmap,
                  aspect='auto',
                  vmin=0,
                  vmax=1,
                  origin='lower',
                  interpolation='none',
                  extent=extent)

        if xtick == 'beat':
            next_major_idx = beat_resolution - start % beat_resolution
            if start % beat_resolution < beat_resolution // 2:
                next_minor_idx = beat_resolution // 2 - start % beat_resolution
            else:
                next_minor_idx = (beat_resolution // 2 -
                                  start % beat_resolution + beat_resolution)
            xticks_major = np.arange(next_major_idx, window, beat_resolution)
            xticks_minor = np.arange(next_minor_idx, window, beat_resolution)
            if end % beat_resolution < beat_resolution // 2:
                last_minor_idx = beat_resolution // 2 - end % beat_resolution
            else:
                last_minor_idx = (beat_resolution // 2 -
                                  end % beat_resolution + beat_resolution)
            xtick_labels = np.arange(
                (start + next_minor_idx) // beat_resolution,
                (end + last_minor_idx) // beat_resolution)
            ax.set_xticks(xticks_major)
            ax.set_xticklabels('')
            ax.set_xticks(xticks_minor, minor=True)
            ax.set_xticklabels(xtick_labels, minor=True)
            ax.tick_params(axis='x', which='minor', width=0)

        return mplfig_to_npimage(fig)

    if xtick == 'auto':
        xtick = 'beat' if beat_resolution is not None else 'step'

    fig, ax = plt.subplots()
    plot_pianoroll(ax,
                   pianoroll[:window],
                   is_drum=is_drum,
                   beat_resolution=beat_resolution,
                   downbeats=downbeats,
                   normalization=normalization,
                   preset=preset,
                   cmap=cmap,
                   tick_loc=tick_loc,
                   xtick=xtick,
                   ytick=ytick,
                   xticklabel=xticklabel,
                   yticklabel=yticklabel,
                   direction=direction,
                   label='both',
                   grid='both',
                   grid_linestyle=':',
                   grid_linewidth=.5)

    num_frame = int((pianoroll.shape[0] - window) / hop)
    duration = int(num_frame / fps)
    animation = VideoClip(make_frame, duration=duration)
    if filepath.endswith('.gif'):
        animation.write_gif(filepath, fps, kwargs)
    else:
        animation.write_videofile(filepath, fps, kwargs)
    plt.close()
Beispiel #22
0
clip = VideoFileClip(args.filename).resize(0.2)

print('%s is %i fps, for % seconds at %s' %
      (args.filename, clip.fps, clip.duration, clip.size))

img = np.zeros((clip.size[1], clip.size[0], 3), dtype='uint8')

currentX = 0
slitwidth = 1

slitpoint = clip.size[1] // 2

frame_generator = clip.iter_frames(fps=clip.fps, dtype='uint8')


def make_frame(t):
    global img, currentX
    next_frame = next(frame_generator)
    img = np.roll(img, -1, axis=0)
    img[slitpoint, :, :] = next_frame[slitpoint, :, :]
    next_frame[max(slitpoint - currentX, 0):slitpoint, :, :] = img[
        max(0, slitpoint - currentX):slitpoint, :, :]

    currentX += 1
    return next_frame


output = VideoClip(make_frame=make_frame, duration=10.5)
output.write_gif('output1.gif', fps=12)
Beispiel #23
0
x = np.linspace(0, 2 * np.pi, 100)

# vytvoření objektu reprezentujícího průběh funkce
# + nastavení rozlišení obrázku (resp. jednotlivých rámců)
fig, axis = plt.subplots(figsize=(1.0 * WIDTH / DPI, 1.0 * HEIGHT / DPI),
                         dpi=DPI)


def make_frame(t):
    """Deklarace callback funkce zavolane pri renderingu kazdeho snimku videa."""
    axis.clear()

    # offset v rozmezí 0 .. 2*Pi
    offset = 2 * np.pi * t / DURATION

    # hodnoty na y-ové ose
    y = np.sin(x + offset)

    # vykreslení průběhu funkce
    axis.plot(x, y)

    # konverze na objekt typu "frame"
    return mplfig_to_npimage(fig)


# vytvoreni video klipu
animation = VideoClip(make_frame, duration=DURATION)

# export videa do formatu GIF
animation.write_gif('sinus_B.gif', fps=FPS)
Beispiel #24
0
            hue_left = hue[rs, cs-1]
            hue_up = hue[rs-1, cs]
            this_hue = chunk[0, 0]
            new_hue = (-random.randrange(30, 50) * (hue_up / 360)
                       -10*random.randrange(1, 10) * (hue_left / 360))
            new_hue = (15*this_hue + 2*new_hue) / 17
            chunk[:] = new_hue
        np.mod(hue, 360, out=hue)
        yield nphusl.to_rgb(hsl)


if __name__ == "__main__":
    filename = sys.argv[1]
    img = imread.imread(filename)
    transforms = reveal_blue, reveal_blue_rgb, hue_watermelon,\
                 reveal_light, reveal_light_rgb, highlight_saturation
    for t in transforms:
        out, name = t(img)
        imread.imwrite(name + ".jpg", out.astype(np.uint8))

    n_frames = 300
    fps = 50
    duration = n_frames / fps
    #frames = microwave(img)
    #animation = VideoClip(lambda _: next(frames), duration=duration)
    #animation.write_gif("video2.gif", fps=fps, opt="OptimizePlus")
    frames = melonize(img, n_frames)
    animation = VideoClip(lambda _: next(frames), duration=duration)
    animation.write_gif("melonized.gif", fps=fps, opt="OptimizePlus")

    global line
    print("time: {time}, line: {lime}".format(time=t, line=line))

    # vyplneni trojrozmerneho pole nulami
    frame = numpy.zeros((HEIGHT, WIDTH, 3))

    # vykresleni jedine vodorovne usecky
    if line < HEIGHT:
        frame[line].fill(255)
        line += 1
    return frame


# vytvoreni video klipu
animation = VideoClip(make_frame, duration=10)

# export videa do formatu MPEG-4
animation.write_videofile("line.mp4", fps=24)

# znovunastaveni pocitadla
line = 0

# export videa do formatu Ogg Video File
animation.write_videofile("line.ogv", fps=24)

# znovunastaveni pocitadla
line = 0

# export videa do formatu GIF
animation.write_gif("line.gif", fps=24)

def make_frame(t):
    filename = f'diff{make_frame.counter:06d}.dat'

    A = np.loadtxt(filename)
    x, y, T = A[:, 0].reshape((21, 21)), A[:, 1].reshape(
        (21, 21)), A[:, 2].reshape((21, 21))

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.plot_wireframe(x, y, T)
    ax.set_zlim(0, 1)

    img = mplfig_to_npimage(fig)
    plt.close(fig)

    make_frame.counter += 1
    return img


make_frame.counter = 1

if __name__ == '__main__':
    fps = 20
    N = 200
    duration = (N - 1) / fps

    animation = VideoClip(make_frame, duration=duration)
    animation.write_gif('gif.gif', fps=fps)
Beispiel #27
0
def cli(ctx, opt_dir_in, opt_fp_out, opt_fps, opt_ext, opt_slice, opt_decimate,
        opt_width, opt_force, opt_interp):
    """Converts still image to GIF"""

    from glob import glob
    from pathlib import Path

    from PIL import Image
    import numpy as np
    from tqdm import tqdm
    from moviepy.editor import VideoClip

    from app.utils import file_utils, im_utils

    log = app_cfg.LOG
    log.info('Generating animated GIF')

    if not opt_fp_out:
        opt_fp_out = str(
            Path(opt_dir_in).parent / f'{Path(opt_dir_in).name}.gif')
        if Path(opt_fp_out).is_dir() and not opt_force:
            log.error(f'{opt_fp_out} exists. Use "-f/--force" to overwrite')

    # glob comp images
    fps_im = sorted(
        [im for im in glob(str(Path(opt_dir_in) / f'*.{opt_ext}'))])
    if opt_slice:
        fps_im = fps_im[opt_slice[0]:opt_slice[1]]
    if opt_decimate:
        fps_im = [x for i, x in enumerate(fps_im) if i % opt_decimate]

    if len(fps_im) > 100:
        log.warn(
            'Creating GIF with over 100 frames. Could create memory issues')

    # load all images into list
    ims = []
    for fp_im in tqdm(fps_im):
        log.debug(fp_im)
        im = Image.open(fp_im)
        log.debug(im.size)
        w, h = im.size
        h = int(opt_width * h / w)
        im = im.resize((opt_width, h), Image.NEAREST)
        ims.append(im)

    num_frames = len(fps_im)
    duration_sec = num_frames / opt_fps

    def make_frame(t):
        frame_idx = int(np.clip(np.round(t * opt_fps), 0, num_frames - 1))
        im = ims[frame_idx]
        im_np_rgb = im_utils.pil2np(im, swap=False)
        return im_np_rgb

    animation = VideoClip(make_frame, duration=duration_sec)
    animation.write_gif(opt_fp_out, fps=opt_fps)  # export as GIF (slow)

    # ims[0].save(opt_fp_out,
    #            save_all=True,
    #            append_images=ims[1:],
    #            duration=int((1.0/opt_fps)*1000),
    #            loop=0)

    log.info('Done.')
Beispiel #28
0
        # set working directory
        dataset = 'chirp'
        try:
            os.chdir(args.evalpath + '/' + dataset)
        except FileNotFoundError:
            os.makedirs(args.evalpath + '/' + dataset, exist_ok=True)
            os.chdir(args.evalpath + '/' + dataset)

        # save tikz and pdf
        import tikzplotlib

        tikzplotlib.save(dataset + '_' + str(n) + '.tex')
        plt.savefig(dataset + '_' + str(n) + '.pdf')

    from moviepy.editor import VideoClip
    from moviepy.video.io.bindings import mplfig_to_npimage

    fps = 10

    def make_frame(t):
        idx = int(t * fps)
        return mplfig_to_npimage(anim[idx])

    # set working directory
    os.chdir(args.evalpath)
    dataset = 'chirp'
    path = os.path.join(str(dataset) + '/')

    animation = VideoClip(make_frame, duration=2.5)
    animation.write_gif(path + dataset + '.gif', fps=fps)
# zde začínáme od nuly!
# viz: https://github.com/Zulko/moviepy/issues/155
order = 0


def make_frame(t):
    """Deklarace callback funkce zavolane pri renderingu kazdeho snimku videa."""
    axis.clear()

    # Fourierova syntéza
    global order
    approx = ys(x, order)

    axis.plot(x, approx, label='order {o}'.format(o=order))
    order += 1

    # limity na ose y
    axis.set_ylim([-1, 1])
    axis.legend()

    # konverze na objekt typu "frame"
    return mplfig_to_npimage(fig)


# vytvoreni video klipu
animation = VideoClip(make_frame, duration=DURATION)

# export videa do formatu GIF
animation.write_gif('fourier_square_wave.gif', fps=FPS)
Beispiel #30
0
fig = plt.figure(figsize=(1.0 * WIDTH / DPI, 1.0 * HEIGHT / DPI), dpi=DPI)
axis = fig.add_subplot(111, projection="polar")


def make_frame(t):
    """Deklarace callback funkce zavolane pri renderingu kazdeho snimku videa."""
    axis.clear()

    # offset v rozmezí 0 .. 2*Pi
    offset = 2 * np.pi * t / DURATION

    # úhel v polárním grafu
    theta = np.linspace(0.01 + offset, 2 * np.pi + offset, 150)

    # vzdálenost od středu
    radius = np.log(theta)

    # vykreslení průběhu funkce
    # v polárním grafu
    axis.plot(theta, radius)

    # konverze na objekt typu "frame"
    return mplfig_to_npimage(fig)


# vytvoreni video klipu
animation = VideoClip(make_frame, duration=DURATION)

# export videa do formatu GIF
animation.write_gif('polar.gif', fps=FPS)
        y_usa[i * 4 + 3] = y_usa[i * 4 + 2] + beta
    except:
        'h'
y_china = y_china[::-1]
y_usa = y_usa[::-1]


def make_frame(t):
    ax.clear()
    y_c = np.array([np.nan] * 229)
    y_u = np.array([np.nan] * 229)
    t = int(np.floor(t / 0.05))
    y_c[:t] = y_china[:t]
    y_u[:t] = y_usa[:t]
    ax.plot(x, y_c, lw=3)
    ax.set_xlabel('year')
    ax.set_ylabel('$')
    ax.set_title('GDP')
    ax.text(1970, 23, 'USA: ' + str(np.round(y_u[t - 1:t], 2)) + 'trillion')
    ax.text(1970, 20, 'China: ' + str(np.round(y_c[t - 1:t], 2)) + 'trillion')
    ax.plot(x, y_u, lw=3)
    ax.legend(['China', 'USA'])
    ax.set_xlim(1959, 2018)
    ax.set_ylim(0, np.ceil(max(y_usa + y_china) + 1))
    ax.set_xticks(list(range(1960, 2018, 10)))
    return mplfig_to_npimage(fig)


animation = VideoClip(make_frame, duration=11)
animation.write_gif('matplotlib.gif', fps=20)
Beispiel #32
0
fig.subplots_adjust(left=0, right=1, bottom=0)
xx, yy = np.meshgrid(np.linspace(-2, 3, 500), np.linspace(-1, 2, 500))


def make_frame(t):
    ax.clear()
    ax.axis('off')
    ax.set_title("SVC classification", fontsize=16)

    classifier = svm.SVC(gamma=2, C=1)
    # the varying weights make the points appear one after the other
    weights = np.minimum(1, np.maximum(0, t**2 + 10 - np.arange(50)))
    classifier.fit(X, Y, sample_weight=weights)
    Z = classifier.decision_function(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    ax.contourf(xx,
                yy,
                Z,
                cmap=plt.cm.bone,
                alpha=0.8,
                vmin=-2.5,
                vmax=2.5,
                levels=np.linspace(-2, 2, 20))
    ax.scatter(X[:, 0], X[:, 1], c=Y, s=50 * weights, cmap=plt.cm.bone)

    return mplfig_to_npimage(fig)


animation = VideoClip(make_frame, duration=7)
animation.write_gif("svm.gif", fps=15)
Beispiel #33
0
view.set_camera('turntable',
                mode='perspective',
                up='z',
                distance=2,
                azimuth=30.,
                elevation=65.)

xx, yy = np.arange(-1, 1, .02), np.arange(-1, 1, .02)
X, Y = np.meshgrid(xx, yy)
R = np.sqrt(X**2 + Y**2)
Z = lambda t: 0.1 * np.sin(10 * R - 2 * np.pi * t)
surface = scene.visuals.SurfacePlot(x=xx - 0.1,
                                    y=yy + 0.2,
                                    z=Z(0),
                                    shading='smooth',
                                    color=(0.5, 0.5, 1, 1))
view.add(surface)
canvas.show()

# ANIMATE WITH MOVIEPY


def make_frame(t):
    surface.set_data(z=Z(t))  # Update the mathematical surface
    canvas.on_draw(None)  # Update the image on Vispy's canvas
    return _screenshot((0, 0, canvas.size[0], canvas.size[1]))[:, :, :3]


animation = VideoClip(make_frame, duration=1).resize(width=350)
animation.write_gif('sinc_vispy.gif', fps=20, opt='OptimizePlus')
Beispiel #34
0
from sklearn.datasets import make_moons
from moviepy.editor import VideoClip
from moviepy.video.io.bindings import mplfig_to_npimage

X, Y = make_moons(50, noise=0.1, random_state=2) # semi-random data

fig, ax = plt.subplots(1, figsize=(4, 4), facecolor=(1,1,1))
fig.subplots_adjust(left=0, right=1, bottom=0)
xx, yy = np.meshgrid(np.linspace(-2,3,500), np.linspace(-1,2,500))

def make_frame(t):
    ax.clear()
    ax.axis('off')
    ax.set_title("SVC classification", fontsize=16)

    classifier = svm.SVC(gamma=2, C=1)
    # the varying weights make the points appear one after the other
    weights = np.minimum(1, np.maximum(0, t**2+10-np.arange(50)))
    classifier.fit(X, Y, sample_weight=weights)
    Z = classifier.decision_function(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    ax.contourf(xx, yy, Z, cmap=plt.cm.bone, alpha=0.8,
                vmin=-2.5, vmax=2.5, levels=np.linspace(-2,2,20))
    ax.scatter(X[:,0], X[:,1], c=Y, s=50*weights, cmap=plt.cm.bone)

    return mplfig_to_npimage(fig)

animation = VideoClip(make_frame, duration = 7)
animation.write_gif("svm.gif", fps=15)