Python imageio.mimwrite() Examples

The following are 22 code examples of imageio.mimwrite(). 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: imagemaker.py    From Trusty-cogs with MIT License 7 votes vote down vote up
def make_banner(self, text: str, colour: str) -> BytesIO:
        im = Image.new("RGBA", (300, 100), (0, 0, 0, 0))
        font = ImageFont.truetype(str(bundled_data_path(self) / "impact.ttf"), 18)
        draw = ImageDraw.Draw(im)
        size_w, size_h = draw.textsize(text, font=font)
        W, H = (size_w + 25, 100)

        images = []
        for i in range(0, W):
            im = Image.new("RGBA", (W, H), colour)
            draw = ImageDraw.Draw(im)
            draw.text((((W - size_w) / 2) - i, (100 - size_h) / 2), text, font=font, fill="white")
            draw.text((10 + W - i, (100 - size_h) / 2), text, font=font, fill="white")
            images.append(np.array(im))

        temp = BytesIO()
        temp.name = "temp.gif"
        imageio.mimwrite(temp, images, "gif", duration=0.02)
        temp.seek(0)
        return temp 
Example #2
Source File: convert_imgs_to_video.py    From 3DDFA with MIT License 6 votes vote down vote up
def main():
    assert len(sys.argv) >= 2
    d = sys.argv[1]

    fps = glob(osp.join(d, '*.jpg'))
    fps = sorted(fps, key=lambda x: int(x.split('/')[-1].replace('.jpg', '')))

    imgs = []
    for fp in fps:
        img = imageio.imread(fp)
        imgs.append(img)

    if len(sys.argv) >= 3:
        imageio.mimwrite(sys.argv[2], imgs, fps=24, macro_block_size=None)
    else:
        imageio.mimwrite(osp.basename(d) + '.mp4', imgs, fps=24, macro_block_size=None) 
Example #3
Source File: viewer.py    From pyrender with MIT License 6 votes vote down vote up
def save_gif(self, filename=None):
        """Save the stored GIF frames to a file.

        To use this asynchronously, run the viewer with the ``record``
        flag and the ``run_in_thread`` flags set.
        Kill the viewer after your desired time with
        :meth:`.Viewer.close_external`, and then call :meth:`.Viewer.save_gif`.

        Parameters
        ----------
        filename : str
            The file to save the GIF to. If not specified,
            a file dialog will be opened to ask the user where
            to save the GIF file.
        """
        if filename is None:
            filename = self._get_save_filename(['gif', 'all'])
        if filename is not None:
            self.viewer_flags['save_directory'] = os.path.dirname(filename)
            imageio.mimwrite(filename, self._saved_frames,
                             fps=self.viewer_flags['refresh_rate'],
                             palettesize=128, subrectangles=True)
        self._saved_frames = [] 
Example #4
Source File: viewer.py    From gqn-dataset-renderer with MIT License 6 votes vote down vote up
def save_gif(self, filename=None):
        """Save the stored GIF frames to a file.

        To use this asynchronously, run the viewer with the ``record``
        flag and the ``run_in_thread`` flags set.
        Kill the viewer after your desired time with
        :meth:`.Viewer.close_external`, and then call :meth:`.Viewer.save_gif`.

        Parameters
        ----------
        filename : str
            The file to save the GIF to. If not specified,
            a file dialog will be opened to ask the user where
            to save the GIF file.
        """
        if filename is None:
            filename = self._get_save_filename(['gif', 'all'])
        if filename is not None:
            self.viewer_flags['save_directory'] = os.path.dirname(filename)
            imageio.mimwrite(filename, self._saved_frames,
                             fps=self.viewer_flags['refresh_rate'],
                             palettesize=128, subrectangles=True)
        self._saved_frames = [] 
Example #5
Source File: vis.py    From phyre with Apache License 2.0 6 votes vote down vote up
def save_observation_series_to_gif(batched_observation_series,
                                   fpath,
                                   solved_states=None):
    """Saves a list of arrays of intermediate scenes as a gif."""
    max_steps = max(len(img) for img in batched_observation_series)
    images_per_step = []
    for step in range(max_steps):
        images_for_step = []
        for i, images in enumerate(batched_observation_series):
            real_step = min(len(images) - 1, step)
            if solved_states is None:
                solved = None
            else:
                solved = solved_states[i]
            images_for_step.append(
                observations_to_uint8_rgb(images[real_step], is_solved=solved))
        images_for_step = np.concatenate(images_for_step, axis=1)
        images_per_step.append(images_for_step)

    imageio.mimwrite(fpath, images_per_step, format="gif") 
