def make_gif(h5name,dielectric_bg = True,data_name = None,normalize = False): """makes a gif animation of the real part of the field in the file h5name. if dielectric_bg is a h5 name, will also plot the dielectric landscape. in case dielectric_bg = True will look for a file dielectric.h5 as well""" f = h5py.File(h5name) if data_name == None: data_name = f.keys()[-1] d = f[data_name] if normalize: d = d/abs(array(d).flatten()).max() if dielectric_bg == True: where = "./" + os.path.dirname(h5name) + "/dielectric.h5" if os.path.exists(where): dielectric_bg = where else: dielectric_bg = None if dielectric_bg != None: diel = h5py.File(dielectric_bg) diel_val = transpose(array(diel["eps"])) imdiel = diel_val diel.close() else: imdiel = transpose(ones(shape(d[:,:,0]))) #m = max(imdiel.flatten()) di = uint8(dstack((imdiel,imdiel,imdiel,imdiel))) images2gif.writeGif(h5name[:-3] + ".gif",[Image.fromarray(cm.jet(0.5+transpose(d[:,:,i]), bytes=True)*(di==1.0) + cm.gray(0.5+transpose(d[:,:,i]) , bytes=True)*(di!=1.0)) for i in range(shape(d)[-1])]) f.close()
def process(self, filepath): img = Image(filepath) # load the image into SimpleCV #~ img = img.edges() # Get the edges img.save(filepath) # save the temporary image self.imageset.append(img.getPIL()) writeGif(self.giffile, self.imageset, 0.2, 9999) return
def CrapImageIntoSlices(pImage, pColumns, pRows): try: sImage = Image.open(pImage) except: print 'Image Not Found!' return; mWidth = sImage.size[0] mHeight = sImage.size[1] sColumn = mWidth / pColumns sRow = mHeight / pRows mWidth = sColumn * pColumns mHeight = sRow * pRows for iWidth in range(0, mWidth, sColumn): for iHeight in range(0, mHeight, sRow): fName = os.path.join('output', 'tiled_%d_%d.png.'%(iWidth, iHeight)) print "Creating Image " + fName; print "Croping from (%d, %d) to (%d, %d)."%(iWidth, iHeight, min(iWidth + sColumn, mWidth), min(iHeight + sRow, mHeight)) mBuffer = Image.new("RGBA", [sColumn, sRow], (0, 0, 0, 0)) # mTile = sImage.crop((iWidth, iHeight, min(iHeight + sRow, mHeight), min(iWidth + sColumn, mWidth))) mTile = sImage.crop((iWidth, iHeight, min(iWidth + sColumn, mWidth), min(iHeight + sRow, mHeight))) mBuffer.paste(mTile, (0, 0)) mBuffer.save(fName, 'PNG') mImageFiles = sorted((fn for fn in os.listdir('output/') if fn.endswith('png'))) os.chdir('output/') mImages = [Image.open(fn) for fn in mImageFiles] writeGif('%s_result.gif'%(pImage.split('.')[0]), mImages, duration=0.2)
def make_gif_from_frames_with_yt(self,folder='../frames/', output='phi.gif'): # Create an animated gif of all the frames: images = [PIL_Image.open(framefile) for framefile in glob.glob(folder+'*.png')] writeGif(output, images, duration=0.2) return
def horizontal_gif(): for child_dir in os.listdir(sourceFilePath): for attr_file in os.listdir(sourceFilePath + child_dir + '\\'): if os.path.exists('./horizontal_gif/' + child_dir + '-' + attr_file + '.gif'): continue else: sourceFile = sourceFilePath + child_dir + '\\' + attr_file print(sourceFile) seismic_profile_num = 25 seismic_profile = get_all_incline_data(sourceFile, seismic_profile_num,direct='horizontal') images = [] for plane_no in range(len(seismic_profile)): im = Image.fromarray(seismic_profile[plane_no]) # scipy.misc.imsave('./images/img_'+str(plane_no)+'.png',im) if im.mode != 'RGB': im = im.convert('RGB') # im.save('./images/img_'+str(plane_no)+'.jpg') images.append(im) # for image in images: # plt.imshow(image,cmap=plt.cm.gray) # plt.show() # images = [Image.open(fn) for fn in os.listdir('./images/')] gif_name = './horizontal_gif/' + child_dir + '-' + attr_file + '.gif' writeGif(gif_name, images, duration=0.2)
def ascii_seq_to_gif(seq, output_path, fps=15.0, font_size=10): try: from images2gif import writeGif except ImportError as e: raise RuntimeError("Writing gifs requires images2gif library.\nTry 'pip install images2gif' %s" % e) 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)) status.update(index) status.complete() duration = 1.0/fps writeGif(output_path, images, duration)
def remove_multiple_frames(input_filename, output_filename): im = Image.open(input_filename) original_duration = im.info['duration'] images = [frame.copy() for frame in ImageSequence.Iterator(im)] frame_durations = [] unique_frames = [] image_index = 0 images_size = len(images) - 1 while image_index < images_size: current_frame = images[image_index] next_frame = images[image_index + 1] frame_repetition = 1 while compare_image(current_frame, next_frame) < 0.001: frame_repetition += 1 image_index += 1 if image_index >= images_size: break next_frame = images[image_index + 1] if image_index + 1 == images_size: frame_durations.append(frame_repetition) unique_frames.append(next_frame) unique_frames.append(current_frame) frame_durations.append(frame_repetition * original_duration / 1000.0) image_index += 1 print(unique_frames) print(frame_durations) assert len(unique_frames) == len(frame_durations) writeGif(output_filename, unique_frames, dither=0, subRectangles=False, nq=1, duration=frame_durations)
def animate3d(prefix, dir="images/", steps=36, transform=(10, 0, 0), **kwargs): import os import math import inspect from PIL import Image from images2gif import writeGif base_dir = os.path.join(dir, prefix) if not os.path.exists(base_dir): os.makedirs(base_dir) ax = plt.gca() digits = int(math.log10(steps-1))+1 files = [] for n in range(steps): if inspect.isfunction(transform): transform(ax) else: ax.azim += transform[0] ax.elev += transform[1] ax.dist += transform[2] filename = os.path.join(base_dir, 'img' + str(n).zfill(digits) + '.png') plt.savefig(filename, bbox_inches='tight') files.append(filename) images = [Image.open(file) for file in files] file_path_name = os.path.join(dir, prefix + '.gif') writeGif(file_path_name, images, **kwargs)
def gifme6(): frames = [create_frame(url) for url in fetch_radar_image_urls_last_6_hours()] gif_buffer = cStringIO.StringIO() writeGif(gif_buffer, frames, duration=0.001) response = make_response(gif_buffer.getvalue()) response.headers['Content-Type'] = 'image/gif' return response
def createGif(name, imageRefList, prefix="", suffix=""): # Create our reference list rlist = [] for eachString in imageRefList: if(find(eachString,".ds") >= 0 or find(eachString, ".DS") >= 0): continue rlist.append(prefix+eachString+suffix) pass # First: find dimensions of the images. avgHeightToWidth = 0.0 count = 0.0 imageList = [] for eachItem in rlist: imageList.append(Image.open(eachItem)) # add item to imageList. Useful for later. s = imageList[-1].size avgHeightToWidth += (float(s[1]) / float(s[0])) count += 1.0 pass avgHeightToWidth /= count # We will stretch all images to average dimensions finalDimensions = (300, int(300 * avgHeightToWidth)) finalImageList = [] for eachImage in imageList: finalImageList.append(eachImage.resize(finalDimensions, Image.ANTIALIAS)) pass # Now, create our gif. # silence the console save_stdout = sys.stdout sys.stdout = open('trash', 'w') images2gif.writeGif(filename=name+".gif", images=finalImageList, duration=2, repeat=True, dither=True) sys.stdout = save_stdout pass
def gifGen(folder, duration=0.3): os.chdir('/Users/harleyr/Documents/plots/' + folder) subdirs1 = cleanSubdirs(os.listdir('.')) for subdir1 in subdirs1: os.chdir(subdir1) subdirs = cleanSubdirs(os.listdir('.')) i = 0 for subdir in subdirs: file_names = sorted((fn for fn in cleanSubdirs(os.listdir(subdir)) if fn.endswith('.png'))) #['animationframa.png', 'animationframb.png', ...] " os.chdir(subdir) images = [Image.open(fn) for fn in file_names] size = (1920,1080) for im in images: im.thumbnail(size, Image.ANTIALIAS) filename = subdir + '.gif' writeGif(filename, images, duration=duration) os.chdir('../') i+= 1 print(str(i) + '/' + str(len(subdirs))) os.chdir('../')
def gen(dst): im = Image.new('RGB', (320, 200)) ims = [] font1 = loadfont(12) font2 = loadfont(16) fc = "#fff" ## initial frame num = random.randint(1, 2**30) pen = ImageDraw.Draw(im) pen.text((2, 2), "Logic Shift Right with Positive Number %d" % num, font=font1, fill=fc) drawBits(pen, genBits(num, 0, '0', 'red', 'green'), (6, 22), font1) pen.text((2, 52), "Arithmetic Shift Right with Positive Number %d" % num, font=font1, fill=fc) drawBits(pen, genBits(num, 0, '0', 'red', 'green'), (6, 72), font1) pen.text((2, 102), "Logic Shift Right with Negative Number %d" % -num, font=font1, fill=fc) drawBits(pen, genBits(-num, 0, '0', 'red', 'green'), (6, 122), font1) pen.text((2, 152), "Arithmetic Shift Right with Negative Number %d" % -num, font=font1, fill=fc) drawBits(pen, genBits(-num, 0, '1', 'red', 'green'), (6, 172), font1) ims.append(im.copy()) for idx in xrange(1, 16): drawBits(pen, genBits(num, idx, '0', 'red', 'green'), (6, 22), font1) drawBits(pen, genBits(num, idx, '0', 'red', 'green'), (6, 72), font1) drawBits(pen, genBits(num, idx, '0', 'red', 'green'), (6, 122), font1) drawBits(pen, genBits(num, idx, '1', 'red', 'green'), (6, 172), font1) ims.append(im.copy()) writeGif(dst, ims, duration=0.5, repeat=True, dither=0)
def make_gif(): """ creates gif image based on selected Instagram Images """ # get entered time time = float(request.form.get('time')) if time == "" and math.isnan(time): abort(404) # get array of images pics = request.form.getlist('pics[]') if not pics: abort(404) # prepare for processing file_names = [] for p in pics: file_names.append(cStringIO.StringIO(urllib.urlopen(p).read())) images = [Image.open(fn) for fn in file_names] # generate a random filename random_name = str(shortuuid.uuid()) filename = GIF_PATH + "%s.gif" % random_name #generate gif sequence writeGif(filename, images, duration=time) return random_name
def show_potential_from_all_angles_with_yt(self, output='phi.gif'): # Create 36 frames for the animated gif, one for each angle: steps = 36 angles = np.arange(steps) * np.pi / np.float(steps) / 2.0 + np.pi / 4 # current bug: the frames jump at pi/4, 3pi/4 etc.. # book-keeping: folder = 'frames/' os.system("rm -rf " + folder) os.system("mkdir -p " + folder) # Now create the individual frames: for k, angle in enumerate(angles): framefile = folder + str(k).zfill(3) print "Making frame", k, ": ", framefile, "at viewing angle", angle self.show_potential_with_yt(output=framefile, angle=angle, N_layer=6, alpha_norm=5.0, cmap='BrBG', Proj=0, Slice=0, gifmaking=1) # Create an animated gif of all the frames: images = [ PIL_Image.open(framefile) for framefile in glob.glob(folder + '*.png') ] writeGif(output, images, duration=0.2) return
def create_gif_file(): dir_list=os.listdir(PATH) for dir in dir_list: file_names = sorted( (fn for fn in os.listdir(PATH+dir) if fn.endswith('.png')) ) try: images = [Image.open(PATH+dir+"\\"+fn) for fn in file_names] except: print "Load image failed!" continue #draw_gif(images[0].filename,"Begin") #draw_gif(images[-1].filename,"End") size = (1000,1000) for im in images: try: im.thumbnail(size, Image.ANTIALIAS) except: images.pop(images.index(im)) filename = PATH+dir+"\\"+dir+".gif" try: writeGif(filename, images, duration=0.6) except: print "Write gif file failed!" traceback.print_exc() copy_gif_file()
def save(self): """ Apply a series of actions from a set of (action, arg) tuples, probably as parsed from a URL. Each action is a code into PROCESSORS. Then save the mogrified image. """ from settings import PROCESSORS filename = self.get_processed_filename() if not self.actions: if self.frames: new_frames = [frame for frame in self.frames] images2gif.writeGif(filename, new_frames) else: if self.im is None: return self.im.save(filename, quality=self.quality) for action, arg in self.actions: action = PROCESSORS[action] if self.frames: new_frames = [] for frame in self.frames: new_frames.append(action.process(frame, arg)) images2gif.writeGif(filename, new_frames) else: if self.im is None: return self.im = action.process(self.im, arg) self.im.save(filename, quality=self.quality)
def gif(): gifFiles=glob.glob(os.path.join(directory,'Classified','*.TIF')) images=[Image.open(file) for file in files] #Duration in writeGif is in seconds images2gif.writeGif(os.path.join('Classified','Classification.gif'),images,duration=1) print "Enjoy your GIF!" sys.exit()
def appendGif(): sequence = choice(sequences) sequence_str = ''.join(i for i in sequence) for i in sequence: i = ['y', 'b', 'g', 'r', 'p'].index(i) ok = Colors(500,100) ok.drawCells() im = ok.img.convert("P") images.append(im) ok = Colors(500,100) ok.drawCells() ok.drawCell(i, 'active') im = ok.img.convert("P") images.append(im) ok = Colors(500,100) ok.drawCells() im = ok.img.convert("P") images.append(im) writeGif(sequence_str+".gif", images, duration=0.5, repeat=False) system("convert %s -colors 9 %s" % (sequence_str+".gif", sequence_str+".gif")) with open(sequence_str+".gif", "rb") as image_file: encoded_string = base64.b64encode(image_file.read()) json_data = json.dumps({'gif' : encoded_string, 'sequence' : sequence_str}) print sequence_str
def solve(self): step = 0 while step < self.n: pos = self.find_next_legal(step) if pos is not None: self.result[step] = pos if self.draw: self.draw_queue(step) if step == self.n - 1: if self.draw: self.draw = False # only draw the picture for one solution from images2gif import writeGif writeGif("%s/all.gif" % self.pic_path, self.images, duration=0.2, repeat=False) yield self.result # start traceback if pos is None or step == self.n - 1: while 1: step -= 1 if step >= 0: pos = self.find_next_legal(step, True) if pos: self.result[step] = pos if self.draw: self.draw_queue(step, is_traceback=True) break else: # all the possibility have been examined return step += 1
def animated_gif(folder_with_images, gif_filename, loop_duration, size): """uses images2gif.py to turn all png images in a folder into an animated GIF""" os.chdir(folder_with_images) # changes directory to the folder with the images png_files = [] # get list of png files in folder for fn in os.listdir(folder_with_images): if fn.endswith('.png'): png_files.append(fn) sort_nicely(png_files) print(png_files) # number of png_files num_pngs = len(png_files) png_time = float(loop_duration)/ float(num_pngs) images = [Image.open(fn) for fn in png_files] dim = (size, size) # change sizes for the image file dimension #for im in images: # im.thumbnail(dim, Image.ANTIALIAS) output_file = os.path.join(folder_with_images, gif_filename) # path for output file writeGif(output_file, images, png_time) # writes out GIF
async def spoiler_create_image(message, attachments, tmp_path, error_message): img_url = attachments[0]["url"] height = attachments[0]["height"] width = attachments[0]["width"] name = attachments[0]["filename"] if height < 400: font_front = PIL.ImageFont.truetype(path_font, 25) message = split_spoiler_lines(message, 25) elif height < 700: font_front = PIL.ImageFont.truetype(path_font, 45) message = split_spoiler_lines(message, 45) elif height < 1400: font_front = PIL.ImageFont.truetype(path_font, 120) message = split_spoiler_lines(message, 63) else: font_front = PIL.ImageFont.truetype(path_font, 180) message = split_spoiler_lines(message, 80) start_text = text_replace(message) images = [] if ".png" in name: images = create_image(start_text, width, height, images, font_front, tmp_path, number=1, img=True, rgb="RGBA") else: images = create_image(start_text, width, height, images, font_front, tmp_path, number=1, img=True, rgb="RGB") with aiohttp.ClientSession() as sess: async with sess.get(img_url) as resp: if resp.status == 200: with open(f"{tmp_path}/{name}", 'wb') as f: f.write(await resp.read()) images.append(PIL.Image.open(f"{tmp_path}/{name}")) writeGif(f"{tmp_path}/animation.gif", images, repeat=False, duration=1) else: await private_msg(error_message, "Error cant load the picture. Pls wait and try it again.") return True
def spoiler_create(start_text, text, tmp_path): height = ceil(len(text) / 55) * 60 for i in range(text.count("\n")): height += 60 if height < 700: height += 120 width = 1100 font = PIL.ImageFont.truetype(path_font, 45) font_front = PIL.ImageFont.truetype(path_font, 45) start_text = split_spoiler_lines(start_text, 42) text = split_spoiler_lines(text, 45) elif height < 1400: height += 200 width = 2100 font = PIL.ImageFont.truetype(path_font, 65) font_front = PIL.ImageFont.truetype(path_font, 120) start_text = split_spoiler_lines(start_text, 41) text = split_spoiler_lines(text, 63) else: height += 360 width = 3600 font = PIL.ImageFont.truetype(path_font, 90) font_front = PIL.ImageFont.truetype(path_font, 180) start_text = split_spoiler_lines(start_text, 47) text = split_spoiler_lines(text, 80) images = [] text = text_replace(text) start_text = text_replace(start_text) images = create_image(start_text, width, height, images, font_front, tmp_path, number=1) images = create_image(text, width, height, images, font, tmp_path, number=2) writeGif(f"{tmp_path}/animation.gif", images, repeat=False, duration=1)
def lotsofMotion(self): #cap = cv2.VideoCapture('http://128.193.38.138/mjpg/video.mjpg') cap = cv2.VideoCapture('http://mu.webcam.oregonstate.edu') lol, img = cap.read() og = np.array(img) imglist = [] for ok in range(40): lol, img1 = cap.read() time.sleep(1) lol, img2 = cap.read() rgb = np.array(img1) rgb2 = np.array(img2) g = 0.2989 * rgb[:, :, 0] + 0.5870 * rgb[:, :, 1] + 0.1140 * rgb[:, :, 2] g2 = 0.2989 * rgb2[:, :, 0] + 0.5870 * rgb2[:, :, 1] + 0.1140 * rgb2[:, :, 2] blankimg = Image.new('1', (1280, 960)) dif = g - g2 print dif x, y = dif.shape for i in range(x): for j in range(y): if dif[i, j] < -30: blankimg.putpixel((j, i), 1) imglist.append(blankimg.convert(mode="RGB")) writeGif("result.gif", imglist, duration=0.1, dither=0)
def vertical_gif(): for child_dir in os.listdir(sourceFilePath): for attr_file in os.listdir(os.path.join(sourceFilePath,child_dir)): if not os.path.exists(os.path.join('./vertical_gif_line', child_dir)): # 生成文件夹 os.makedirs(os.path.join('./vertical_gif_line', child_dir)) gif_file_name = os.path.join('./vertical_gif_line/',child_dir,attr_file+'.gif') if os.path.exists(gif_file_name): print('文件:%s 已存在'%(attr_file+'.gif')) else: sourceFile = os.path.join(sourceFilePath,child_dir,attr_file) print(sourceFile) seismic_profile_num = 25 seismic_profile = get_all_incline_data(sourceFile,seismic_profile_num) images = [] for plane_no in range(len(seismic_profile)): im = Image.fromarray(seismic_profile[plane_no]) # scipy.misc.imsave('./images/img_'+str(plane_no)+'.png',im) if im.mode!='RGB': im = im.convert('RGB') #im.save('./images/img_'+str(plane_no)+'.jpg') images.append(im) #for image in images: # plt.imshow(image,cmap=plt.cm.gray) # plt.show() #images = [Image.open(fn) for fn in os.listdir('./images/')] writeGif(gif_file_name, images, duration=0.2)
def get_video_preview(video_cap, file_name="out.gif", img_count=15, duration=0.5): """ :param file_name: :param video_cap: cv2.VideoCapture :param img_count: int :param duration: float :return: """ image_list = list() frame_count = int(video_cap.get(cv2.CAP_PROP_FRAME_COUNT)) frame_delta = int(math.floor(frame_count / img_count)) img_index = range(0, frame_count, frame_delta) img_index = img_index[:img_count] for frame in img_index: video_cap.set(cv2.CAP_PROP_POS_FRAMES, frame) success, frame = video_cap.read() image_list.append(Image.fromarray(frame[:, :, [2, 1, 0]])) images2gif.writeGif(filename=file_name, images=image_list, duration=duration, repeat=True, subRectangles=False)
def transform(num_images, output_file, size, img_size): makedir(".images") create(num_images, size, img_size) images = [Image.open(fn) for fn in os.listdir(".")] os.chdir("..") writeGif(output_file, images, duration=0.1, loops=0, dither=0) shutil.rmtree(".images")
def animated_gif(folder_with_images, gif_filename, loop_duration, size): """uses images2gif.py to turn all png images in a folder into an animated GIF""" os.chdir( folder_with_images) # changes directory to the folder with the images png_files = [] # get list of png files in folder for fn in os.listdir(folder_with_images): if fn.endswith('.png'): png_files.append(fn) sort_nicely(png_files) print(png_files) # number of png_files num_pngs = len(png_files) png_time = float(loop_duration) / float(num_pngs) images = [Image.open(fn) for fn in png_files] dim = (size, size) # change sizes for the image file dimension #for im in images: # im.thumbnail(dim, Image.ANTIALIAS) output_file = os.path.join(folder_with_images, gif_filename) # path for output file writeGif(output_file, images, png_time) # writes out GIF
def plot_spiral(r,img,parray,loops=8, makeGif=False,background=0): theta = 0 imagelist = Image.fromarray(img.astype('uint8')) t = 0 maxInt = numpy.amax(parray) init_radius = r (x_limit,y_limit) = parray.shape count = 0 while theta<2*pi*loops: if count == 720: count = 0 if makeGif: add_photo(img,imagelist) theta += float(1)/(2*r) count = count + 1 for i in xrange(int(-t),int(t)+1): r = (init_radius)*theta + i x = x_limit/2 + int(r*cos(theta)) y = y_limit/2 + int(r*sin(theta)) if x >0 and x < x_limit and y > 0 and y<y_limit: if background == 1: img[x][y] = [0,0,0] new_thickness=maxInt-int(parray[x,y]) else: img[x][y] = [255,255,255] new_thickness=(parray[x,y]) if (new_thickness>t): t = t + .2; if (new_thickness<t): t = t - .2 print count if makeGif: writeGif("result.gif",imagelist,duration=0.02,dither=0)
def make_gif(self, image_paths, gif_path): """Simple utility method to combine a set of images into a gif.""" frames = [] for im in image_paths: frames.append(Image.open(im)) writeGif(gif_path, frames, duration=self.props["frame_duration"])
def update_map_images(): #Fetch a radar image of the Midwest from Intellicast and save it to disk. r = requests.get('http://services.intellicast.com/200904-01/158765827/Image/Radar/Radar2009.13L/Loop/SectorName/r03') #Load up the fetched file from the disk original_file = Image.open(StringIO(r.content)) original_file.load() #Set up zipcodes with a list for their image frames frame = 0 frames_dict = {} #Loop through the frames of the original images, cropping out frames for each region while True: try: original_file.seek(frame) for size, key_dict in settings.INTELLICAST_CROP_DICT.items(): for key, crop in key_dict.items(): frame_list = frames_dict.setdefault(key, []) frame_list.append(original_file.copy().crop(crop).resize(size)) frame = frame + 1 except EOFError: break #Write the new sets of frames to GIF files on the disk. for (zip_code, frame_list) in frames_dict.items(): writeGif( filename=settings.MEDIA_ROOT + '/intellicast/intellicast_animated_' + zip_code + '.gif', images=frame_list, duration=0.5, subRectangles=False )
def ascii_seq_to_gif(seq, output_path, fps=15.0, font_size=10): try: from images2gif import writeGif except ImportError as e: raise RuntimeError( "Writing gifs requires images2gif library.\nTry 'pip install images2gif' %s" % e) 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)) status.update(index) status.complete() duration = 1.0 / fps writeGif(output_path, images, duration)
def saveCurrentFile(self): try: writeGif(self.filename,self.frames, duration=0.3, dither=0) self.changed = False except Exception as e: print "Unable to save file error:" ,e.message raise e
def main(): dates = date_range(argv[1], argv[2]) print dates[0].ctime() print dates[-1].ctime() images = [np.asarray(stitch(date)) for date in dates] outfile = argv[3] images2gif.writeGif(outfile, images, duration=0.1)
def plaatje(): frames = read7Gif( "plaatjes/croppedgif.gif" ) i=0 for f in frames: f.save("gif/frame%i.png" % i) i+=1 gifs.writeGif( "gif/lel_new.gif", frames)
def stackem(stackarray, filename, gifit=False): """ stacks a series of np arrays in a stack Args: imgesize : a dictionary containing the number of rows, columns and bands in the image stackarray : a numpuy ndarray dontaining the data filename : the name of the file output, no path, no extension Returns: the stack in an nD array """ stack = np.zeros_like(stackarray.shape[0]) if SAVEALL: for i, f in enumerate(stackarray): print("\r working on image {0} of {1}".format(i+1,\ stackarray.shape[0]), end="") sys.stdout.flush() fig = pl.figure() pl.imshow(f, interpolation='nearest') pl.savefig('../outputs/stacks/'+filename+'_%03d.png'%i) pl.close(fig) # save the images of the stack in a movie if gifit: print("\nGIFfing...") writeGif('../outputs/stacks/' + \ filename + "_N%d"%stackarray.shape[0] + ".GIF", [Image.fromarray(np.uint8(np.array(f) / \ f.max() * 255)) for f in stackarray], duration = 0.01) stack = np.median(stackarray, axis = 0).astype(np.uint8) return stack
def generateGIF(file_names, size, uid): for fn in file_names: im = Image.open("./tmp_images/"+uid+"/"+fn) im = im.resize(size, Image.ANTIALIAS) im.save("./tmp_images/"+uid+"/"+fn, "JPEG") images = [Image.open("./tmp_images/"+uid+"/"+fn) for fn in file_names] writeGif("./tmp_images/"+uid+".gif", images, duration=0.5)
def build_gif(model): file_names = [] for fn in os.listdir('./images'): if fn.startswith(model) and fn.endswith('.png'): file_names.append(fn) images = [Image.open('./images/' + fn) for fn in file_names] writeGif('images/%s.gif' % model.replace('_', ''), images, duration=1.0)
def gen_gif(self): file_names = sorted((fn for fn in os.listdir(self.temp_dir) if fn.endswith('.png'))) print file_names images = [Image.open(os.path.join(self.temp_dir,fn)) for fn in file_names] filename = "blah.gif" writeGif(os.path.join(self.final_out_dir, filename), images, duration=1, dispose=2) shutil.rmtree(self.temp_dir) return self.create_gif_descriptor()
def save_anim_gif(self, img_data_array, filename, duration = 0.1): ''' this saves an animated gif given a list of img_data (numpy arrays) ''' images = [] for i in range(len(img_data_array)): images.append(self.to_image(img_data_array[i])) writeGif(filename, images, duration = duration)
def animate(self, outfilename, duration=1.0): images = list() for filename in glob(self.image_dir + "/*.png"): img = Image.open(filename) images.append(img) writeGif(outfilename, images, duration=duration, dither=0) for image in images: image.close()
def createGIF(): file_names = sorted( (x for x in os.listdir('./tempImages') if x.endswith('.png'))) images = [Image.open('./tempImages/' + fn) for fn in file_names] filename = "./tempImages/result.gif" writeGif(filename, images, duration=0.2)
def save_anim_gif(self, img_data_array, filename, duration=0.1): ''' this saves an animated gif given a list of img_data (numpy arrays) ''' images = [] for i in range(len(img_data_array)): images.append(self.to_image(img_data_array[i])) writeGif(filename, images, duration=duration)
def exe(self, gif_path, dest_index, save_first_frame=False): args_count = 0 frames_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'gif_test', 'frames') im_dst = cv2.imread(self.base_imgs[dest_index]) pts_dst = np.array( self.obtain_dimensions(self.base_imgs[dest_index], self.test_imgs[dest_index])) h, status = cv2.findHomography(pts_dst, pts_dst) im_out = cv2.warpPerspective(im_dst, h, (im_dst.shape[1], im_dst.shape[0])) if save_first_frame is True: cv2.imwrite( os.path.join(frames_dir, 'frame' + str(args_count) + '.png'), im_out) # Note: the images of base and test are aligned for merging using their respective indices in parallel for index in xrange(0, len(self.base_imgs)): args_count += 1 im_src = cv2.imread(self.test_imgs[index]) pts_src = np.array( self.obtain_dimensions(self.base_imgs[index], self.test_imgs[index])) h, status = cv2.findHomography(pts_src, pts_dst) im_out = cv2.warpPerspective(im_src, h, (im_dst.shape[1], im_dst.shape[0])) cv2.imwrite( os.path.join(frames_dir, 'frame' + str(args_count) + '.png'), im_out) print 'file args processed', args_count self.trim_imgs(frames_dir, 0.15) apply_names(frames_dir) file_names = sorted( (os.path.join(os.path.dirname(os.path.realpath(__file__)), 'gif_test', 'frames', fn) for fn in os.listdir(frames_dir) if fn.endswith('.png'))) print 'frames:' pprint(file_names) images = self.modularize_frames(file_names, omit_first_and_last=True) images2gif.writeGif(gif_path, images, duration=0.4) return
def make_gif(frames, save_path): for clip in frames.keys(): imgs = frames[clip] if len(imgs) > 110: continue sort_nicely(imgs) path = "{}{}.gif".format(save_path, clip) imgs = [Image.open(item) for item in imgs] writeGif(path, imgs)
def jpg2gif(filename): time = 1/len(filename) images = [Image.open(fn) for fn in filename] outname = 'result.gif' if images is None: print 'error' else : writeGif(outname, images, duration=time, subRectangles=False) print 'down'
def writeAnimatedGIF(self, filename): filename = filename + ".gif" images = [] for im in self.PA[1:]: im -= im.min() #set lowestvalue to 0 im *= 1 / im.max() #set highest value to 1 im = np.transpose(im) images.append(im) writeGif(filename, images, duration=0.2, repeat=True, dither=False)
def gen(self, seconds): pics = [] pics.append(self.draw()) for i in xrange(seconds * 24): for j in xrange(self.amount): self.get_next(j) pics.append(self.draw()) images2gif.writeGif('test.gif', pics, duration=1.0 / 24)
def build_gif(images, filename): files = [] for file in images: meh = Image.open(file) files.append(meh) # writeGIF is a function that creates GIF and is a part of images2gif library # print writeGif.__doc__ # Above print statement would give you details about the function in detail writeGif(filename, files, duration=0.2)
def to_gif(imlist, fname, indices, path): gifimages = [] for i in indices: gifimages.append(Image.open(path + imlist[i])) size = (600, 600) for im in gifimages: im.thumbnail(size, Image.ANTIALIAS) writeGif(path + fname, gifimages, duration=0.1, subRectangles=False) print 'wrote gif ', fname
def index(): ### Delete old images ### images = glob.glob("static/*.gif") for image in images: os.remove(image) ### Get images and station info ### img_num = 15 # How many frames for animation? station = request.args.get("station") # Get the radar station requested if not station: return render_template( "home.html" ) # Render a home page with form to enter a radar station id else: station = station.upper() # Make it uppercase fetch = GetImgs(station) # Initialize communication handler title, name = fetch.get_name() # Get station name if title == None: return render_template( "nostation.html", station=station) # If the station requested doesn't exist elif title == "short": return render_template( "tooshort.html" ) # If the station requested doesn't have 3 letters (they all have three letters) if not os.path.isfile( "static/Overlay_" + station + ".png"): # Does an overlay already exist for this station? overlay.make_overlay(station) fetch.get_imgs_srcs("radar", img_num) # Get urls for radar images fetch.get_imgs_srcs("warnings", img_num) # Get urls for warning overlay fetch.get_imgs() # Download images ### Make frames ### imgoverlay = Image.open("static/Overlay_" + station + ".png") frames = [] img_num += -1 # Renumber to prevent off-by-one error within loop (list indicies start at 0) for i in range(img_num, 0, -1): background = Image.open("static/Background.png") img = ("%02d" % i) # Image names start with 0 for all of them radar = Image.open("static/radar_" + img + ".gif") os.remove("static/radar_" + img + ".gif") radar = radar.convert("RGBA") # To prevent weird errors warnings = Image.open("static/warning_" + img + ".gif") os.remove("static/warning_" + img + ".gif") warnings = warnings.convert("RGBA") background.paste(radar, (0, 0), radar) background.paste(warnings, (0, 0), warnings) background.paste(imgoverlay, (0, 0), imgoverlay) background.convert("RGB").convert( "P", palette=Image.ADAPTIVE) # So it can be saved as a gif frames.append(background) ### Write animation, save, and render html page ### writeGif("static/animation_" + station + ".gif", frames, duration=0.225) return render_template("radar.html", title=title, name=name, station=station)
def buildGif(imgs, incrementsPerSec, imgName, effectName): mkdir("output") mkdir("output/" + imgName.split(".")[0]) smallimgs = [] for im in imgs: smallimgs.append(cv2.resize(im, (0, 0), fx=0.07, fy=0.07)) images2gif.writeGif("output/" + imgName.split(".")[0] + "/" + effectName + ".gif", imgs, duration=1 / incrementsPerSec)
def create_gif(images): duration = 0.1 * len(images) giffile = str(time()) + '.gif' frames = [] for frame in images: frames.append(Image.open(frame)) writeGif(giffile, frames, duration)
def makeAnimatedGif(path, filename): from images2gif import writeGif from PIL import Image # Recursively list image files and store them in a variable imgs = sorted(os.listdir(path)) images = [Image.open(os.path.join(path, i)) for i in imgs] writeGif(filename, images, duration=0.1) print os.path.realpath(filename) print "%s has been created" % filename
def doit(self): # remove any non-trackitem entries (ie transitions) if not self._currentSequence: return try: self._inFrame = self._currentSequence.inTime() self._outFrame = self._currentSequence.outTime() self._duration = self._outFrame - self._inFrame print 'Duration of In/Out is ' + str(self._duration) except: msgBox = PySide.QtGui.QMessageBox() msgBox.setText("Please set an In and Out point. (Frame Range is limited to 500 frames)") msgBox.exec_() return # Images for GIF... if hasattr(self._currentSequence,'thumbnail'): images = [] self.renderPreview.show() count = 1 for t in range(self._inFrame,self._outFrame): thumb = self._currentSequence.thumbnail(t) buffer = PySide.QtCore.QBuffer() buffer.open(PySide.QtCore.QIODevice.ReadWrite) thumb.save(buffer, "PNG") strio = cStringIO.StringIO() strio.write(buffer.data()) buffer.close() strio.seek(0) images += [Image.open(strio)] progress = int(100.0*(float(count)/float(self._duration))) hiero.core.log.debug('Progress is: '+ str(progress)) self.renderPreview.lbl.setPixmap(PySide.QtGui.QPixmap(thumb)) self.renderPreview.pbar.setValue(progress) QtCore.QCoreApplication.processEvents() count+=1 if not self.renderPreview.renderingEnabled: print 'Rendering Cancelled' self.renderPreview.hide() self.renderPreview.renderingEnabled = True return filename = "/tmp/my_gif.GIF" writeGif(filename, images, duration=0.2) self.renderPreview.hide() hiero.ui.revealInOSShell(filename)