本文整理匯總了Python中imageio.mimsave方法的典型用法代碼示例。如果您正苦於以下問題:Python imageio.mimsave方法的具體用法?Python imageio.mimsave怎麽用?Python imageio.mimsave使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類imageio
的用法示例。
在下文中一共展示了imageio.mimsave方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: create_gif
# 需要導入模塊: import imageio [as 別名]
# 或者: from imageio import mimsave [as 別名]
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)
示例2: save_movie
# 需要導入模塊: import imageio [as 別名]
# 或者: from imageio import mimsave [as 別名]
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))
示例3: train
# 需要導入模塊: import imageio [as 別名]
# 或者: from imageio import mimsave [as 別名]
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)
示例4: generate_gif
# 需要導入模塊: import imageio [as 別名]
# 或者: from imageio import mimsave [as 別名]
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)
示例5: create_gif
# 需要導入模塊: import imageio [as 別名]
# 或者: from imageio import mimsave [as 別名]
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)
示例6: save_video
# 需要導入模塊: import imageio [as 別名]
# 或者: from imageio import mimsave [as 別名]
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)
示例7: animate
# 需要導入模塊: import imageio [as 別名]
# 或者: from imageio import mimsave [as 別名]
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)
示例8: test_save_imgs
# 需要導入模塊: import imageio [as 別名]
# 或者: from imageio import mimsave [as 別名]
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)
示例9: make_movie_from_files
# 需要導入模塊: import imageio [as 別名]
# 或者: from imageio import mimsave [as 別名]
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)
示例10: timer_tick
# 需要導入模塊: import imageio [as 別名]
# 或者: from imageio import mimsave [as 別名]
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))
示例11: to_movie
# 需要導入模塊: import imageio [as 別名]
# 或者: from imageio import mimsave [as 別名]
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)
示例12: make_gif
# 需要導入模塊: import imageio [as 別名]
# 或者: from imageio import mimsave [as 別名]
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)
示例13: dynamic_download_and_Synthesizing
# 需要導入模塊: import imageio [as 別名]
# 或者: from imageio import mimsave [as 別名]
def dynamic_download_and_Synthesizing(illust_id, title=None, prefix=None):
tag = 'Dynamic_Download_And_Synthesizing'
d_json_data = 'https://www.pixiv.net/ajax/illust/' + str(illust_id) + '/ugoira_meta'
d_json_decoded = json.loads(get_text_from_url(d_json_data))['body']
src_zip_url = d_json_decoded['originalSrc']
src_mime_type = d_json_decoded['mime_type']
src_img_delay = int(d_json_decoded['frames'][0]['delay']) / 1000
src_saved_path = save_path + 'TEMP' + global_symbol + str(illust_id) + global_symbol + \
src_zip_url.split('/')[-1]
src_saved_dir = save_path + 'TEMP' + global_symbol + str(illust_id) + global_symbol
src_final_dir = save_path + 'Dynamic' + global_symbol
download_thread(src_zip_url, save_path, None, 'TEMP' + global_symbol + str(illust_id))
while not os.path.exists(src_saved_path + '.done'):
time.sleep(1)
print_with_tag(tag, 'Waiting for complete...')
print_with_tag(tag, ['Zip target downloaded:', src_saved_path])
with zipfile.ZipFile(src_saved_path, 'r') as zip_file:
zip_file.extractall(path=src_saved_dir)
# get each frame
sort_by_num = []
frames = []
for root, dirs, files in os.walk(src_saved_dir):
for file in files:
if file.endswith('jpg') or file.endswith('png'):
sort_by_num.append(src_saved_dir + global_symbol + file)
sort_by_num.sort()
print_with_tag(tag, 'Reading each frame..')
for each_frame in sort_by_num:
frames.append(imageio.imread(each_frame))
gif_save_dir = save_path + str(prefix) + global_symbol + year_month + str(
day) + global_symbol + 'D-' + str(illust_id) + global_symbol
gif_name_format = re.sub('[\/:*?"<>|]', '_', str(title)) + '-' + str(illust_id) + '.gif'
if not os.path.exists(gif_save_dir):
os.makedirs(gif_save_dir)
print_with_tag(tag, 'Synthesizing dynamic images..')
try:
imageio.mimsave(gif_save_dir + gif_name_format, frames, duration=src_img_delay)
except Exception as e:
print_with_tag(tag, [gif_save_dir + gif_name_format])
print_with_tag(tag, e)
exit()
示例14: create_gif
# 需要導入模塊: import imageio [as 別名]
# 或者: from imageio import mimsave [as 別名]
def create_gif(self, dirname, density=False):
images = []
if density:
filenames = [x for x in os.listdir(dirname) if '_density.png' in x]
sorted_fnames = sorted(filenames, key=lambda x: int(x.split('_density.png')[0]))
else:
filenames = [x for x in os.listdir(dirname) if ('.png' in x and 'density' not in x)]
sorted_fnames = sorted(filenames, key=lambda x: int(x.split('.png')[0]))
for f in sorted_fnames:
images.append(imageio.imread(os.path.join(dirname, f)))
imageio.mimsave(os.path.join(dirname, 'exploration.gif'), images)
示例15: save
# 需要導入模塊: import imageio [as 別名]
# 或者: from imageio import mimsave [as 別名]
def save(self, file_name):
if self.enabled:
path = os.path.join(self.dir_name, file_name)
imageio.mimsave(path, self.frames, fps=self.fps)