Example #6
Source File: Gif_Maker.py    From qxf2-page-object-model with MIT License 6 votes vote down vote up
def make_gif(screenshot_dir_path,name = "test_recap",suffix=".gif",duration=2):
    "Creates gif of the screenshots"
    gif_name = None
    images = []

    if "/" in name:
        name=name.split("/")[-1]

    filenames = os.listdir(screenshot_dir_path)
    if len(filenames) != 0:
        gif_name = os.path.join(screenshot_dir_path, name + suffix)
        for files in sorted(filenames):
            images.append(imageio.imread(os.path.join(screenshot_dir_path, files)))
        imageio.mimwrite(gif_name, images, duration=duration)

    return gif_name 
Example #7
Source File: __init__.py    From stytra with GNU General Public License v3.0 5 votes vote down vote up
def save_data(self):
        if self.base_dir is not None:
            if self.dc is not None:
                # save the stimulus movie if it is generated
                movie, movie_times = self.window_display.widget_display.get_movie()
                if movie is not None:
                    if self.stim_movie_format == "h5":
                        movie_dict = dict(
                            movie=np.stack(movie, 0), movie_times=movie_times
                        )
                        fl.save(
                            self.filename_base() + "stim_movie.h5",
                            movie_dict,
                            compression="blosc",
                        )
                    elif self.stim_movie_format == "mp4":
                        imageio.mimwrite(
                            self.filename_base() + "stim_movie.mp4",
                            movie,
                            fps=30,
                            quality=None,
                            ffmpeg_params=[
                                "-pix_fmt",
                                "yuv420p",
                                "-profile:v",
                                "baseline",
                                "-level",
                                "3",
                            ],
                        )
                    else:
                        raise Exception(
                            "Tried to write the stimulus video into an unsupported format"
                        )
        super().save_data() 
Example #8
Source File: viewer.py    From meshrender with Apache License 2.0 5 votes vote down vote up
def _save_gif(self):
        # Get save file location
        try:
            root = Tk()
            fn = ''
            if self._save_filename:
                fn = '{}.gif'.format(self._save_filename)
            filename = filedialog.asksaveasfilename(initialfile = fn,
                                                    initialdir = (self._save_directory or os.getcwd()),
                                                    title = 'Select file save location',
                                                    filetypes = (('gif files','*.gif'),
                                                                ('all files','*.*')))
        except:
            logging.warning('Cannot use Tkinter file dialogs over SSH')
            self._saved_frames = []
            return

        root.destroy()
        if filename == ():
            self._saved_frames = []
            return
        else:
            self._save_directory = os.path.dirname(filename)

        imageio.mimwrite(filename, self._saved_frames, fps=30.0, palettesize=128, subrectangles=True)

        self._saved_frames = [] 
Example #9
Source File: log.py    From DeepVideoCS with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def write_video(path, idx, video_data, video_format):
    save_path = path + '/' + idx.split('.')[0] + '.' + video_format
    imageio.mimwrite(save_path, video_data, fps=30) 
Example #10
Source File: vis.py    From phyre with Apache License 2.0 5 votes vote down vote up
def compose_gifs(input_fpathes, output_fpath):
    """Concatenate and sync all gifs."""
    all_data = []
    for fname in input_fpathes:
        all_data.append(imageio.mimread(fname))
    max_timestamps = max(len(data) for data in all_data)

    def _pad(data):
        return data + [data[-1]] * (max_timestamps - len(data))

    all_data = np.concatenate([_pad(data) for data in all_data], 1)
    imageio.mimwrite(output_fpath, all_data) 
Example #11
Source File: vis.py    From phyre with Apache License 2.0 5 votes vote down vote up
def compose_gifs_compact(input_fpathes, output_fpath):
    """Create progressin for first and last frames over time."""
    first_and_last_per_batch_id = []
    for fname in input_fpathes:
        data = imageio.mimread(fname)
        data = np.concatenate([data[0], data[-1]], axis=0)
        first_and_last_per_batch_id.append(data)
    if first_and_last_per_batch_id:
        imageio.mimwrite(output_fpath, first_and_last_per_batch_id) 
Example #12
Source File: render_graphics.py    From safelife with Apache License 2.0 5 votes vote down vote up
def _save_movie_data(fname, data, fps, fmt):
    if fmt == 'gif':
        imageio.mimwrite(fname+'.gif', data,
                         duration=1/fps, subrectangles=True)
    else:
        imageio.mimwrite(fname + '.' + fmt, data,
                         fps=fps, macro_block_size=SPRITE_SIZE,
                         ffmpeg_log_level='quiet') 
