Python imageio.get_writer() Examples

The following are 30 code examples of imageio.get_writer(). 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 imageio , or try the search function .
Example #1
Source File: visualizer.py    From lighttrack with MIT License 8 votes vote down vote up
def make_gif_from_images(img_paths, outgif_path):
    import imageio
    resize_ratio = 4
    skip_ratio = 2

    with imageio.get_writer(outgif_path, mode='I') as writer:
        for img_id, img_path in enumerate(img_paths):
            image = imageio.imread(img_path)
            image_resize = image[::resize_ratio, ::resize_ratio, :]
            # Do sth to make gif file smaller
            # 1) change resolution
            # 2) change framerate
            if img_id % skip_ratio == 0:
                writer.append_data(image_resize)
    print("Gif made!")
    return 
Example #2
Source File: visualization.py    From 2D-Motion-Retargeting with MIT License 6 votes vote down vote up
def motion2video(motion, h, w, save_path, colors, transparency=False, motion_tgt=None, fps=25, save_frame=False):
    nr_joints = motion.shape[0]
    videowriter = imageio.get_writer(save_path, fps=fps)
    vlen = motion.shape[-1]
    if save_frame:
        frames_dir = save_path[:-4] + '-frames'
        ensure_dir(frames_dir)
    for i in tqdm(range(vlen)):
        [img, img_cropped] = joints2image(motion[:, :, i], colors, transparency, H=h, W=w, nr_joints=nr_joints)
        if motion_tgt is not None:
            [img_tgt, img_tgt_cropped] = joints2image(motion_tgt[:, :, i], colors, transparency, H=h, W=w, nr_joints=nr_joints)
            img_ori = img.copy()
            img = cv2.addWeighted(img_tgt, 0.3, img_ori, 0.7, 0)
            img_cropped = cv2.addWeighted(img_tgt, 0.3, img_ori, 0.7, 0)
            bb = bounding_box(img_cropped)
            img_cropped = img_cropped[:, bb[2]:bb[3], :]
        if save_frame:
            save_image(img_cropped, os.path.join(frames_dir, "%04d.png" % i))
        videowriter.append_data(img)
    videowriter.close() 
Example #3
Source File: plotting.py    From pyvista with MIT License 6 votes vote down vote up
def open_movie(self, filename, framerate=24):
        """Establish a connection to the ffmpeg writer.

        Parameters
        ----------
        filename : str
            Filename of the movie to open.  Filename should end in mp4,
            but other filetypes may be supported.  See "imagio.get_writer"

        framerate : int, optional
            Frames per second.

        """
        if isinstance(pyvista.FIGURE_PATH, str) and not os.path.isabs(filename):
            filename = os.path.join(pyvista.FIGURE_PATH, filename)
        self.mwriter = imageio.get_writer(filename, fps=framerate) 
Example #4
Source File: plot_tool.py    From cbc-casper with GNU Affero General Public License v3.0 6 votes vote down vote up
def make_gif(self, frame_count_limit=IMAGE_LIMIT, gif_name="mygif.gif", frame_duration=0.4):
        """Make a GIF visualization of view graph."""
        if not self.save:
            return

        self.make_thumbnails(frame_count_limit=frame_count_limit)

        file_names = sorted([file_name for file_name in os.listdir(self.thumbnail_path)
                             if file_name.endswith('thumbnail.png')])

        images = []
        for file_name in file_names:
            images.append(Image.open(self.thumbnail_path + file_name))

        destination_filename = self.graph_path + gif_name

        iterator = 0
        with io.get_writer(destination_filename, mode='I', duration=frame_duration) as writer:
            for file_name in file_names:
                image = io.imread(self.thumbnail_path + file_name)
                writer.append_data(image)
                iterator += 1

        writer.close() 
Example #5
Source File: __init__.py    From ATX with Apache License 2.0 6 votes vote down vote up
def __init__(self, d, save_dir='report'):
        image_dir = os.path.join(save_dir, 'images')
        if not os.path.exists(image_dir):
            os.makedirs(image_dir)

        self.d = d
        self.save_dir = save_dir
        self.steps = []
        self.result = None

        self.__gif_path = os.path.join(save_dir, 'output.gif')
        self.__gif = imageio.get_writer(self.__gif_path, format='GIF', fps=2)
        self.__uia_last_position = None
        self.__last_screenshot = None
        self.__closed = False
        
        self.start_record() 
