Python imageio.mimsave() Examples
The following are 30
code examples of imageio.mimsave().
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: viz.py From cortex with BSD 3-Clause "New" or "Revised" License | 6 votes |
def save_movie(images, num_x, num_y, out_file=None, movie_id=0): if out_file is None: logger.warning('`out_file` not provided. Not saving.') else: images_ = [] for i, image in enumerate(images): if _options['quantized']: image = dequantize(image) dim_c, dim_x, dim_y = image.shape[-3:] image = image.reshape((num_x, num_y, dim_c, dim_x, dim_y)) image = image.transpose(0, 3, 1, 4, 2) image = image.reshape(num_x * dim_x, num_y * dim_y, dim_c) if _options['use_tanh']: image = 0.5 * (image + 1.) images_.append(image) imageio.mimsave(out_file, images_) visualizer.video(videofile=out_file, env=exp.NAME, win='movie_{}'.format(movie_id))
Example #2
Source File: solvers.py From ganimation_replicate with MIT License | 6 votes |
def test_save_imgs(self, faces_list, paths_list): for idx in range(len(paths_list[0])): src_name = os.path.splitext(os.path.basename(paths_list[0][idx]))[0] tar_name = os.path.splitext(os.path.basename(paths_list[1][idx]))[0] if self.opt.save_test_gif: import imageio imgs_numpy_list = [] for face_idx in range(len(faces_list) - 1): # remove target image cur_numpy = np.array(self.visual.numpy2im(faces_list[face_idx][idx])) imgs_numpy_list.extend([cur_numpy for _ in range(3)]) saved_path = os.path.join(self.opt.results, "%s_%s.gif" % (src_name, tar_name)) imageio.mimsave(saved_path, imgs_numpy_list) else: # concate src, inters, tar faces concate_img = np.array(self.visual.numpy2im(faces_list[0][idx])) for face_idx in range(1, len(faces_list)): concate_img = np.concatenate((concate_img, np.array(self.visual.numpy2im(faces_list[face_idx][idx]))), axis=1) concate_img = Image.fromarray(concate_img) # save image saved_path = os.path.join(self.opt.results, "%s_%s.jpg" % (src_name, tar_name)) concate_img.save(saved_path) print("[Success] Saved images to %s" % saved_path)
Example #3
Source File: movie.py From k2mosaic with MIT License | 6 votes |
def to_movie(self, output_fn, fps=15., dpi=50, cut=None, cmap='gray', extension=1): viz = [] with click.progressbar(self.mosaic_filenames, label="Reading mosaics", show_pos=True) as bar: for fn in bar: try: frame = KeplerMosaicMovieFrame(fn) fig = frame.to_fig(rowrange=self.rowrange, colrange=self.colrange, dpi=dpi, cut=cut, cmap=cmap, extension=extension,) img = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='') img = img.reshape(fig.canvas.get_width_height()[::-1] + (3,)) pl.close(fig) # Avoid memory leak! viz.append(img) except InvalidFrameException: print("InvalidFrameException for {}".format(fn)) # Save the output as a movie if output_fn.endswith('.gif'): kwargs = {'duration': 1. / fps} else: kwargs = {'fps': fps} imageio.mimsave(output_fn, viz, **kwargs)
Example #4
Source File: utils.py From cvlib with MIT License | 6 votes |
def animate(src, gif_name, reshape=None, fps=25): if not isinstance(src, list): if os.path.isdir(src): src = list(paths.list_images(src)) for idx, image in enumerate(src): src[idx] = cv2.imread(image) if reshape: for idx, image in enumerate(src): src[idx] = cv2.resize(image, reshape) for idx, image in enumerate(src): src[idx] = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) src = np.array(src) imageio.mimsave(gif_name, src, fps=fps)
Example #5
Source File: video.py From drawSvg with MIT License | 6 votes |
def save_video(frames, file, **kwargs): ''' Save a series of drawings as a GIF or video. Arguments: frames: A list of `Drawing`s or a list of `numpy.array`s. file: File name or file like object to write the video to. The extension determines the output format. align_bottom: If frames are different sizes, align the bottoms of each frame in the video. align_right: If frames are different sizes, align the right edge of each frame in the video. bg: If frames are different sizes, fill the background with this color. (default is white: (255, 255, 255, 255)) duration: If writing a GIF, sets the duration of each frame. fps: If writing a video, sets the frame rate in FPS. **kwargs: Other arguments to imageio.mimsave(). ''' if isinstance(frames[0], Drawing): frames = render_svg_frames(frames, **kwargs) kwargs.pop('align_bottom', None) kwargs.pop('align_right', None) kwargs.pop('bg', None) imageio.mimsave(file, frames, **kwargs)
Example #6
Source File: viz.py From pyAFQ with BSD 2-Clause "Simplified" License | 6 votes |
def create_gif(scene, file_name, n_frames=60, size=(600, 600)): tdir = tempfile.gettempdir() window.record(scene, az_ang=360.0 / n_frames, n_frames=n_frames, path_numbering=True, out_path=tdir + '/tgif', size=size) angles = [] for i in range(n_frames): if i < 10: angle_fname = f"tgif00000{i}.png" elif i < 100: angle_fname = f"tgif0000{i}.png" else: angle_fname = f"tgif000{i}.png" angles.append(io.imread(os.path.join(tdir, angle_fname))) io.mimsave(file_name, angles)
Example #7
Source File: graph_animator.py From lookml-tools with Apache License 2.0 | 6 votes |
def generate_gif(self, filenames, gif_filename): '''create an animated GIF given a list of images Args: filenames (list): list of image filenames, ordered in required sequence gif_filename (str): filepath of final GIF file Returns: nothing. Side effect is to save a GIF file at gif_filename ''' images = [] for filename in filenames: if os.path.exists(filename): logging.info("Adding to gif: image " + filename) images.append(imageio.imread(filename)) logging.info("Creating GIF. This can take some time...") imageio.mimsave(gif_filename, images) logging.info("Gif generated at " + gif_filename)
Example #8
Source File: training.py From Self-Supervised-Gans-Pytorch with MIT License | 6 votes |
def train(self, data_loader, epochs, save_training_gif=True): if save_training_gif: # Fix latents to see how image generation improves during training fixed_latents = Variable(self.G.sample_latent(64)) if self.use_cuda: fixed_latents = fixed_latents.cuda() training_progress_images = [] for epoch in range(epochs): print("\nEpoch {}".format(epoch + 1)) self._train_epoch(data_loader) if save_training_gif: # Generate batch of images and convert to grid img_grid = make_grid(self.G(fixed_latents).cpu().data) # Convert to numpy and transpose axes to fit imageio convention # i.e. (width, height, channels) img_grid = np.transpose(img_grid.numpy(), (1, 2, 0)) # Add image grid to training progress training_progress_images.append(img_grid) if save_training_gif: imageio.mimsave('./training_{}_epochs.gif'.format(epochs), training_progress_images)
Example #9
Source File: pgn2gif.py From pgn2gif with MIT License | 6 votes |
def create_gif(pgn, gif_path, duration): board_image = initial_board.copy() images = [array(board_image)] game = chess.ChessGame() moves = chess.get_moves_from_pgn(pgn) for move in moves: previous = game.state.copy() game.push(move) apply_move(board_image, game.state, previous) images.append(array(board_image)) last = images[len(moves)] for i in range(3): images.append(last) imageio.mimsave(gif_path, images, duration=duration)
Example #10
Source File: visualize_temp.py From pySDC with BSD 2-Clause "Simplified" License | 6 votes |
def make_movie_from_files(path='./data', name='', output='.'): """ Visualization using numpy arrays (written via MPI I/O) and json description Produces one png file per time-step, combine as movie via e.g. > ffmpeg -i data/name_%08d.png name.mp4 Args: path (str): path to data files name (str): name of the simulation (expects data to be in data path) output (str): path to output """ img_files = sorted(glob.glob(f'{path}/{name}_*.png')) print(f'{path}{name}') images = [] for fimg in img_files: img = imageio.imread(fimg) print(fimg, img.shape) images.append(imageio.imread(fimg)) fname = f'{output}/{name}.mp4' imageio.mimsave(fname, images, fps=8)
Example #11
Source File: graphics.py From robopy with MIT License | 6 votes |
def timer_tick(self): import imageio self.timer_count += 1 if self.timer_count >= self.total_time_steps: self.iren.DestroyTimer() if self.gif_file is not None: assert len(self.gif_data) > 0 imageio.mimsave(self.gif_file + '.gif', self.gif_data) import os for i in range(self.screenshot_count): os.remove(self.gif_file + '%d.png' % i) return if self.gif_file is not None: if (self.timer_count % 60) == 0: self.screenshot(self.gif_file) path = self.gif_file + '%d.png' % (self.screenshot_count - 1) self.gif_data.append(imageio.imread(path))
Example #12
Source File: gif.py From yoda with MIT License | 5 votes |
def from_images(ctx): #importing imageio in theis function improves load time for all yoda commands import imageio args = { ctx.args[i].strip("--"): ctx.args[i + 1] for i in range(0, len(ctx.args), 2) } try: source = args.pop("source") except KeyError: click.echo( chalk.red( "Source parameter is missing. " "Use --source to provide the path." ) ) return try: output = args.pop("output") except KeyError: click.echo( chalk.red("Output path is missing. " "Use --output to provide the path.") ) return images = [] if not os.path.isdir(source): click.echo(chalk.red("Source should be a directory.")) for filename in os.listdir(source): if os.path.isfile(os.path.join(source, filename)): images.append(imageio.imread(os.path.join(source, filename))) try: with open(output, "w") as outfile: imageio.mimsave(outfile, images, format="gif", **args) click.echo(chalk.green("GIF exported at {}".format(output))) except (OSError, IOError): click.echo( chalk.red( "Could not write to file {}. " "Please check the path".format(output) ) )
Example #13
Source File: Environment.py From Deep-RL-agents with MIT License | 5 votes |
def save_gif(self, path): os.makedirs(os.path.dirname(path), exist_ok=True) imageio.mimsave(path, self.img_buffer, duration=0.001) self.img_buffer = []
Example #14
Source File: pyCrawler_function.py From weibo-crawler with MIT License | 5 votes |
def create_gif(path_gif, duration_gif, folder_frame, frmt_frame='.jpg'): '''Create a GIF image with the given frames. Parameters: path_gif <str> - The path for saving the output GIF image. duration_gif <float> - The duration of the output GIF image. folder_frame <str> - The folder of the input frames. frmt_frame <str> - The format of the input frames. Default is '.jpg'. Return: 0 <int> - If the task is completed. ''' # Get the name of the input (sorted) frames. imgFames = sorted((iN for iN in os.listdir(folder_frame) if iN.endswith(frmt_frame))) # Calculate the duration of each frame. duration_frame = duration_gif / len(imgFames) # Create the output GIF image. imgGIF = [] for imgFame in imgFames: # Scale down the size of each frame. resize_image(folder_frame + imgFame) # Concatenate each frame. imgGIF.append(imageio.imread(folder_frame + imgFame)) # Save the output GIF image. imageio.mimsave(path_gif, imgGIF, duration=duration_frame) return 0
Example #15
Source File: train.py From robin with MIT License | 5 votes |
def on_train_end(self, logs=None): for fname in self.fnames: frames = [] for frame_name in sorted(os.listdir(os.path.join(self.dir_name, fname[:fname.rfind('.')] + '_frames'))): frames.append(imageio.imread(os.path.join(self.dir_name, fname[:fname.rfind('.')] + '_frames', frame_name))) imageio.mimsave(os.path.join(self.dir_name, fname[:fname.rfind('.')] + '.gif'), frames, format='GIF', duration=0.5) # rmtree(os.path.join(self.dir_name, fname[:fname.rfind('.')] + '_frames'))
Example #16
Source File: show_result.py From Tensorflow-Computer-Vision-Tutorial with MIT License | 5 votes |
def dcgan(): import imageio images = [] files = [file for file in os.listdir('../results') if file.startswith('dcgan') and file.endswith('.png')] for file in files: images.append(imageio.imread(os.path.join('../results', file))) imageio.mimsave('../results/dcgan.gif', images, fps=5)
Example #17
Source File: gif.py From dreampower with GNU General Public License v3.0 | 5 votes |
def _execute(self, *args): """ Execute all phases on each frames of the gif and recreate the gif. :return: None """ MultipleImageProcessing().run(config=self._args) dir_out = os.path.dirname(self.__output_path) if dir_out != '': os.makedirs(dir_out, exist_ok=True) imageio.mimsave(self.__output_path, [imageio.imread(i) for i in self.__temp_output_paths]) Conf.log.info("{} Gif Created ".format(self.__output_path))
Example #18
Source File: plot_utils.py From teachDeepRL with MIT License | 5 votes |
def gmm_plot_gif(bk, gifname='test', gifdir='graphics/', ax=None, xlim=[0,1], ylim=[0,1], fig_size=(9,6), save_imgs=False, title=True, bar=True): gifdir = 'graphics/' + gifdir plt.ioff() # Create target Directory if don't exist tmpdir = 'tmp/' tmppath = gifdir + 'tmp/' if not os.path.exists(gifdir): os.mkdir(gifdir) print("Directory ", gifdir, " Created ") if not os.path.exists(tmppath): os.mkdir(tmppath) print("Directory ", tmppath, " Created ") print("Making " + tmppath + gifname + ".gif") images = [] old_ep = 0 gen_size = int(len(bk['tasks_lps']) / len(bk['episodes'])) gs_lps = bk['tasks_lps'] for i,(ws, covs, means, ep) in enumerate(zip(bk['weights'], bk['covariances'], bk['means'], bk['episodes'])): plt.figure(figsize=fig_size) ax = plt.gca() plot_gmm(ws, means, covs, np.array(gs_lps[old_ep + gen_size:ep + gen_size]), ax=ax, xlim=xlim, ylim=ylim, bar=bar) # add gen_size to have gmm + the points that they generated, not they fitted if 'comp_grids' in bk: # add competence grid info draw_competence_grid(ax,bk['comp_grids'][i], bk['comp_xs'][i], bk['comp_ys'][i]) if 'start_points' in bk: # add lineworld info draw_lineworld_info(ax, bk['start_points'], bk['end_points'], bk['current_states'][i]) f_name = gifdir+tmpdir+gifname+"_{}.png".format(ep) if title: plt.suptitle('Episode {} | nb Gaussians:{}'.format(ep,len(means)), fontsize=20) old_ep = ep if save_imgs: plt.savefig(f_name, bbox_inches='tight') images.append(plt_2_rgb(ax)) plt.close() imageio.mimsave(gifdir + gifname + '.gif', images, duration=0.4)
Example #19
Source File: Environment.py From Deep-RL-agents with MIT License | 5 votes |
def save_gif(self): if not self.images: return print("Saving gif in ", GIF_PATH, "...", sep='') number = self.n_gif.get(self.name_gif, 0) path = GIF_PATH + self.name_gif + str(number) + ".gif" os.makedirs(os.path.dirname(path), exist_ok=True) imageio.mimsave(path, self.images, duration=1) self.images = [] self.n_gif[self.name_gif] = (number + 1) % MAX_NB_GIF self.name_gif = 'save_'
Example #20
Source File: plot_utils.py From teachDeepRL with MIT License | 5 votes |
def random_plot_gif(bk, step=250, gifname='test', gifdir='graphics/', ax=None, xlim=[0,1], ylim=[0,1], fig_size=(9,6), save_imgs=False, title=True, bar=True): gifdir = 'graphics/' + gifdir plt.ioff() # Create target Directory if don't exist tmpdir = 'tmp/' tmppath = gifdir + 'tmp/' if not os.path.exists(gifdir): os.mkdir(gifdir) print("Directory ", gifdir, " Created ") if not os.path.exists(tmppath): os.mkdir(tmppath) print("Directory ", tmppath, " Created ") print("Making " + tmppath + gifname + ".gif") images = [] tasks = np.array(bk['tasks']) for i,(c_grids, c_xs, c_ys) in enumerate(zip(bk['comp_grids'], bk['comp_xs'], bk['comp_ys'])): plt.figure(figsize=fig_size) ax = plt.gca() draw_competence_grid(ax, c_grids, c_xs, c_ys) ax.scatter(tasks[i*step:(i+1)*step, 0], tasks[i*step:(i+1)*step, 1], c='blue', s=2, zorder=2) ax.set_xlim(left=xlim[0], right=xlim[1]) ax.set_ylim(bottom=ylim[0], top=ylim[1]) ax.tick_params(axis='both', which='major', labelsize=20) ax.set_aspect('equal', 'box') f_name = gifdir+tmpdir+gifname+"_{}.png".format(i) if title: plt.suptitle('Episode {}'.format(i*step), fontsize=20) if save_imgs: plt.savefig(f_name, bbox_inches='tight') images.append(plt_2_rgb(ax)) plt.close() imageio.mimsave(gifdir + gifname + '.gif', images, duration=0.4)
Example #21
Source File: example.py From Pytorch-Project-Template with MIT License | 5 votes |
def make_gif(self, epochs): """ Make a gif from a multiple images of epochs :param epochs: num_epochs till now :return: """ gen_image_plots = [] for epoch in range(epochs + 1): img_epoch = '{}samples_epoch_{:d}.png'.format(self.config.out_dir, epoch) try: gen_image_plots.append(imageio.imread(img_epoch)) except OSError as e: pass imageio.mimsave(self.config.out_dir + 'animation_epochs_{:d}.gif'.format(epochs), gen_image_plots, fps=2)
Example #22
Source File: Environment.py From Deep-RL-agents with MIT License | 5 votes |
def save_gif(self, path): os.makedirs(os.path.dirname(path), exist_ok=True) imageio.mimsave(path, self.img_buffer, duration=0.001) self.img_buffer = []
Example #23
Source File: Environment.py From Deep-RL-agents with MIT License | 5 votes |
def save_gif(self, path): os.makedirs(os.path.dirname(path), exist_ok=True) imageio.mimsave(path, self.img_buffer, duration=0.001) self.img_buffer = []
Example #24
Source File: parse_ec2_results.py From deep_image_prior with Apache License 2.0 | 5 votes |
def make_gif(output_file=output_name+'.gif', folder=input_folder+'output/', output_size=output_size): imgs = [] for i in range(100): img = Image.open('{}output_{}.jpg'.format(folder,i)) img = img.resize((output_size, output_size)) img = np.array(img) imgs.append(img) imageio.mimsave(output_file, imgs)
Example #25
Source File: Environment.py From Deep-RL-agents with MIT License | 5 votes |
def save_gif(self, path, i): path = path + "_{}.gif".format(i) os.makedirs(os.path.dirname(path), exist_ok=True) imageio.mimsave(path, self.images, duration=1) self.images = []
Example #26
Source File: EnvironmentFlappy.py From Deep-RL-agents with MIT License | 5 votes |
def save_gif(self): """ If images have been saved in the memory list, save these images in a gif. The gif will have the name given in the set_gif method (default to 'save_') plus a number corresponding to the number of gifs saved with that name plus one. For instance, if set_gif is called twice with name='example_gif' and once with name='other_example_gif', then three gifs will be saved with the names 'example_gif_0', 'example_gif_1' and 'other_example_gif_0'. The gif number wraps to 0 after Settings.MAX_NB_GIF (which will overwrite the first gif saved). """ if not self.images: return print("Saving gif in ", Settings.GIF_PATH, "...", sep='') number = self.n_gif.get(self.name_gif, 0) path = Settings.GIF_PATH + self.name_gif + str(number) + ".gif" os.makedirs(os.path.dirname(path), exist_ok=True) imageio.mimsave(path, self.images, duration=1) self.images = [] self.n_gif[self.name_gif] = (number + 1) % Settings.MAX_NB_GIF self.name_gif = 'save_' print("Gif saved!\n")
Example #27
Source File: Environment.py From Deep-RL-agents with MIT License | 5 votes |
def save_gif(self): """ If images have been saved in the memory list, save these images in a gif. The gif will have the name given in the set_gif method (default to 'save_') plus a number corresponding to the number of gifs saved with that name plus one. For instance, if set_gif is called twice with name='example_gif' and once with name='other_example_gif', then three gifs will be saved with the names 'example_gif_0', 'example_gif_1' and 'other_example_gif_0'. The gif number wraps to 0 after Settings.MAX_NB_GIF (which will overwrite the first gif saved). """ if not self.images: return print("Saving gif in ", Settings.GIF_PATH, "...", sep='') number = self.n_gif.get(self.name_gif, 0) path = Settings.GIF_PATH + self.name_gif + str(number) + ".gif" os.makedirs(os.path.dirname(path), exist_ok=True) imageio.mimsave(path, self.images, duration=1) self.images = [] self.n_gif[self.name_gif] = (number + 1) % Settings.MAX_NB_GIF self.name_gif = 'save_' print("Gif saved!\n")
Example #28
Source File: utils.py From zi2zi with Apache License 2.0 | 5 votes |
def compile_frames_to_gif(frame_dir, gif_file): frames = sorted(glob.glob(os.path.join(frame_dir, "*.png"))) print(frames) images = [misc.imresize(imageio.imread(f), interp='nearest', size=0.33) for f in frames] imageio.mimsave(gif_file, images, duration=0.1) return gif_file
Example #29
Source File: utils.py From ENAS-pytorch with Apache License 2.0 | 5 votes |
def make_gif(paths, gif_path, max_frame=50, prefix=""): import imageio paths.sort() skip_frame = len(paths) // max_frame paths = paths[::skip_frame] images = [imageio.imread(path) for path in paths] max_h, max_w, max_c = np.max( np.array([image.shape for image in images]), 0) for idx, image in enumerate(images): h, w, c = image.shape blank = np.ones([max_h, max_w, max_c], dtype=np.uint8) * 255 pivot_h, pivot_w = (max_h-h)//2, (max_w-w)//2 blank[pivot_h:pivot_h+h,pivot_w:pivot_w+w,:c] = image images[idx] = blank try: images = [Image.fromarray(image) for image in images] draws = [ImageDraw.Draw(image) for image in images] font = ImageFont.truetype("assets/arial.ttf", 30) steps = [int(os.path.basename(path).rsplit('.', 1)[0].split('-')[1]) for path in paths] for step, draw in zip(steps, draws): draw.text((max_h//20, max_h//20), f"{prefix}step: {format(step, ',d')}", (0, 0, 0), font=font) except IndexError: pass imageio.mimsave(gif_path, [np.array(img) for img in images], duration=0.5) ########################## # Torch ##########################
Example #30
Source File: conversions.py From asciisciit with MIT License | 5 votes |
def ascii_seq_to_gif(seq, output_path, fps=15.0, font_size=10, font_path=None): """ Creates a gif from a sequence of ascii images. Parameters ---------- output_path : str Path for gif output. fps : float FPS for gif playback. font_size : int Font size for ascii. """ images = [] status = StatusBar(len(seq), text="Generating frames: ",) for index, ascii_img in enumerate(seq): if type(ascii_img) == str: #raw text text = ascii_img else: #AsciiImage instance text = ascii_img.data images.append( ascii_to_pil(text, font_size=font_size, font_path=font_path ) ) status.update(index) status.complete() duration = 1.0/fps images_np = [np.array(img) for img in images] imageio.mimsave(output_path, images_np, duration=duration)