Example #13
Source File: __init__.py    From pyimagevideo with GNU General Public License v3.0 5 votes vote down vote up
def png2tiff(ofn: Path, pat: str, indir: Path = None):
    """
    convert series of PNG, which may not be exactly the same shape,
    to a multipage TIFF (in the same directory)

    alternatives: use ImageMagick from command line, or Wand.
    however, since the files are grouped in a specific weird way, the histfeas program
    worked best to have this perhaps ImageMagick duplicative functionality in
    Python/imageio/skimage.
    """
    if resize is None:
        raise ImportError('pip install scikit-image')

    ofn = Path(ofn).expanduser()
    indir = ofn.parent if indir is None else Path(indir).expanduser()
# %% convert these sets of images to multipage image
    flist = sorted(indir.glob(pat))  # yes, sorted()
    if not flist:
        raise FileNotFoundError('found no files with {pat} in {ofn}')

    im0 = imageio.imread(flist[0])  # priming read
    images = np.empty((len(flist), *im0.shape), dtype=im0.dtype)
    for i, f in enumerate(flist):
        im = imageio.imread(f)
        images[i, ...] = resize(im, im0.shape, mode='edge')  # they are all of slightly different shape

    imageio.mimwrite(ofn, images) 
Example #14
Source File: imagemaker.py    From Trusty-cogs with MIT License 5 votes vote down vote up
def face_transition(self, images: list) -> BytesIO:
        img_list = []
        # base = Image.open(images[-1])
        for image in images[:-1]:
            overlay = Image.open(image)
            overlay = overlay.resize((256, 256), Image.ANTIALIAS)
            overlay = overlay.convert("RGBA")
            if len(overlay.split()) != 4:
                alpha = Image.new("L", overlay.size, 255)
            else:
                alpha = overlay.convert("L")  # Image.new("L", overlay.size, 255)
            overlay.putalpha(alpha)
            for i in range(0, 50):
                base_img = Image.open(images[-1])
                base_img = base_img.convert("RGBA")
                base_img = base_img.resize((256, 256), Image.ANTIALIAS)
                paste_mask = overlay.split()[3].point(lambda x: x * i / 50)
                base_img.paste(overlay, (0, 0), paste_mask)
                img_list.append(np.array(base_img))
            for i in range(49, -1, -1):
                base_img = Image.open(images[-1])
                base_img = base_img.convert("RGBA")
                base_img = base_img.resize((256, 256), Image.ANTIALIAS)
                paste_mask = overlay.split()[3].point(lambda x: x * i / 50)
                base_img.paste(overlay, (0, 0), paste_mask)
                img_list.append(np.array(base_img))
        # print(len(img_list))
        temp = BytesIO()
        temp.name = "merge.gif"
        imageio.mimwrite(temp, img_list, "gif", duration=0.02)
        return temp 
Example #15
Source File: visualizer.py    From mentornet with Apache License 2.0 5 votes vote down vote up
def _make_gif(input_png_path):
  png_filenames = [t for t in os.listdir(input_png_path) if t.endswith('.png')]
  png_filenames = sort_filename(png_filenames)
  out_gif_filename = os.path.join(input_png_path, 'plot.gif')
  images = []
  for filename in png_filenames:
    images.append(imageio.imread(os.path.join(input_png_path, filename)))
  imageio.mimwrite(out_gif_filename, images, duration=0.5, loop=0) 
Example #16
Source File: visualize_util.py    From disentanglement_lib with Apache License 2.0 5 votes vote down vote up
def save_animation(list_of_animated_images, image_path, fps):
  full_size_images = []
  for single_images in zip(*list_of_animated_images):
    full_size_images.append(
        pad_around(add_below(padded_grid(list(single_images)))))
  imageio.mimwrite(image_path, full_size_images, fps=fps) 
Example #17
Source File: __main__.py    From anishot with MIT License 5 votes vote down vote up
def make_anishot():
    image = Image.fromarray(imageio.imread(ARGS.input.name))
    frames = []

    if ARGS.zoom_steps:
        make_zoomin(image, frames)
    make_scroll(image, frames)

    imageio.mimwrite(ARGS.output,
                     map(lambda f: numpy.array(f[0]), frames),
                     duration=list(map(lambda f: f[1], frames))) 