Example #6
Source File: visualizer.py    From cvToolkit with MIT License 6 votes vote down vote up
def make_gif_from_images(img_paths, outgif_path):
    import imageio
    resize_ratio = 4
    skip_ratio = 2

    with imageio.get_writer(outgif_path, mode='I') as writer:
        for img_id, img_path in enumerate(img_paths):
            image = imageio.imread(img_path)
            image_resize = image[::resize_ratio, ::resize_ratio, :]
            # Do sth to make gif file smaller
            # 1) change resolution
            # 2) change framerate
            if img_id % skip_ratio == 0:
                writer.append_data(image_resize)
    print("Gif made!")
    return 
Example #7
Source File: cmd_util.py    From MOREL with MIT License 6 votes vote down vote up
def _start_new_episode(self):
        if self.writer:
            self.writer.close()

        if self.attention_writer:
            self.attention_writer.close()

        if self.episode_id % self.episode_save_rate == 0:
            self.writer = imageio.get_writer(
                os.path.join(self.video_dir, 'video_episode_{}.mp4'.format(self.episode_id)),
                fps=15,
            )
            if self.write_attention_video:
                self.attention_writer = imageio.get_writer(
                    os.path.join(self.video_dir, 'video_episode_{}_attention.mp4'.format(self.episode_id)),
                    fps=15,
                )
        else:
            self.writer = None
            self.attention_writer = None

        self.episode_id += 1 
Example #8
Source File: visualizer.py    From ethshardingpoc with MIT License 6 votes vote down vote up
def make_gif(self, frame_count_limit=IMAGE_LIMIT, gif_name="mygif.gif", frame_duration=0.4):
        """Make a GIF visualization of view graph."""

        self.make_thumbnails(frame_count_limit=frame_count_limit)

        file_names = sorted([file_name for file_name in os.listdir(self.thumbnail_path)
                             if file_name.endswith('thumbnail.png')])

        images = []
        for file_name in file_names:
            images.append(Image.open(self.thumbnail_path + file_name))

        destination_filename = self.graph_path + gif_name

        iterator = 0
        with io.get_writer(destination_filename, mode='I', duration=frame_duration) as writer:
            for file_name in file_names:
                image = io.imread(self.thumbnail_path + file_name)
                writer.append_data(image)
                iterator += 1

        writer.close() 
Example #9
Source File: util.py    From neural-flow-style with MIT License 6 votes vote down vote up
def save_video(imgdir, filename, ext='png', fps=24, delete_imgdir=False):
    filename = os.path.join(imgdir, '..', filename+'.mp4')
    try:
        writer = imageio.get_writer(filename, fps=fps)
    except Exception:
        imageio.plugins.ffmpeg.download()
        writer = imageio.get_writer(filename, fps=fps)

    imgs = glob("{}/*.{}".format(imgdir, ext))
    imgs = sorted(imgs, key=lambda x: int(os.path.basename(x).split('.')[0]))

    # print(imgs)
    for img in imgs:
        im = imageio.imread(img)
        writer.append_data(im)
    
    writer.close()
    
    if delete_imgdir: shutil.rmtree(imgdir) 
Example #10
Source File: visualizer.py    From video-to-pose3D with MIT License 6 votes vote down vote up
def make_gif_from_images(img_paths, outgif_path):
    import imageio
    resize_ratio = 4
    skip_ratio = 2

    with imageio.get_writer(outgif_path, mode='I') as writer:
        for img_id, img_path in enumerate(img_paths):
            image = imageio.imread(img_path)
            image_resize = image[::resize_ratio, ::resize_ratio, :]
            # Do sth to make gif file smaller
            # 1) change resolution
            # 2) change framerate
            if img_id % skip_ratio == 0:
                writer.append_data(image_resize)
    print("Gif made!")
    return 
Example #11
Source File: file2hdf5.py    From visual_foresight with MIT License 6 votes vote down vote up
def serialize_video(imgs, temp_name_append):
    mp4_name = './temp{}.mp4'.format(temp_name_append)
    try:
        assert imgs.dtype == np.uint8, "Must be uint8 array!"
        assert not os.path.exists(mp4_name), "file {} exists!".format(mp4_name)
        # this is a hack to ensure imageio succesfully saves as a mp4 (instead of getting encoding confused)
        writer = imageio.get_writer(mp4_name)
        [writer.append_data(i[:, :, ::-1]) for i in imgs]
        writer.close()

        f = open(mp4_name, 'rb')
        buf = f.read()
        f.close()
    finally:
        if os.path.exists(mp4_name):
            os.remove(mp4_name)

    return np.frombuffer(buf, dtype=np.uint8) 
