def repo_gif(repo, outfile, max_width=1920, max_height=1200, skip_empty=True): commits = deque([repo.head.commit]) while commits[0].parents: commits.appendleft(commits[0].parents[0]) file_images = {} for commit in commits: for f in commit.tree.traverse( lambda i, d: i.type == 'blob' and is_text(i.data_stream.read(1024)) ): file_images.setdefault( f.path, FileHistoryImages(f.path, skip_empty) ).add_commit_data( commit.hexsha, f ) images = list(file_images.values()) arranged = aspackt.arrangement(images) width = arranged.width height = arranged.height with open(outfile, 'wb') as fp: gifmaker.makedelta( fp, frames(commits, width, height, images, arranged) )
def make_gif(iter): import glob from PIL import Image, ImageChops import numpy from PIL.GifImagePlugin import getheader, getdata import gifmaker sequence = [] # fileList = glob.glob('../hko_fast/1900it6850outputn_*') fileList = [] path = '../hko_lstm_baseline_nopeep/' for i in range(15): name = path + 'trainImg/it' + str(iter) + 'outputn_' + str(i + 1) + '.png' fileList.append(name) print(fileList) for file in fileList: print(file) im = Image.open(file) img = numpy.asarray(im) print(img) sequence.append(im) name = path + str(iter) + "out.gif" fp = open(name, "wb") print('save as '+ name) gifmaker.makedelta(fp, sequence) fp.close()
def _output_movie(movie, filename): import Tkinter, gifmaker, os, sys from PIL import ImageTk frames = len(movie) if filename: #for Nr in range(frames): # fn = filename + str(Nr) + ".jpg" # movie[Nr].save(fn) #return for Nr in range(0, frames): movie[Nr] = movie[Nr].convert("P") if '.' in filename: (name, suffix) = os.path.splitext(filename) if suffix != '.gif': print "File format not supported. Defaulting to gif." filename = filename[:filename.index('.')] + ".gif" else: filename += ".gif" slash = '/' script = sys.argv[0] totalpath = os.path.abspath(script) userpath = os.path.dirname(totalpath) + slash + filename fp = open(userpath, "wb") gifmaker.makedelta(fp, movie) fp.close() print "Created", userpath else: root = Tkinter.Tk() # Close window procedure. stop = [0] def callback(): stop[0] = 1 root.protocol("WM_DELETE_WINDOW", callback) # Animate picture. canvas = Tkinter.Canvas(width=movie[0].size[0], height=movie[0].size[1]) while not stop[0]: for x in range(frames): if stop[0]: break backdrop = ImageTk.PhotoImage(movie[x]) canvas.create_image(0, 0, image=backdrop, anchor=Tkinter.NW) canvas.pack() root.update() root.after(int(100)) root.destroy()
def make_gif(time, iter): import glob from PIL import Image, ImageChops import numpy from PIL.GifImagePlugin import getheader, getdata import gifmaker sequence = [] # fileList = glob.glob('../hko_fast/1900it6850outputn_*') fileList = [] # iter = 24000 for i in range(15): name = '../hko_lstm_baseline/' + str(time) + 'it' + str(iter) + 'outputn_' + str(i + 1) + '.png' fileList.append(name) print(fileList) for file in fileList: print(file) im = Image.open(file) img = numpy.asarray(im) print(img) sequence.append(im) fp = open(str(iter) + "out.gif", "wb") gifmaker.makedelta(fp, sequence) fp.close()
def makeGif(inputdir, outfile, skip = 10, colorMode = "P", reverse=False): files = os.listdir(inputdir) files.sort(reverse=reverse) count = 0 seq = [] for fname in files: if skip > 1 and count % skip != 0: count+= 1 continue im = Image.open(inputdir+'/'+fname) im = im.convert(colorMode) # P or L seq.append(im) count+= 1 fp = open(outfile, "wb") gifmaker.makedelta(fp, seq) fp.close()
def _save(self, saveas="CAMFRPICTURE"): import tkFileDialog, tkMessageBox, os, gifmaker, Image, ImagePalette index = self.indexFlag.get() if (saveas == "CAMFRPICTURE"): ifile = "myplot.jpg" ftypes = [("picture", ".jpg"), ("picture", ".bmp"), ("picture", ".png")] ttle = "save plot" elif (saveas == "CAMFRRAWDATA"): ifile = "myplot.xls" ftypes = [("numeric tabbed", ".xls")] ttle = "save data" elif (saveas == "CAMFRGIFMOVIE"): ifile = "mymovie.gif" ftypes = [("movie", ".gif")] ttle = "save movie as gif" elif (saveas == "CAMFRFRAMESMOVIE"): ifile = "mymovie.jpg" ftypes = [("moviefiles", ".jpg"), ("moviefiles", ".bmp"), ("moviefiles", ".png")] ttle = "save movie as jpg files" # Get file name. name = tkFileDialog.asksaveasfilename(filetypes=ftypes, initialfile=ifile, title=ttle) (root, ext) = os.path.splitext(name) # Save options. if (saveas == "CAMFRPICTURE"): if not (ext in camfr_PIL.formats): ext = '.jpg' name = root + ext if not index: self.pic_f.save(name) else: camfr_PIL._overlay_pictures(self.pic_f, self.pic_n, 1).save(name) print "file saved as ", name elif (saveas == "CAMFRRAWDATA"): if not (ext in ['.xls', '.XLS']): ext = '.xls' name = root + ext self._saveMatrix(name, self.mat_f) print "file saved as", name elif (saveas == "CAMFRGIFMOVIE"): if not (ext in ['.gif', '.GIF']): ext = '.gif' name = root + ext # copy from playbutton self._movieNewPlay() movie2 = range(0, len(self.movie)) for Nr in range(0, len(self.movie)): if not index: movie2[Nr] = self.movie[Nr].convert("P") else: movie2[Nr] = camfr_PIL._overlay_pictures( self.movie[Nr], self.pic_n, 1).convert("P") fp = open(name, "wb") gifmaker.makedelta(fp, movie2) fp.close() print "file saved as", name elif (saveas == "CAMFRFRAMESMOVIE"): if not (ext in camfr_PIL.formats): ext = '.jpg' # this wil make a movie if nessecary self._movieNewPlay() for Nr in range(0, len(self.movie)): nameNR = root + "_%i" % Nr + ext if not index: self.movie[Nr].save(nameNR) else: camfr_PIL._overlay_pictures(self.movie[Nr], self.pic_n, 1).save(nameNR) print "file saved as %i " % len( self.movie), root, "_Nr", ext, " frames" else: tkMessageBox.showwarning(title="fail", message="no file/data is saved")
def main(): model = 0 if model == 0: filename = "data/knight.json" rotation_count = 0 elif model == 1: filename = "data/new_knight_baseclean_sym.json" rotation_count = 3 elif model == 2: filename = "data/DNA.json" rotation_count = 2 triangles = loadFile(filename) print "The model has %d triangles." % len(triangles) for i in range(rotation_count): # We need the model to be around Z. If it's around Y, transform the initial # geometry so that the rest of the program doesn't have to concern itself with it. triangles = [triangle.rotatex90() for triangle in triangles] # Single image. if True: img, _ = render(triangles, 1024, 1024, 0, None) # add_base(img) before = time.time() img.save("out.png") after = time.time() print "%dms" % ((after - before)*1000) sys.exit(0) # Animated GIF. if False: images = [render(triangles, IMAGE_SIZE, IMAGE_SIZE, angle)[0] for angle in angles(ANGLE_COUNT)] fp = open("out.gif", "wb") gifmaker.makedelta(fp, images) fp.close() # Single SVG. if False: image, _ = render(triangles, IMAGE_SIZE*RENDER_SCALE, IMAGE_SIZE*RENDER_SCALE, 0) paths = get_outlines(image) paths = [simplify_vertices(vertices, 1) for vertices in paths] generate_file("out", paths) # All SVGs. if True: bbox3d = BoundingBox3D() for triangle in triangles: bbox3d.addTriangle(triangle) center = bbox3d.center() # Move center to origin. triangles = [triangle - center for triangle in triangles] # Find scaling factor. size = bbox3d.size() max_size = max(size.x, size.y) scale = MODEL_DIAMETER / max_size * DPI # Light vector (to light). light = Vector3(-1, 1, 1).normalized() all_paths = [] # We write out the theta's in a deep link format. Once we have better file naming # we could provide a better name than "fromlink" which is only to distinguish it from # Default. thetas_file = open("thetas.txt", "w") thetas_file.write("lathser://sequence/add?name=fromlink") index = 0 for pass_number, shade_percent in enumerate(PASS_SHADES): print "------------------ Making pass %d (%d%%)" % (pass_number, shade_percent) for is_last, angle in identify_last(half_list(angles(ANGLE_COUNT))): # We append these into a deep link that can be fed into the app. thetas_file.write("&%g" % angle) if GENERATE_LIT_VERSION: image, _ = render(triangles, IMAGE_SIZE*RENDER_SCALE, IMAGE_SIZE*RENDER_SCALE, angle, light) image.save("out%02d-lit.png" % index) image, transform = render(triangles, IMAGE_SIZE*RENDER_SCALE, IMAGE_SIZE*RENDER_SCALE, angle, None) image.save("out%02d-render.png" % index) add_base(image) # Add the shade (for spiraling). The "transform" converts from # model units to raster coordinates. "scale" converts from # model units to dots. DPI converts from inches to dots. shade_width = int(ROD_DIAMETER*shade_percent/100.0*transform.scale/scale*DPI) shade_center_x = int(transform.offx) add_shade(image, shade_width, shade_center_x) image.save("out%02d-shade.png" % index) # Expand to take into account the kerf. kerf_radius = KERF_RADIUS_IN*transform.scale/scale*DPI if shade_percent != 0: # Rough cut, add some spacing so we don't char the wood. kerf_radius += ROUGH_EXTRA_IN*transform.scale/scale*DPI image = add_kerf(image, kerf_radius) # Cut off the sides when we're shading. if shade_percent > 0: clear_top(image, 2, RASTER_WHITE) image.save("out%02d-kerf.png" % index) paths = get_outlines(image) paths = [simplify_vertices(vertices, 1) for vertices in paths] paths = [transform_vertices(vertices, transform, scale) for vertices in paths] all_paths.extend(paths) all_paths.extend(make_heat_sensor()) all_paths.extend(make_time_waster(is_last)) index += 1 print generate_file("out", all_paths) thetas_file.close()
def make_movie(runid=None, num_movie=None, tz=1, ty=0, tx=0): """ make_montage(runid=None, num_movie=None, tz=1,ty=0,tx=0): This function looks in the current directory, assembles all the tif files prefixed by the runid provided (top.runid by default), and arranges them in a gif animation. <Needs More Work (to change fps, etc)> """ if runid is None: runid = arraytostr(top.runid) if tz: # ---- Reading z pictures ---- # -- Looking for biggest number of picture file name -- max_num = '00' for file in os.listdir(os.curdir): fname = file.split('.') try: if len(fname) == 3: if (fname[0] == runid) and (fname[2] == 'tif') and (fname[1][0] == 'z'): if (fname[1][1:] > max_num): max_num = fname[1][1:] except IndexError: continue print "maxnum: ", max_num # -- Making movie file name -- m_num = '00' if num_movie == None: for mfile in os.listdir(os.curdir): mfname = mfile.split('.') try: if len(mfname) == 4: if (mfname[0] == runid) and (mfname[3] == 'gif') and (mfname[2] == 'm'): if (mfname[1][1:] > m_num): m_num = mfname[1][1:] except IndexError: continue m_num = ` (int(m_num) + 1) ` # else: # m_num = `num_movie` if len(m_num) < 2: m_num = '0' + m_num filename = runid + '.' + 'z' + m_num + '.' + 'm' + ".gif" # -- Opening needed files in the directory and saving them in frames -- max_num = ` (int(max_num) + 1) ` sequence = [] for file in os.listdir(os.curdir): fname = file.split('.') try: if len(fname) == 3: if (fname[0] == runid) and (fname[2] == 'tif') and (fname[1][0] == 'z'): if (fname[1][1:] < max_num) and (fname[1][1:] > '0'): try: im = Image.open(file) sequence.append(im) except IOError: print "!!Wrong input output" except IndexError: continue #write GIF animation with open(filename, "wb") as fp: gifmaker.makedelta(fp, sequence) if ty: # ---- Reading y pictures ---- # -- Looking for biggest number of picture file name -- max_num = '00' for file in os.listdir(os.curdir): fname = file.split('.') try: if len(fname) == 3: if (fname[0] == runid) and (fname[2] == 'tif') and (fname[1][0] == 'y'): if (fname[1][1:] > max_num): max_num = fname[1][1:] except IndexError: continue print "maxnum: ", max_num # -- Making movie file name -- m_num = '00' if num_movie == None: for mfile in os.listdir(os.curdir): mfname = mfile.split('.') try: if len(mfname) == 4: if (mfname[0] == runid) and (mfname[3] == 'gif') and (mfname[2] == 'm'): if (mfname[1][1:] > m_num): m_num = mfname[1][1:] except IndexError: continue m_num = ` (int(m_num) + 1) ` # else: # m_num = `num_movie` if len(m_num) < 2: m_num = '0' + m_num filename = runid + '.' + 'y' + m_num + '.' + 'm' + ".gif" # -- Opening needed files in the directory and saving them in frames -- max_num = ` (int(max_num) + 1) ` sequence = [] for file in os.listdir(os.curdir): fname = file.split('.') try: if len(fname) == 3: if (fname[0] == runid) and (fname[2] == 'tif') and (fname[1][0] == 'y'): if (fname[1][1:] < max_num) and (fname[1][1:] > '0'): try: im = Image.open(file) sequence.append(im) except IOError: print "!!Wrong input output" except IndexError: continue #write GIF animation with open(filename, "wb") as fp: gifmaker.makedelta(fp, sequence) if tx: # ---- Reading x pictures ---- # -- Looking for biggest number of picture file name -- max_num = '00' for file in os.listdir(os.curdir): fname = file.split('.') try: if len(fname) == 3: if (fname[0] == runid) and (fname[2] == 'tif') and (fname[1][0] == 'x'): if (fname[1][1:] > max_num): max_num = fname[1][1:] except IndexError: continue print "maxnum: ", max_num # -- Making movie file name -- m_num = '00' if num_movie == None: for mfile in os.listdir(os.curdir): mfname = mfile.split('.') try: if len(mfname) == 4: if (mfname[0] == runid) and (mfname[3] == 'gif') and (mfname[2] == 'm'): if (mfname[1][1:] > m_num): m_num = mfname[1][1:] except IndexError: continue m_num = ` (int(m_num) + 1) ` # else: # m_num = `num_movie` if len(m_num) < 2: m_num = '0' + m_num filename = runid + '.' + 'x' + m_num + '.' + 'm' + ".gif" # -- Opening needed files in the directory and saving them in frames -- max_num = ` (int(max_num) + 1) ` sequence = [] for file in os.listdir(os.curdir): fname = file.split('.') try: if len(fname) == 3: if (fname[0] == runid) and (fname[2] == 'tif') and (fname[1][0] == 'x'): if (fname[1][1:] < max_num) and (fname[1][1:] > '0'): try: im = Image.open(file) sequence.append(im) except IOError: print "!!Wrong input output" except IndexError: continue #write GIF animation with open(filename, "wb") as fp: gifmaker.makedelta(fp, sequence)
from the source distribution of PIL. """ from PIL import Image from locale import format_string import glob import gifmaker if __name__ == "__main__": seq = [] # sequence of converted images num = -1 # counter of converted images minus 1 idir = "./pngs/" # input file directory odir = "./gifs/" # output file directory # Assemble sequence of converted images for ifile in glob.glob(idir + "*.png"): im = Image.open(ifile, "r") imc = im.convert('P') seq.append(imc) print "Loaded %s and converted from %s to %s" % \ (ifile, im.mode, imc.mode) num += 1 # Create compressed animated GIF file ofile = odir + "frames_0000_" + format_string("%04d", num) + ".gif" fp = open(ofile, "wb") gifmaker.makedelta(fp, seq) fp.close()
def to_animation(self, start_kwargs, end_kwargs, steps=10, delay=0.1, log_base=1.1): start_time = time() from gevent.threading import Lock from gifmaker import makedelta from io import BytesIO from PIL import Image kwargs = start_kwargs.copy() z_start = start_kwargs['zoom_factor'] z_end = end_kwargs['zoom_factor'] min_exp = 0 max_exp = 100 while log_base**(log_base*max_exp) > min(z_end, self.max_zoom): max_exp -= 1 while log_base**(log_base*min_exp) < z_start: min_exp += 1 min_exp -= 1 # we overshot zooms = np.logspace(log_base*min_exp, log_base*max_exp, steps, base=log_base, dtype=np.float64) # xcenters = np.linspace(start_kwargs['xcenter'], end_kwargs['xcenter'], steps, dtype=np.double) # ycenters = np.linspace(start_kwargs['ycenter'], end_kwargs['ycenter'], steps, dtype=np.double) x_min = min(start_kwargs['xcenter'], end_kwargs['xcenter']) x_max = max(start_kwargs['xcenter'], end_kwargs['xcenter']) if start_kwargs['xcenter'] > end_kwargs['xcenter']: x_dir = -1 else: x_dir = 1 xcenters = self.gen_exponential_space(x_min, x_max, steps, log_base)[::x_dir] y_min = min(start_kwargs['ycenter'], end_kwargs['ycenter']) y_max = max(start_kwargs['ycenter'], end_kwargs['ycenter']) if start_kwargs['ycenter'] > end_kwargs['ycenter']: y_dir = -1 else: y_dir = 1 ycenters = self.gen_exponential_space(y_min, y_max, steps, log_base)[::y_dir] # print('X', x_min, x_max, x_dir) # print(xcenters[0], xcenters[-1], '\n') # print('Y', y_min, y_max, y_dir) # print(ycenters[0], ycenters[-1], '\n') # print('Z', zooms[0], zooms[-1]) img_cnt = 0 threads = [] breakout_lock = Lock() def loop_breakout(count, x, y, z, **kw): kw['xcenter'] = x kw['ycenter'] = y kw['zoom_factor'] = z # start['zoom_factor']*(z**log_base) # print(x, y, z) with breakout_lock: raw_png = self.to_png(mode='.gif', **kw) img = Image.open(raw_png).convert(mode='L') # img.save('ani.%03d.gif' % (count,)) # raw_png.seek(0) return count, img for img_cnt, (x, y, z) in enumerate(zip(xcenters, ycenters, zooms)): thread = mock_thread(loop_breakout(img_cnt, x, y, z, **kwargs.copy())) # thread = gevent.spawn(loop_breakout, img_cnt, x, y, z, **kwargs.copy()) threads.append(thread) if not isinstance(threads[0], mock_thread): gevent.joinall(threads) buf = BytesIO() gifs = tuple(gif for _, gif in sorted(t.value for t in threads)) try: makedelta(buf, gifs) except: import traceback traceback.print_exc() buf.seek(0) print('took', time() - start_time, 'to animate') return buf