Example #18
Source File: image_gen.py    From PSSR with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def process_tif(fn, processor, proc_func, out_fn, baseline_dir, n_depth=1, n_time=1, mode='L'):
    with PIL.Image.open(fn) as img_tif:
        n_frame = max(n_depth, n_time)
        offset_frames = n_frame // 2

        if n_frame > img_tif.n_frames:
            if img_tif.n_frames == 1:
                times = n_frame
                img_tif = np.array(img_tif)
                data = np.repeat(img_tif[None],5,axis=0).astype(np.float32)
            else:
                return []
        else:
            times = img_tif.n_frames
            img_tifs = []
            for i in range(times):
                img_tif.seek(i)
                img_tif.load()
                img_tifs.append(np.array(img_tif).copy())
            data = np.stack(img_tifs).astype(np.float32)

        data, img_info = img_to_float(data)
        img_tiffs = []
        time_range = list(range(offset_frames, times - offset_frames))
        for t in progress_bar(time_range):
            time_slice = slice(t-offset_frames, t+offset_frames+1)
            img = data[time_slice].copy()
            pred_img = proc_func(img, img_info=img_info, mode=mode)
            pred_img8 = (pred_img * np.iinfo(np.uint8).max).astype(np.uint8)
            img_tiffs.append(pred_img8[None])

        imgs = np.concatenate(img_tiffs)
        if processor!='bilinear':
            fldr_name = f'{out_fn.parent}/{processor}'
        else:
            fldr_name = out_fn.parent.parent.parent/processor/out_fn.parent.stem
        save_name = f'{fn.stem}_{processor}.tif'
        out_fldr = ensure_folder(out_fn.parent/processor)

        if imgs.size < 4e9:
            imageio.mimwrite(out_fldr/save_name, imgs)
        else:
            imageio.mimwrite(out_fldr/save_name, imgs, bigtiff=True)
        #imageio.mimwrite((out_fldr/save_name).with_suffix('.mp4'), imgs, fps=30, macro_block_size=None) 
Example #19
Source File: utils.py    From PSSR with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def tif_predict_images(learn,
                       tif_in,
                       dest,
                       category,
                       tag=None,
                       size=128,
                       max_imgs=None):
    under_tag = f'_' if tag is None else f'_{tag}_'
    dest_folder = Path(dest / category)
    dest_folder.mkdir(exist_ok=True, parents=True)
    pred_out = dest_folder / f'{tif_in.stem}{under_tag}pred.tif'
    orig_out = dest_folder / f'{tif_in.stem}{under_tag}orig.tif'
    if pred_out.exists():
        print(f'{pred_out.stem} exists')
        return

    im = PIL.Image.open(tif_in)
    im.load()
    times = im.n_frames
    if not max_imgs is None: times = min(max_imgs, times)

    imgs = []

    for i in range(times):
        im.seek(i)
        im.load()
        imgs.append(np.array(im))

    imgs, img_info = img_to_float(np.stack(imgs))

    preds = []

    x, y = im.size
    print(f'tif: x:{x} y:{y} t:{times}')
    for t in progress_bar(list(range(times))):
        img = imgs[t]
        img = img.copy()

    if len(preds) > 0:
        all_y = img_to_uint8(np.concatenate(preds))
        imageio.mimwrite(pred_out, all_y, bigtiff=True)
        shutil.copy(tif_in, orig_out) 