Example #12
Source File: file_2_hdf5.py    From visual_foresight with MIT License 6 votes vote down vote up
def serialize_video(imgs, temp_name_append):
    mp4_name = './temp{}.mp4'.format(temp_name_append)
    try:
        assert imgs.dtype == np.uint8, "Must be uint8 array!"
        assert not os.path.exists(mp4_name), "file {} exists!".format(mp4_name)
        # this is a hack to ensure imageio succesfully saves as a mp4 (instead of getting encoding confused)
        writer = imageio.get_writer(mp4_name)
        [writer.append_data(i[:, :, ::-1]) for i in imgs]
        writer.close()

        f = open(mp4_name, 'rb')
        buf = f.read()
        f.close()
    finally:
        if os.path.exists(mp4_name):
            os.remove(mp4_name)

    return np.frombuffer(buf, dtype=np.uint8) 
Example #13
Source File: video_env.py    From surreal with MIT License 6 votes vote down vote up
def save_video(frame_queue, filename, fps):
    '''
    Target function for video process. Opens up file with path and uses library imageio
    Args:
        frame_queue: a queue of frames to be store. If the frame is None, the capture is over
        filename: filename to which the capture is to be stored
        fps: framerate.
    Note that Queue.get() is a blocking function and thus will hang until new frames are
    added to frame_queue
    '''
    writer = imageio.get_writer(filename, fps=fps)
    while True:
        frame = frame_queue.get()
        if frame is None:
            break
        writer.append_data(frame)
    writer.close() 
Example #14
Source File: viz.py    From postman_problems with MIT License 6 votes vote down vote up
def make_circuit_video(infile_dir_images, outfile_movie, fps=3, format='png'):
    """
    Create a movie that visualizes the CPP solution from a series of static images.
    Args:
        infile_dir_images (str): path to list of images named like `img[X].png`.  These are produced from make_circuit_images
        outfile_movie (str): filename of created movie/gif (output)
        fps (int): frames per second for movie
        format (str): image format (png, jpeg, etc) used to generate images in named like img[X].[format].

    Returns:
        No return value.  Writes a movie/gif to disk
    """
    # sorting filenames in order
    filenames = glob.glob(os.path.join(infile_dir_images, 'img*.%s' % format))
    filenames_sort_indices = np.argsort([int(os.path.basename(filename).split('.')[0][3:]) for filename in filenames])
    filenames = [filenames[i] for i in filenames_sort_indices]

    # make movie
    with imageio.get_writer(outfile_movie, mode='I', fps=fps) as writer:
        for filename in tqdm.tqdm(filenames):
            image = imageio.imread(filename)
            writer.append_data(image)
    return 'Movie written to {}'.format(outfile_movie) 
Example #15
Source File: annotatedvideowriter.py    From deepvisualminer with MIT License 5 votes vote down vote up
def execute(self, input_data, input_directory, output_directory):
        if not input_data['isvideo']:
            return {}
            
        # Open output video stream if this is first frame.
        if input_data['frame'] == 0:
            # The output directory structure should match input directory structure.
            relpath_of_input_file = os.path.relpath(input_data['file'], input_directory)
            relparent_of_input_file = os.path.dirname(relpath_of_input_file)
            inp_filename,inp_extension = os.path.splitext(os.path.basename(relpath_of_input_file))
            
            output_filedir = os.path.join(output_directory, relparent_of_input_file)
            if not os.path.exists(output_filedir):
                os.makedirs(output_filedir)
                
            self.output_filepath =  os.path.join(output_filedir,
                inp_filename + '-annotated.' + self.cfg['params']['format'])

            self.output_video = imageio.get_writer(self.output_filepath, 'ffmpeg')
            
            
            
        img = input_data['img'].copy()
        
        for comp in self.cfg['inputs']:
            comp_outputs = input_data.get(comp)
            comp_reports = comp_outputs['reports']
            if not comp_reports:
                print("Warning: pipeline file specifies {} as input for {} but {} is not outputting any location reports".format(
                    comp, self.name, comp
                ))
                continue
            
            annotate(img, comp_reports)
        
            
        final_img = cv2.resize(img, (self.cfg['params']['size']['width'], self.cfg['params']['size']['height']))
            
        self.output_video.append_data(final_img)
        
        return {'file': self.output_filepath} 
