def create_composite_image_coin_id(coin_id, crop_dir, data_dir):
images = []
images_gif = []
for id in range(0,56):
image_id = coin_id * 100 + id
crop = ci.get_rotated_crop(crop_dir, image_id, 56, 0)
images.append(crop)
filename = ci.get_filename_from(image_id,crop_dir)
images_gif.append(imageio.imread(filename))
composite_image = ci.get_composite_image(images, 8, 8)
cv2.imwrite(data_dir + str(coin_id) + '.png', composite_image)
imageio.mimsave(data_dir + str(coin_id) + '.gif', images_gif)
return
python类mimsave()的实例源码
def draw1DMovie(solution, t_filming_step, x_start, x_end, legend, t_grid_step):
#??????? ????? ?? ?????????? img\ ????? ????????? ????????.
files = glob.glob('img' + os.sep + '*')
for f in files:
os.remove(f)
#???????? ????????? ?????? ?? ??????? ? ?????.
for i in range(0, solution.shape[0], t_filming_step):
draw1DSlice(solution[i], i * t_grid_step, x_start, x_end, legend, np.max(solution))
#?????? ????? ?? ??????????? ????? img\, ????????? ?? ???? ??.
images = []
filenames = sorted(fn for fn in os.listdir(path='img' + os.sep) if fn.endswith('.png'))
for filename in filenames:
images.append(imageio.imread('img' + os.sep + filename))
imageio.mimsave('img' + os.sep + 'movie.gif', images, duration = 0.1)
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)
def main():
images_dir = '/Users/alan/Documents/research/nips2017/dcgan_w_results'
font_size = 30
images = []
font = ImageFont.truetype('/Library/Fonts/Arial.ttf', font_size)
for file_name in sorted(os.listdir(images_dir)):
if os.path.splitext(file_name)[-1] != '.png' or file_name == 'real_samples.png':
continue
image = Image.open(os.path.join(images_dir, file_name)).convert('RGBA')
text = 'Epoch '+str(int(file_name.split('_')[-1].split('.')[0]))
layer = Image.new('RGBA', image.size, (255, 255, 255, 0))
draw = ImageDraw.Draw(layer)
w, h = draw.textsize(text, font=font)
draw.text(((image.size[0]-w)//2, (image.size[1]-h)//2), text, font=font, fill=(255, 255, 255, 180))
image = Image.alpha_composite(image, layer)
images.append(image)
images = np.stack(images)
imageio.mimsave(os.path.join(images_dir, 'animation.gif'), images, duration=0.1)
def cmd_info(message, parameters, recursion=0):
await client.send_typing(message.channel)
async for msg in client.logs_from(message.channel, limit=25):
try:
if msg.attachments:
img = Image.open(BytesIO(requests.get(msg.attachments[0]['url']).content)).convert('RGB')
neg = ImageOps.invert(img)
neg.save("tmp/negative.png","PNG")
img.save("tmp/positive.png","PNG")
frames = [imageio.imread("tmp/negative.png"), imageio.imread("tmp/positive.png")]
imageio.mimsave("tmp/epilepsy.gif", frames, duration=0.07)
with open("tmp/epilepsy.gif", "rb") as outputGif:
await client.send_file(message.channel, outputGif, filename="epilepsy.gif")
os.system("rm tmp/epilepsy.gif tmp/negative.png tmp/positive.png")
return
except Exception as e:
e = discord.Embed(colour=0xB5434E)
e.description = "Error ocurred, 2 lazy to check what was it, try again later."
await client.send_message(message.channel, embed=e)
return
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
def upload_imgur(image):
try:
if image.file_path[::-1].split('.')[0][::-1] == "mp4":
mp4request = requests.get(image.file_path)
mp4 = BytesIO(mp4request.content)
gif = imageio.get_reader(mp4, 'ffmpeg')
fps = gif.get_meta_data()['fps']
frames = []
for i,im in enumerate(gif):
frames.append(im)
temp = BytesIO()
imageio.mimsave(temp, frames, format='GIF', fps=fps)
temp.seek(0)
elif image.file_path[::-1].split('.')[0][::-1] == "webp":
imgrequest = requests.get(image.file_path)
img = BytesIO(imgrequest.content)
image2 = Image.open(img)
temp = BytesIO()
image2.save(temp, 'png')
temp.seek(0)
client_id = botconfig.clientid_imgur
headers = {"Authorization": "Client-ID " + client_id}
api_key = botconfig.api_imgur
url = "https://api.imgur.com/3/upload.json"
rpost = requests.post(
url,
headers = headers,
data = {
'key': api_key,
'image': b64encode(temp.read()) if image.file_path[::-1].split('.')[0][::-1] == "mp4" or image.file_path[::-1].split('.')[0][::-1] == "webp" else image.file_path,
'type': 'base64' if image.file_path[::-1].split('.')[0][::-1] == "mp4" or image.file_path[::-1].split('.')[0][::-1] == "webp" else 'url',
'name': image.file_id,
'title': image.file_id + 'Upload by @imgurplusbot'
}
)
return json.loads(rpost.text)["data"]["link"] if rpost.status_code == 200 else "Error uploading image."
except:
return "Error uploading image."
def make_gif(self, save_path, speed=0.3):
if not save_path.endswith('.gif'):
save_path += '.gif'
images = []
for img in self._images:
image = PIL.Image.new('RGB', (self.width, self.height), 'white')
image.paste(img, box=(0,0))
images.append(numpy.asarray(image))
imageio.mimsave(save_path, images, duration=speed)
self.reset()
def triggered(cmd, message, args):
if message.mentions:
target = message.mentions[0]
else:
target = message.author
if not cmd.cooldown.on_cooldown(cmd, message):
cmd.cooldown.set_cooldown(cmd, message, 180)
avatar_url = user_avatar(target) + '?size=512'
wait_trig_response = discord.Embed(color=0xff6600, title='?? Triggering...')
resp_msg = await message.channel.send(embed=wait_trig_response)
async with aiohttp.ClientSession() as session:
async with session.get(avatar_url) as data:
avatar_data = await data.read()
avatar = Image.open(BytesIO(avatar_data))
avatar = avatar.resize((300, 300), Image.ANTIALIAS)
image_list = []
for x in range(0, 30):
base = Image.new('RGBA', (256, 320), (0, 0, 0, 0))
with Image.open(cmd.resource('trig_bot.png')) as trig_sign:
move_max = 22
move_x = random.randint(-move_max, move_max)
move_y = random.randint(-move_max, move_max)
base.paste(avatar, (-22 + move_x, -22 + move_y))
base.paste(trig_sign, (0, 256))
temp_loc = f'temp_gif_cache_{random.randint(99, 999999)}.png'
base.save(temp_loc)
image_list.append(imageio.imread(temp_loc))
os.remove(temp_loc)
out_loc = f'cache/triggered_{message.id}.gif'
imageio.mimsave(out_loc, image_list, fps=30)
dfile = discord.File(out_loc)
await message.channel.send(file=dfile)
try:
await resp_msg.delete()
except:
pass
os.remove(out_loc)
else:
cdembed = discord.Embed(color=0x696969, title=f'?? {target.name} has been put on ice to cool off.')
await message.channel.send(embed=cdembed)
def compile_frames_to_gif(frame_dir, gif_file):
frames = sorted(glob.glob(os.path.join(frame_dir, "*.png")))
images = [imageio.imread(f) for f in frames]
imageio.mimsave(gif_file, images, duration=0.1)
return gif_file
def draw(img):
width = img.size[0]
height = img.size[1]
imgs = []
filename = "imagesTest/movie_"+str(randint(1000000,9999999))+".gif"
val = randint(150,192)
colour=(val,int(val*7/8),int(val*5/6),255)
pen = (0,0,0,255)
# with imageio.get_writer(filename, mode='I') as writer:
P = []
V = []
delta = 2
for i in xrange(0,150):
P.append((randint(0,width-1),randint(0,height-1),randint(32,192)))
V.append((randint(-1,1)*randint(delta>1,delta),(randint(-1,1)*randint(delta>1,delta)),(randint(-1,1)*randint(delta>1,delta))))
P.append(P[0])
P.append(P[1])
V.append(V[0])
V.append(V[1])
for i in xrange(1,1200):
imgNew = img.copy() #Image.new("RGBA",size=(img.size[0],img.size[1]),color=colour)
# print(P)
testLineAnimation.draw(imgNew,P,pen)
# writer.append_data(imgNew)
imgs.append(array(imgNew.getdata()).reshape(imgNew.size[0], imgNew.size[1], 4))
Q = []
for j in xrange(0,len(P)):
(x,y,z) = P[j]
(vx,vy,vz) = V[j]
nx = vx+x
ny = vy+y
nz = vz+z
Q.append((nx,ny,nz))
P = Q
imageio.mimsave(filename, imgs)
def draw(img):
SAVEANIMATION = False # Make this True to create an animated file. Warning: large.
imgs=alife(img,randint(20,80))
filename = "imagesTest/ablife_"+str(randint(1000000,9999999))+".gif"
imgsNumpy = []
for image in imgs:
imgsNumpy.append(array(image.getdata()).reshape(image.size[0], image.size[1], 4))
if SAVEANIMATION == True:
imageio.mimsave(filename, imgsNumpy)
imageBlend(img,imgs[len(imgs)-1])
def create_gif(n_images, source_directory, output_name, duration):
images = []
for dp_i in range(n_images):
images.append(imageio.imread('%s/%06i.png' % (source_directory, dp_i) ) )
output_file = '%s.gif' % ( output_name)
imageio.mimsave(output_file, images, duration=duration)
def save_gif(filenames, filepath, duration):
images = []
for filename in filenames:
images.append(imageio.imread(filename))
kargs = { 'duration': duration }
imageio.mimsave(filepath, images, 'GIF', **kargs)
def create_gif(filenames, duration=DURATION):
images = []
for filename in filenames:
images.append(imageio.imread(filename))
imageio.mimsave(OUT_GIF, images, duration=duration)
def draw2DMovie(solution, t_filming_step, x_start, x_end, y_start, legend, solution_min_value, solution_max_value, t_grid_step):
#??????????, ?????????????? ????? ???? ?????(????? ??? ??????????)
time_marker_length = len(str(t_filming_step))
#!!!????? ?????????, ????? ?????? x ? ????? ?????? y ?? ????? ???????? ?????
x_slice_value = 3
y_slice_value = -1
y_end = 0
#???? ???????? ?? ?????, ??????? ???????? ?????? ? ???????? ????????? ??????:
#1: ????? ???? ???? ?? ???????
npArray = np.array(solution[0])
#2: ???? ?????? ?? ????
M = len(npArray)
x_step = (x_end - x_start) / M
x = np.arange(x_start,x_end,x_step)
x_slice_index = int((x_slice_value - x_start) / x_step) + 1
#3: ???? ?????? ?? ??????
M = len(npArray[0])
y_step = (0 - y_start) / M
y = np.arange(y_start,y_end,y_step)
y_slice_index = int((y_slice_value - y_start) / y_step) + 1
#??????? ?????, ???? ?? ?? ??????????
if not os.path.exists('img'):
os.makedirs('img')
#??????? ????? ?? ?????????? img\ ????? ????????? ????????.
files = glob.glob('img' + os.sep + '*')
for f in files:
os.remove(f)
#???? ???????????? ???, ??????, ?? ?????? ? ????, ??? ????? ???????? ???????? ??????? ???????????? ?? ?????.
#???????????? ????????????? ???? ?? ?????????? ? ?????.
#?????????? ?? ????? ????? ?????? ??? ????? ??????.
# absolute_solution_minimum = solution_min_value
# absolute_solution_maximum = solution_max_value
#???????? ????????? ?????? ?? ??????? ? ?????.
for i in range(0, solution.shape[0], t_filming_step):
#???? ???????????? ???, ?????? ?? ?????? ? ????????? ????. ???????????? ????????????? ???? ?? ?????????? ????? ????? ??????
#?????????? ?? ????? ????? ??????????? ???????? ??? ??????? ?????
absolute_solution_minimum = np.min(np.min(solution[i]))
absolute_solution_maximum = np.max(np.max(solution[i]))
draw2DSlice(solution[i], i * t_grid_step,
x_start, x_end, y_start, legend,
absolute_solution_minimum, absolute_solution_maximum,
time_marker_length)
#?????? ????? ?? ??????????? ????? img\, ????????? ?? ???? ??.
images = []
filenames = sorted(fn for fn in os.listdir(path='img' + os.sep) if fn.endswith('s.png'))
for filename in filenames:
tmp = imageio.imread('img' + os.sep + filename)
images.append(tmp)
imageio.mimsave('img' + os.sep + legend + ' movie.gif', images, duration = 0.2)