Example #20
Source File: utils.py    From PSSR with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def czi_predict_movie(learn,
                      czi_in,
                      orig_out='orig.tif',
                      pred_out='pred.tif',
                      size=128,
                      wsize=3):
    with czifile.CziFile(czi_in) as czi_f:
        proc_axes, proc_shape = get_czi_shape_info(czi_f)
        channels = proc_shape['C']
        depths = proc_shape['Z']
        times = proc_shape['T']
        #times = min(times, 100)
        x, y = proc_shape['X'], proc_shape['Y']
        #print(f'czi: x:{x} y:{y} t:{times} z:{depths}')
        if times < (wsize + 2):
            print(f'skip {czi_in} only {times} frames')
            return

        #folder_name = Path(pred_out).stem
        #folder = Path(folder_name)
        #if folder.exists(): shutil.rmtree(folder)
        #folder.mkdir()

        data = czi_f.asarray().astype(np.float32) / 255.
        preds = []
        origs = []

        img_max = data.max()
        #print(img_max)
        for t in progress_bar(list(range(0, times - wsize + 1))):
            idx = build_index(
                proc_axes, {
                    'T': slice(t, t + wsize),
                    'C': 0,
                    'Z': 0,
                    'X': slice(0, x),
                    'Y': slice(0, y)
                })
            img = data[idx].copy()
            img /= img_max

            out_img = unet_multi_image_from_tiles(learn,
                                                  img,
                                                  tile_sz=size,
                                                  wsize=wsize)
            pred = (out_img * 255).cpu().numpy().astype(np.uint8)
            preds.append(pred)
            #imsave(folder/f'{t}.tif', pred[0])

            orig = (img[wsize // 2][None] * 255).astype(np.uint8)
            origs.append(orig)
        if len(preds) > 0:
            all_y = img_to_uint8(np.concatenate(preds))
            imageio.mimwrite(
                pred_out, all_y,
                bigtiff=True)  #, fps=30, macro_block_size=None) # for mp4

            all_y = img_to_uint8(np.concatenate(origs))
            imageio.mimwrite(orig_out, all_y,
                             bigtiff=True)  #, fps=30, macro_block_size=None) 
Example #21
Source File: utils.py    From PSSR with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def tif_predict_movie(learn,
                      tif_in,
                      orig_out='orig.tif',
                      pred_out='pred.tif',
                      size=128,
                      wsize=3):
    im = PIL.Image.open(tif_in)
    im.load()
    times = im.n_frames
    #times = min(times,100)
    imgs = []

    if times < (wsize + 2):
        print(f'skip {tif_in} only {times} frames')
        return

    for i in range(times):
        im.seek(i)
        imgs.append(np.array(im).astype(np.float32) / 255.)
    img_data = np.stack(imgs)

    def pull_frame(i):
        im.seek(i)
        im.load()
        return np.array(im)

    preds = []
    origs = []
    img_max = img_data.max()

    x, y = im.size
    #print(f'tif: x:{x} y:{y} t:{times}')
    for t in progress_bar(list(range(0, times - wsize + 1))):
        img = img_data[t:(t + wsize)].copy()
        img /= img_max

        out_img = unet_multi_image_from_tiles(learn,
                                              img,
                                              tile_sz=size,
                                              wsize=wsize)
        pred = (out_img * 255).cpu().numpy().astype(np.uint8)
        preds.append(pred)
        orig = (img[1][None] * 255).astype(np.uint8)
        origs.append(orig)
    if len(preds) > 0:
        all_y = img_to_uint8(np.concatenate(preds))
        imageio.mimwrite(
            pred_out, all_y,
            bigtiff=True)  #, fps=30, macro_block_size=None) # for mp4
        all_y = img_to_uint8(np.concatenate(origs))
        imageio.mimwrite(orig_out, all_y,
                         bigtiff=True)  #, fps=30, macro_block_size=None) 
Example #22
Source File: base.py    From pulse2percept with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def save(self, fname, shape=None, fps=None):
        """Save the percept as an MP4 or GIF

        Parameters
        ----------
        fname : str
            The filename to be created, with the file extension indicating the
            file type. Percepts with time=None can be saved as images (e.g.,
            '.jpg', '.png', '.gif'). Multi-frame percepts can be saved as
            movies (e.g., '.mp4', '.avi', '.mov') or '.gif'.
        shape : (height, width) or None, optional, default: (320,)
            The desired width x height of the resulting image/video.
            Use (h, None) to use a specified height and automatically infer the
            width from the percept's aspect ratio.
            Analogously, use (None, w) to use a specified width.
            If shape is None, width will be set to 320px and height will be
            inferred accordingly.
        fps : float or None
            If None, uses the percept's time axis. Not supported for
            non-homogeneous time axis.

        Notes
        -----
        *  ``shape`` will be adjusted so that width and height are multiples
            of 16 to ensure compatibility with most codecs and players.

        """
        data = self.data - self.data.min()
        if not np.isclose(np.max(data), 0):
            data /= np.max(data)
        data = img_as_uint(data)

        if shape is None:
            # Use 320px width and infer height from aspect ratio:
            shape = (None, 320)
        height, width = shape
        if height is None and width is None:
            raise ValueError('If shape is a tuple, must specify either height '
                             'or width or both.')
        # Infer height or width if necessary:
        if height is None and width is not None:
            height = width / self.data.shape[1] * self.data.shape[0]
        elif height is not None and width is None:
            width = height / self.data.shape[0] * self.data.shape[1]
        # Rescale percept to desired shape:
        data = resize(data, (np.int32(height), np.int32(width)))

        if self.time is None:
            # No time component, store as an image. imwrite will automatically
            # scale the gray levels:
            imageio.imwrite(fname, data)
        else:
            # With time component, store as a movie:
            if fps is None:
                interval = self._get_interval()
                if len(interval) > 1:
                    raise NotImplementedError
                fps = 1000.0 / interval[0]
            imageio.mimwrite(fname, data.transpose((2, 0, 1)), fps=fps)
        logging.getLogger(__name__).info('Created %s.' % fname)