Example #16
Source File: wrappers.py    From atari-reset with MIT License 5 votes vote down vote up
def reset(self):
        if self.video_writer is not None:
            self.video_writer.close()
            self.counter += 1
        self.video_writer = imageio.get_writer(self.file_prefix + str(self.counter) + '.mp4', mode='I', fps=120)
        return self.env.reset() 
Example #17
Source File: ffmpeg.py    From faceswap with GNU General Public License v3.0 5 votes vote down vote up
def get_writer(self):
        """ Add the requested encoding options and return the writer """
        logger.debug("writer config: %s", self.config)
        return imageio.get_writer(self.video_tmp_file,
                                  fps=self.video_fps,
                                  ffmpeg_log_level="error",
                                  quality=None,
                                  macro_block_size=8,
                                  output_params=self.output_params) 
Example #18
Source File: ffmpeg.py    From faceswap with GNU General Public License v3.0 5 votes vote down vote up
def write(self, filename, image):
        """ Frames come from the pool in arbitrary order, so cache frames
            for writing out in correct order """
        logger.trace("Received frame: (filename: '%s', shape: %s", filename, image.shape)
        if not self.output_dimensions:
            logger.info("Outputting to: '%s'", self.video_file)
            self.set_dimensions(image.shape[:2])
            self.writer = self.get_writer()
        self.cache_frame(filename, image)
        self.save_from_cache() 
Example #19
Source File: utils.py    From habitat-api with MIT License 5 votes vote down vote up
def images_to_video(
    images: List[np.ndarray],
    output_dir: str,
    video_name: str,
    fps: int = 10,
    quality: Optional[float] = 5,
    **kwargs,
):
    r"""Calls imageio to run FFMPEG on a list of images. For more info on
    parameters, see https://imageio.readthedocs.io/en/stable/format_ffmpeg.html
    Args:
        images: The list of images. Images should be HxWx3 in RGB order.
        output_dir: The folder to put the video in.
        video_name: The name for the video.
        fps: Frames per second for the video. Not all values work with FFMPEG,
            use at your own risk.
        quality: Default is 5. Uses variable bit rate. Highest quality is 10,
            lowest is 0.  Set to None to prevent variable bitrate flags to
            FFMPEG so you can manually specify them using output_params
            instead. Specifying a fixed bitrate using ‘bitrate’ disables
            this parameter.
    """
    assert 0 <= quality <= 10
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    video_name = video_name.replace(" ", "_").replace("\n", "_") + ".mp4"
    writer = imageio.get_writer(
        os.path.join(output_dir, video_name),
        fps=fps,
        quality=quality,
        **kwargs,
    )
    logger.info(f"Video created: {os.path.join(output_dir, video_name)}")
    for im in tqdm.tqdm(images):
        writer.append_data(im)
    writer.close() 
Example #20
Source File: gif.py    From faceswap with GNU General Public License v3.0 5 votes vote down vote up
def get_writer(self):
        """ Add the requested encoding options and return the writer """
        logger.debug("writer config: %s", self.config)
        return imageio.get_writer(self.gif_file,
                                  mode="i",
                                  **self.config) 
Example #21
Source File: gif.py    From faceswap with GNU General Public License v3.0 5 votes vote down vote up
def write(self, filename, image):
        """ Frames come from the pool in arbitrary order, so cache frames
            for writing out in correct order """
        logger.trace("Received frame: (filename: '%s', shape: %s", filename, image.shape)
        if not self.gif_file:
            self.set_gif_filename(filename)
            self.set_dimensions(image.shape[:2])
            self.writer = self.get_writer()
        if (image.shape[1], image.shape[0]) != self.output_dimensions:
            image = cv2.resize(image, self.output_dimensions)  # pylint: disable=no-member
        self.cache_frame(filename, image)
        self.save_from_cache() 
Example #22
Source File: utils.py    From SMIT with MIT License 5 votes vote down vote up
def make_gif(imgs, path, im_size=256, total_styles=5):
    import imageio
    import numpy as np
    if 'jpg' in path:
        path = path.replace('jpg', 'gif')
    imgs = (imgs.cpu().numpy().transpose(0, 2, 3, 1) * 255).astype(np.uint8)
    target_size = (im_size, im_size, imgs.shape[-1])
    img_list = []
    for x in range(imgs.shape[2] // im_size):
        for bs in range(imgs.shape[0]):
            if x == 0 and bs > 1:
                continue  # Only save one image of the originals
            if x == 1:
                continue  # Do not save any of the 'off' label
            img_short = imgs[bs, :, im_size * x:im_size * (x + 1)]
            assert img_short.shape == target_size
            img_list.append(img_short)
    imageio.mimsave(path, img_list, duration=0.8)

    writer = imageio.get_writer(path.replace('gif', 'mp4'), fps=3)
    for im in img_list:
        writer.append_data(im)
    writer.close()


# ==================================================================#
# ==================================================================# 
Example #23
Source File: poly_visualizer.py    From cvToolkit with MIT License 5 votes vote down vote up
def make_gif_from_images(img_paths, outgif_path):
    import imageio
    with imageio.get_writer(outgif_path, mode='I') as writer:
        for img_path in img_paths:
            image = imageio.imread(img_path)
            # Do sth to make gif file smaller
            # 1) change resolution
            # 2) change framerate
            writer.append_data(image)
    print("Gif made!")
    return 
Example #24
Source File: image.py    From catalyst with Apache License 2.0 5 votes vote down vote up
def mimwrite_with_meta(uri, ims, meta, **kwargs):
    """@TODO: Docs. Contribution is welcome."""
    writer = imageio.get_writer(uri, mode="I", **kwargs)
    writer.set_meta_data(meta)
    with writer:
        for i in ims:
            writer.append_data(i) 
Example #25
Source File: videos.py    From pix2pix-flow with MIT License 5 votes vote down vote up
def write(imgs, name, fps):
    writer = get_writer(name, fps=fps, quality=6)
    for t in range(len(imgs)):
        writer.append_data(imgs[t])
    writer.close() 
Example #26
Source File: poly_visualizer.py    From video-to-pose3D with MIT License 5 votes vote down vote up
def make_gif_from_images(img_paths, outgif_path):
    import imageio
    with imageio.get_writer(outgif_path, mode='I') as writer:
        for img_path in img_paths:
            image = imageio.imread(img_path)
            # Do sth to make gif file smaller
            # 1) change resolution
            # 2) change framerate
            writer.append_data(image)
    print("Gif made!")
    return 
Example #27
Source File: tools.py    From glue-vispy-viewers with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def activate(self):

        # pop up a window for file saving
        outfile, file_filter = compat.getsavefilename(caption='Save Animation',
                                                      filters='GIF Files (*.gif);;')

        # if outfile is not set, the user cancelled
        if outfile:
            import imageio
            self.set_icon(RECORD_STOP_ICON)
            self.writer = imageio.get_writer(outfile)
            self.record_timer.start(0.1) 
Example #28
Source File: wrappers.py    From RLs with Apache License 2.0 5 votes vote down vote up
def render(self, mode, **kwargs):
        filename = kwargs.get('filename', None)
        fps = kwargs.get('fps', 30)
        if filename is not None:
            if not hasattr(self, 'video_writer'):
                self.video_writer = imageio.get_writer(filename, fps=fps)
            self.video_writer.append_data(self.env.render(mode='rgb_array'))
        else:
            self.env.render(mode='human') 
Example #29
Source File: videos.py    From glow with MIT License 5 votes vote down vote up
def write(imgs, name, fps):
    writer = get_writer(name, fps=fps, quality=6)
    for t in range(len(imgs)):
        writer.append_data(imgs[t])
    writer.close() 
Example #30
Source File: file_saver.py    From visual_foresight with MIT License 5 votes vote down vote up
def _file_worker(file_queue):
    logging.debug('started file saver with PID:', os.getpid())
    data = file_queue.get(True)
    prepend_path = './'
    while data is not None:
        dat_type = data[0]
        if dat_type == 'path':
            prepend_path = data[1]
            if not os.path.exists(prepend_path):
                os.makedirs(prepend_path)
        elif dat_type == 'txt_file':
            save_path = '{}/{}'.format(prepend_path, data[1])
            _make_parent_if_needed(save_path)
            with open(save_path, 'w') as f:
                f.write(data[2])
                f.write('\n')
        elif dat_type == 'mov':
            save_path = '{}/{}'.format(prepend_path, data[1])
            _make_parent_if_needed(save_path)
            fps, frames = 4, data[2]
            if len(data) == 4:
                fps = data[3]
            writer = io.get_writer(save_path, fps=fps)
            [writer.append_data(f.astype(np.uint8)) for f in frames]
            writer.close()
        elif dat_type == 'img':
            save_path = '{}/{}'.format(prepend_path, data[1])
            _make_parent_if_needed(save_path)
            cv2.imwrite(save_path, data[2][:, :, ::-1])

        data = file_queue.get(True)
    return