class App(object): def __init__(self, update, fps=8): self.t = 0 self.period = 1000/fps self.update = update self.master = Tk() m = self.update(self.t) self.W, self.H = m3d.shape(m) self.img = PhotoImage(width=self.W, height=self.H) canvas = Canvas(self.master, width=self.W, height=self.H) canvas.pack() canvas.create_image((self.W/2, self.H/2), image=self.img, state="normal") self._on_tick() def _on_tick(self): def _formatcolor(c): return '#{0:02X}{1:02X}{2:02X}'.format(*c) m = self.update(self.t) self.img.blank() lines = [] for j in xrange(self.H): line = ' '.join(_formatcolor(m[j][i]) for i in xrange(self.W)) lines.append( '{' + line + '}') self.img.put(' '.join(lines)) self.master.after(self.period, self._on_tick) self.t += self.period def start(self): self.master.mainloop()
def box_filter(self): print "Box filter is used..." box_filter_pic = PhotoImage( width=self.width, height=self.height) # preserve dimensions of orig. img for v in range(0, self.height): for u in range(0, self.width): summe = [0, 0, 0] # create a filter region for every pixel for j in range(-1, 2): # move filter for i in range(-1, 2): if 0 <= u + i < self.width: if 0 <= v + j < self.height: pixel = map( int, self.pixel_matrix[u + i][v + j].split()) summe = [ sum([x, y]) for x, y in zip(pixel, summe) ] else: pixel = map(int, self.pixel_matrix[u][ v - 1].split()) # fill edge pixel summe = [ sum([x, y]) for x, y in zip(pixel, summe) ] else: pixel = map(int, self.pixel_matrix[u - 1] [v].split()) # fill edge pixel summe = [sum([x, y]) for x, y in zip(pixel, summe)] r, g, b = [x / 9.0 for x in summe] box_filter_pic.put("#%02x%02x%02x" % (int(r), int(g), int(b)), (u, v)) print "Done!\n" return box_filter_pic
def main(): master = Tk() w = Canvas(master, width=WIDTH, height=HEIGHT) w.pack() img = PhotoImage(width=WIDTH, height=HEIGHT, master=master) w.create_image((WIDTH/2, HEIGHT/2), image=img, state="normal") cam = Camera() cam.look_at(np.array([0, 10, -8]), np.array([0, 0, 3.0]), np.array([0, 1.0, 0])) init_world(world_objects) init_light(light_objects) # Generate rays for each pixel and determine color progress_interval = HEIGHT*WIDTH / 10 progress_tick = 0 print 'Progress (10 ticks): [ -', sys.stdout.flush() for y in xrange(HEIGHT): for x in xrange(WIDTH): progress_tick += 1 if progress_tick > progress_interval: progress_tick = 0 print ' -', sys.stdout.flush() ray = compute_camera_ray(WIDTH, HEIGHT, cam, 3, x, y) color = trace_ray(world_objects, light_objects, ray) # TKinter requires a hex string as color input for photo image img.put('#%02X%02X%02X' % tuple(color), (x, y)) print ' ]' mainloop()
def display(): window = Tk() canvas = Canvas(window, width=WIDTH, height=HEIGHT, bg="#000000") canvas.pack() img = PhotoImage(width=WIDTH, height=HEIGHT) canvas.create_image((WIDTH/2, HEIGHT/2), image=img, state="normal") data = "" for i in range(HEIGHT): data += '{' + ' '.join(map( convert_color, memory_dump(i*WIDTH, i*WIDTH + WIDTH) )) + '} ' img.put(data[:-1]) mainloop()
def render_2d(header, blocks): from Tkinter import Tk, Label, mainloop, PhotoImage # Create a random color map from the set of blocks values colors = {} for unique_item in set(chain.from_iterable(blocks)): if unique_item == 0: colors[0] = (0, 0, 0) else: colors[unique_item] = (randrange(128), randrange(128), randrange(128)) master = Tk() # Build image photo = PhotoImage(width=header["z"], height=header["y"]) #{#ff0000 #ff0000 #ff0000} {#ff0000 #ff0000 #ff0000} {#ff0000 #ff0000 #ff0000} {#ff0000 #ff0000 #ff0000} horizontal_line = " ".join(["{" + " ".join(["#%02x%02x%02x" % tuple(colors[blockId]) for blockId in row]) + "}" for row in blocks]) photo.put(horizontal_line) photo = photo.zoom(4, 4) label = Label(master, image=photo) label.pack() mainloop()
def Plot(shape, iterations): global base if iterations != -1: color = iterations * base - 1 #color = abs(math.ceil(255*math.sin(iterations1))) drawColor = color_rgb(color, color, color) else: drawColor = color_rgb(0, 0, 0) shape.setFill(drawColor) shape.setOutline(drawColor) shape.draw(win) return img = PhotoImage(width=x, height=y) canvas.create_image((0, 0), image=img, state="normal", anchor=NW) pixels = " ".join(("{" + " ".join(('#%02x%02x%02x' % iterations for i in xm)) + "}" for j in ym)) img.put(pixels)
def median_filter(self): print "Median filter is used..." medianpic = PhotoImage(width=self.width, height=self.height) for v in range(0, self.height): for u in range(0, self.width): filter_region = [] for j in range(-1, 2): for i in range(-1, 2): if 0 <= u + i < self.width: if 0 <= v + j < self.height: filter_region.append( self.pixel_matrix[u + i][v + j]) else: filter_region.append(self.pixel_matrix[u][v - 1]) else: filter_region.append(self.pixel_matrix[u - 1][v]) filter_region.sort() r, g, b = filter_region[4].split() medianpic.put("#%02x%02x%02x" % (int(r), int(g), int(b)), (u, v)) print "Done!\n" return medianpic
import random import threading import time WIDTH, HEIGHT = 640, 480 window = Tk() canvas = Canvas(window, width=WIDTH, height=HEIGHT, bg="#000000") canvas.pack() img = PhotoImage(width=WIDTH, height=HEIGHT) canvas.create_image((WIDTH / 2, HEIGHT / 2), image=img, state="normal") a = (120, 120) b = (576, 240) c = (455, 444) array = [a, b, c] img.put("#ffffff", a) img.put("#ffffff", b) img.put("#ffffff", c) start = (300, 300) img.put("#ffffff", start) def play(): global start while True: choice = random.choice(array) mid_point = ((start[0] + choice[0]) / 2, (start[1] + choice[1]) / 2) img.put("#ffffff", mid_point) start = mid_point time.sleep(0.05)
def main(): ImageFile.MAXBLOCK = 4096*2304 # this is only required for older PIL versions, if PILs output buffer is not large enough. see: https://mail.python.org/pipermail/image-sig/1999-August/000816.html parser = argparse.ArgumentParser(description='Simple Raytracer by Tilman Ginzel') parser.add_argument('-r', '--recursive', help='sets recursive depth, e.g. -r 3 (required)', nargs=1, type=checkPositiveInt, required=True, metavar='') parser.add_argument('-s', '--size', help='sets the size, e.g. -s 400 400', nargs=2, default=[400, 400], type=checkPositiveInt, required=False, metavar='') parser.add_argument('-v', '--verbose', help='enable live visualization while processing (slower)', required=False, action='store_true') parser.add_argument('-m', '--material', help='enable materials', required=False, action='store_true') parser.add_argument('-a', '--antialiasing', help='enables 4xSSAA (hence, 4 times slower)', required=False, action='store_true') parser.add_argument('-o', '--output', help='saves image to "./saves/"', required=False, action='store_true') parser.add_argument('-set', '--setting', help='choose a setting. -set 1 - 3', required=False, nargs=1, default=[1], type=int, metavar='') parser.add_argument('-nd', '--no-display', help='this should only be set if the script runs on a server without a $DISPLAY environment variable set!', required=False, action='store_true') try: args = vars(parser.parse_args()) except: parser.print_help() sys.exit(1) settingId = args['setting'][0] if settingId == 1: # default setting setting = DefaultSetting(width=args['size'][0], height=args['size'][1], recursiveDepth=args['recursive'][0], showMaterial=args['material']) elif settingId == 2: # space setting setting = SpaceSetting(width=args['size'][0], height=args['size'][1], recursiveDepth=args['recursive'][0], showMaterial=args['material']) elif settingId == 3: # room setting setting = RoomSetting(width=args['size'][0], height=args['size'][1], recursiveDepth=args['recursive'][0], showMaterial=args['material']) else: # default setting setting = DefaultSetting(width=args['size'][0], height=args['size'][1], recursiveDepth=args['recursive'][0], showMaterial=args['material']) # display is used to set whether you want to have a visual feedback in a graphical user interface. display = not args['no_display'] # easier to read and you do not have to negotiate it on every call if display: window = Tk() window._root().wm_title('Raytracer - Tilman Ginzel (173388)') if args['verbose']: can = Canvas(window, width=setting.WIDTH, height=setting.HEIGHT) else: frame = Frame(window, width=setting.WIDTH, height=setting.HEIGHT) can = Canvas(frame, width=setting.WIDTH, height=setting.HEIGHT) frame = Frame(window) can.pack() # photoImage is used to show live changes while processing if args['verbose']: photoImage = PhotoImage(width=setting.WIDTH, height=setting.HEIGHT) can.create_image((setting.WIDTH/2, setting.HEIGHT/2), image=photoImage, state="normal") # pilImage is used to save the image after processing or if verbose is deactivated pilImage = Image.new("RGB", (setting.WIDTH, setting.HEIGHT), (0, 0, 0)) start = time.clock() processor = Processor(setting, display=display, ssaa=args['antialiasing']) print 'start processing...' for pixel in processor.startProcessing(): if display and args['verbose']: photoImage.put("#%02x%02x%02x" %((pixel[1][0], pixel[1][1], pixel[1][2])), (pixel[0][0], pixel[0][1])) if pixel[0][1] == setting.HEIGHT-1: # if y == bottom, update canvas can.update() pilImage.putpixel((pixel[0][0], pixel[0][1]), ((pixel[1][0], pixel[1][1], pixel[1][2]))) end = time.clock() print 'done' print 'duration: %2.2f seconds' %(end-start) if display and not args['verbose']: tkImage = ImageTk.PhotoImage(pilImage) label = Label(image=tkImage) label.image = tkImage label.pack() can.pack() if args['output']: saveImage(pilImage, args) if display: window.mainloop()
class InputLogger(): #TODO: implement bedder synch because events start missing after some time lock = threading.Lock() f = open("log.txt",'w') window = Tk() hm = pyHook.HookManager() #TODO check for secondary display def __init__(self): #global ginlogger #ginlogger = self # Get real screen dimension # TODO: check for secondary display or just expand with mouse range self.OnEvent = self.callbackOnEvent() screen_width = self.window.winfo_screenwidth() screen_height = self.window.winfo_screenheight() self.WIDTH, self.HEIGHT = screen_width, screen_height self.minx = 0 self.miny = 0 self.maxx = self.WIDTH self.maxy = self.HEIGHT # make image for drawing self.canvas = Canvas(self.window, width=self.WIDTH, height=self.HEIGHT, bg="#000000") self.canvas.pack() self.img = PhotoImage(width=self.WIDTH, height=self.HEIGHT) self.canvas.create_image((self.WIDTH/2, self.HEIGHT/2), image=self.img, state="normal") # save state self.lastevent = [] self.xl = [] self.yl = [] self.cl = [] # setup hooks self.hm.KeyDown = self.OnEvent self.hm.MouseAll = self.OnEvent self.hm.HookKeyboard() self.hm.HookMouse() # this is the event callback for the windows pyhook def callbackOnEvent(self): self.n = 0 def OnEvent(event): self.lastevent t1 = int(round(time.time()*1000)) #log only new entries to file currentevent = [i for i in event.__dict__.items() if "__" not in i[0]] # convert class to list of attributes-names and values onlynew = [i for i in currentevent if i not in self.lastevent] # only print changed attributes print t1, currentevent# onlynew self.f.write(str(t1)+ str(currentevent)+"\n") self.lastevent = currentevent # save position in instance if 'Position' in [k for k,v in currentevent]: #self.lock.acquire() self.xl.append(event.Position[0]) self.yl.append(event.Position[1]) self.cl.append(self.n) self.n+=1 #print self.xl[-1] , self.yl[-1] #self.lock.release() return True return OnEvent def loop(self): # TODO: split logging and display tasks !!!!!!!! updatetime = time.time() updatetimefile = time.time() while 1: pythoncom.PumpWaitingMessages() if len(self.xl): #self.img.blank() self.img.put("#ff0000", (self.WIDTH/2, self.HEIGHT/2)) commonlen = zip(self.xl,self.yl,self.cl) for x,y,c in commonlen: self.img.put("#ffffff", (abs(x),abs(y))) # find extrema for x and y if x < self.minx: self.minx = x elif x > self.maxx: self.maxx = x if y < self.miny: self.miny = y elif y > self.maxy: self.maxy = y #print c, x, y # "del positions" #self.lock.acquire() del self.xl[:len(commonlen)] del self.yl[:len(commonlen)] del self.cl[:len(commonlen)] #self.lock.release() if time.time() > updatetime: self.window.update() updatetime = time.time() + 1/60.
def pixelSolverTester(dut): dut.log.info("Cocotb test boot") speedBench = True # Create Agents cocotb.fork(ClockDomainAsyncReset(dut.clk, dut.reset)) cocotb.fork(simulationSpeedPrinter(dut.clk)) cycleCounter = [0] cocotb.fork(cycleCounterAgent(dut, cycleCounter)) cmdThread = cocotb.fork(cmdAgent(dut, 1.0 if speedBench else 0.5)) resultArray = [[0 for x in xrange(resX)] for y in xrange(resY)] rspThread = cocotb.fork( rspAgent(dut, resultArray, 1.0 if speedBench else 0.5)) # Wait everybody finish its job yield cmdThread.join() yield rspThread.join() # Flush the mandelbrot into a text file uutString = reduce(lambda a, b: a + "\n" + b, [str(e) for e in resultArray]) uutFile = open('mandelbrot.uut', 'w') uutFile.write(uutString) uutFile.flush() uutFile.close() # Count how many iteration were done iterationCount = 0 for y in xrange(resY): for x in xrange(resX): iterationCount += resultArray[y][x] + 1 print("Done in %d cycles => %f iteration/cycle" % (cycleCounter[0], 1.0 * iterationCount / cycleCounter[0])) # Display the mandelbrot picture in a GUI from Tkinter import Tk, Canvas, PhotoImage zoomFactor = 4 pictureWidth, pictureHeight = resX * zoomFactor, resY * zoomFactor window = Tk() canvas = Canvas(window, width=pictureWidth, height=pictureHeight, bg="#000000") canvas.pack() img = PhotoImage(width=pictureWidth, height=pictureHeight) canvas.create_image((pictureWidth / 2, pictureHeight / 2), image=img, state="normal") for y in xrange(resY): for x in xrange(resX): r, g, b = 0, 0, 0 r = resultArray[y][x] << 4 for zy in xrange(zoomFactor): for zx in xrange(zoomFactor): img.put("#%02x%02x%02x" % (r, g, b), (x * zoomFactor + zx, y * zoomFactor + zy)) window.mainloop() # Check differences with the reference image refFile = open('mandelbrot.ref', 'r') refString = refFile.read() if refString != uutString: raise TestFailure( "FAIL because of picture missmatch, see mandelbrot.ref vs mandelbrot.uut" )
class Window(Frame): RENDER_PROCESSES = 2 def __init__(self, width, height, scene, tracer, calculate=None): Frame.__init__(self, master=None) if calculate is None: calculate = [0, 0] self.d = calculate self.scene = scene self.after_id = 0 self.tracer = tracer self.width = width self.height = height self.__init_window(height, width) self.master.mainloop() def __init_window(self, height, width): self.master.title = "Ray Py" canvas = Canvas(self.master, width=width, height=height) canvas.pack(side=TOP) self.img = PhotoImage(width=width, height=height) canvas.create_image((width / 2, height / 2), image=self.img, state="normal") self.startButton = Button(self.master, text="Render", command=lambda: self.__onStartPressed()) self.startButton.pack(side=RIGHT) self.resetButton = Button(self.master, text="Reset", command=lambda: self.__onResetPressed()) self.resetButton.config(state="disabled") self.resetButton.pack(side=RIGHT) self.listbox = Listbox(self.master, height=5) self.listbox.bind('<<ListboxSelect>>', self.__selectTracer) self.listbox.insert(END, "Simple", "Shadow", "ShadingShadow", "Recursive", "PathTracer") self.listbox.pack(side=LEFT) self.listbox.selection_set(0) self.listbox.activate(0) self.listbox.focus_set() def __selectTracer(self, evt): value = self.listbox.get(self.listbox.curselection()) if value == "Simple": self.tracer = SimpleRayTracer() elif value == "Shadow": self.tracer = SimpleShadowRayTracer() elif value == "ShadingShadow": self.tracer = ShadingShadowRayTracer(self.scene.eye) elif value == "Recursive": self.tracer = RecursiveRayTracer(self.scene.eye) elif value == "PathTracer": self.tracer = PathTracer(self.scene.eye) def __onStartPressed(self): self.startButton.config(state="disabled") self.listbox.config(state="disabled") self.__draw() def __update(self): if self.finishedQueue.qsize() >= self.RENDER_PROCESSES: self.finishedThreads = self.RENDER_PROCESSES while not self.finishedQueue.empty(): self.finishedQueue.get() if not self.dataQueue.empty(): item = self.dataQueue.get() self.img.put(item[1], item[0]) self.master.update() elif self.finishedThreads == self.RENDER_PROCESSES: for t in self.threads: t.join() self.master.after_cancel(self.after_id) self.resetButton.config(state="active") return self.after_id = self.master.after(0, self.__update) def __draw(self): from processes import BlockProcess from multiprocessing import Queue self.finishedQueue = Queue() self.dataQueue = Queue() self.finishedThreads = 0 self.threads = BlockProcess.forCount(self.RENDER_PROCESSES, self.width, self.height, self.tracer, self.scene, self.dataQueue, self.finishedQueue) for t in self.threads: t.start() self.__update() self.after_id = self.master.after(0, self.__update) def __onResetPressed(self): self.img.blank() self.d = [0, 0] self.resetButton.config(state="disabled") self.startButton.config(state="active") self.listbox.config(state="normal")
def paintTest(): global canvas master = Tk() canvas_width = win_max_x canvas_height = win_max_y canvas = Canvas(master, width=win_max_x, height=win_max_y) canvas.pack() y = int(win_max_y / 2) #w.create_line(0, y, win_max_x, y, fill="#476042") img = PhotoImage(master=master, width=win_max_x, height=win_max_y) #img = w.create_image(0,0, state="normal") canvas.bind("<Button-1>", click) mainloop() return for x in range(0, win_max_x): for y in range(0, win_max_y): color = 128 + int(64 * sin(x * y / 16.0)) drawColor = color_rgb(255, color, color) img.put(drawColor, (x, y)) w.create_image((win_max_x / 2, win_max_y / 2), image=img, state="normal") #w.create_image((win_max_x/2, win_max_y/2), image=img, state="normal") mainloop() return WIDTH, HEIGHT = 640, 480 window = Tk() canvas = Canvas(window, width=WIDTH, height=HEIGHT, bg="#000000") canvas.pack() img = PhotoImage(width=WIDTH, height=HEIGHT) canvas.add #canvas.create_image((WIDTH/2, HEIGHT/2), image=img, state="normal") for x in range(4 * WIDTH): y = int(HEIGHT / 2 + HEIGHT / 4 * sin(x / 80.0)) img.put("#ffffff", (x // 4, y)) #win.getMouse() return img = Image.New('RGB', (255, 255), "black") # create a new black image pixels = img.load() # create the pixel map for i in range(img.size[0]): # for every pixel: for j in range(img.size[1]): pixels[i, j] = (i, j, 100) # set the colour accordingly img.show() return master = Tk() canvas = Canvas(master, width=win_max_x, height=win_max_y) canvas.pack() #img = PhotoImage(file="myimage.jpg") #canvas.create_image(20,20, anchor=NW, image=img) return #pixels = " ".join('#%02x%02x%02x') img = Image.new('RGB', (255, 255), "black") # create a new black image pixels = img.load() # create the pixel map for i in range(img.size[0]): # for every pixel: for j in range(img.size[1]): pixels[i, j] = (i, j, 100) # set the colour accordingly #img.Show(win) myImage = graphics.Image(pixels) myImage.draw(window)
from Tkinter import Tk, Canvas, PhotoImage, mainloop from math import sin WIDTH, HEIGHT = 640, 480 window = Tk() canvas = Canvas(window, width=WIDTH, height=HEIGHT, bg="#000000") canvas.pack() img = PhotoImage(width=WIDTH, height=HEIGHT) canvas.create_image((WIDTH / 2, HEIGHT / 2), image=img, state="normal") for x in range(4 * WIDTH): y = int(HEIGHT / 2 + HEIGHT / 4 * sin(x / 80.0)) img.put("#ffffff", (x // 4, y)) mainloop()
class rayCaster(object): def __init__(self): self.root = Tk() self.root.title("Ray Tracer") canvas = Canvas(self.root, width=WIN_SIZE, height=WIN_SIZE) self.image = PhotoImage(master=self.root, width=WIN_SIZE, height=WIN_SIZE) imageCentre = (WIN_SIZE / 2 + 2, WIN_SIZE / 2 + 2) canvas.create_image(imageCentre, image=self.image) canvas.pack() # Enqueue a callback to the ray tracer to start it going self.root.after(0, lambda: self.trace()) return def putImageRow(self, row, colours): """Output a list of colours to the specified row of the image. Tk uses horrible hexadecimal formatted colours, packed into a string separated by spaces and all enclosed in braces." """ hexColours = ["#%02x%02x%02x" % colour for colour in colours] rowColourString = "{" + " ".join(hexColours) + "}" self.image.put(rowColourString, to=(0, row)) self.root.update() # Main body. Set up an image then compute colour at each pixel def trace(self): camera = definition.camera camera.img = Image.new("RGB", (camera.size, camera.size)) print "ScottTracer" print "\tTracing Rays... 0%", sys.stdout.flush() count = 0 t0 = time.clock() max = float(WIN_SIZE**2) lastPercentage = 0 for row in range(WIN_SIZE): ROW = [] for col in range(WIN_SIZE): count += 1 pixel = camera.pixelColour(col, row) camera.img.putpixel((col, row), pixel.intColour()) ROW.append(pixel.intColour()) percentage = (count / max * 100) self.putImageRow(row, ROW) if percentage - lastPercentage > .9: print "\b\b\b\b\b\b%4.0f%%" % percentage, sys.stdout.flush() lastPercentage = percentage print "\b\b\b\b\b\b Done (%f sec)" % (time.clock() - t0) print "\tAnti-alasing... 0%", sys.stdout.flush() t0 = time.clock() count = 0 lastPercentage = 0 for row in range(WIN_SIZE): ROW = [] self.putImageRow(row, [(255, 255, 255)] * WIN_SIZE) for col in range(WIN_SIZE): count += 1 pixel = camera.aa(col, row) camera.img.putpixel((col, row), pixel) ROW.append(pixel) percentage = (count / max * 100) self.putImageRow(row, ROW) if percentage - lastPercentage > .9: print "\b\b\b\b\b\b%4.0f%%" % percentage, sys.stdout.flush() lastPercentage = percentage print "\b\b\b\b\b\b (%f sec)" % (time.clock() - t0) print camera.pixels camera.img.save( sys.argv[1] + ".png") # Display image in default image-viewer application
def sharpen_filter(self): print "Sharpen filter is used..." sharp_pic = PhotoImage(width=self.width, height=self.height) filter_region = [[0, -1, 0], [-1, 5, -1], [0, -1, 0]] for v in range(0, self.height): for u in range(0, self.width): summe_Rp = [0, 0, 0] summe_Rm = [0, 0, 0] for j in range(-1, 2): for i in range(-1, 2): filter_co = filter_region[j + 1][i + 1] if 0 <= u + i < self.width: if 0 <= v + j < self.height: pixel = map( int, self.pixel_matrix[u + i][v + j].split()) if filter_co > 0: help = [x * filter_co for x in pixel] summe_Rp = [ sum([x, y]) for x, y in zip(help, summe_Rp) ] else: help = [x * abs(filter_co) for x in pixel] summe_Rm = [ sum([x, y]) for x, y in zip(help, summe_Rm) ] else: pixel = map( int, self.pixel_matrix[u][v - 1].split()) if filter_co > 0: help = [x * filter_co for x in pixel] summe_Rp = [ sum([x, y]) for x, y in zip(help, summe_Rp) ] else: help = [x * (filter_co) for x in pixel] summe_Rm = [ sum([x, y]) for x, y in zip(help, summe_Rm) ] else: pixel = map(int, self.pixel_matrix[u - 1][v].split()) if filter_co > 0: help = [x * filter_co for x in pixel] summe_Rp = [ sum([x, y]) for x, y in zip(help, summe_Rp) ] else: help = [x * abs(filter_co) for x in pixel] summe_Rm = [ sum([x, y]) for x, y in zip(help, summe_Rm) ] r, g, b = [x - y for x, y in zip(summe_Rp, summe_Rm)] # pixel value range for too high/too low values if int(r) < 0: r = 0 if int(g) < 0: g = 0 if int(b) < 0: b = 0 if int(r) > 255: r = 255 if int(g) > 255: g = 255 if int(b) > 255: b = 255 sharp_pic.put("#%02x%02x%02x" % (int(r), int(g), int(b)), (u, v)) print "Done!\n" return sharp_pic
class rayCaster(object): def __init__(self): self.root = Tk() self.root.title("Ray Tracer") canvas = Canvas(self.root, width=WIN_SIZE , height=WIN_SIZE ) self.image = PhotoImage(master=self.root, width=WIN_SIZE, height=WIN_SIZE) imageCentre = (WIN_SIZE / 2 + 2, WIN_SIZE / 2 + 2) canvas.create_image(imageCentre, image = self.image) canvas.pack() # Enqueue a callback to the ray tracer to start it going self.root.after(0, lambda : self.trace() ) return def putImageRow(self, row, colours): """Output a list of colours to the specified row of the image. Tk uses horrible hexadecimal formatted colours, packed into a string separated by spaces and all enclosed in braces." """ hexColours = ["#%02x%02x%02x" % colour for colour in colours] rowColourString = "{" + " ".join(hexColours) + "}" self.image.put(rowColourString, to=(0, row)) self.root.update() # Main body. Set up an image then compute colour at each pixel def trace(self): camera = definition.camera camera.img = Image.new("RGB", (camera.size, camera.size)) print "ScottTracer" print "\tTracing Rays... 0%", sys.stdout.flush() count = 0 t0 = time.clock() max = float(WIN_SIZE**2) lastPercentage = 0 for row in range(WIN_SIZE): ROW = [] for col in range(WIN_SIZE): count += 1 pixel = camera.pixelColour(col, row) camera.img.putpixel((col, row), pixel.intColour()) ROW.append(pixel.intColour()) percentage = (count / max * 100) self.putImageRow(row, ROW) if percentage - lastPercentage > .9: print "\b\b\b\b\b\b%4.0f%%" % percentage, sys.stdout.flush() lastPercentage = percentage print "\b\b\b\b\b\b Done (%f sec)" % (time.clock() - t0) print "\tAnti-alasing... 0%", sys.stdout.flush() t0 = time.clock() count = 0 lastPercentage = 0 for row in range(WIN_SIZE): ROW = [] self.putImageRow(row, [(255,255,255)] * WIN_SIZE) for col in range(WIN_SIZE): count += 1 pixel = camera.aa(col, row) camera.img.putpixel((col, row), pixel) ROW.append(pixel) percentage = (count / max * 100) self.putImageRow(row, ROW) if percentage - lastPercentage > .9: print "\b\b\b\b\b\b%4.0f%%" % percentage, sys.stdout.flush() lastPercentage = percentage print "\b\b\b\b\b\b (%f sec)" % (time.clock() - t0) print camera.pixels camera.img.save(sys.argv[1] + ".png") # Display image in default image-viewer application
1) from Tkinter import Tk, Canvas, PhotoImage, mainloop w = 400 h = 300 win = Tk() can = Canvas(win, width=w, height=h, bg="#000000") can.pack() img = PhotoImage(width=w, height=h) can.create_image((w/2, h/2), image=img, state="normal") pt = Vector(0,0,0) sphere_center = Vector(100, 0, 0) sphere_radius = 70 max_dist = 100 def color(dist): r = 255 - int( min(dist, max_dist) / float(max_dist) * 255.0) return '#' + (hex(r)[2:] * 3) for y in range(0, w): for z in range(0, h): sln = intersect_ray_sphere(pt, Vector(100, y - w/2, z - h/2), sphere_center, sphere_radius) img.put(sln and color(sln) or '#000000', (y, z)) mainloop()
from Tkinter import Tk, Canvas, PhotoImage, mainloop from math import sin from time import sleep from sys import argv WIDTH, HEIGHT = 640, 480 CORNA = int(argv[1]) CORNB = int(argv[2]) SIDE = float(argv[3]) window = Tk() canvas = Canvas(window, width=WIDTH, height=HEIGHT, bg="#000000") canvas.pack() img = PhotoImage(width=WIDTH, height=HEIGHT) canvas.create_image((WIDTH / 2, HEIGHT / 2), image=img, state="normal") for i in range(WIDTH): for j in range(HEIGHT): x = CORNA + (SIDE * (i / 100.0)) y = CORNB + (SIDE * (j / 100.0)) z = x * x + y * y c = int(z) if c % 2 == 0: img.put("#ffffff", (i, j)) mainloop()
1) from Tkinter import Tk, Canvas, PhotoImage, mainloop w = 400 h = 300 win = Tk() can = Canvas(win, width=w, height=h, bg="#000000") can.pack() img = PhotoImage(width=w, height=h) can.create_image((w / 2, h / 2), image=img, state="normal") pt = Vector(0, 0, 0) sphere_center = Vector(100, 0, 0) sphere_radius = 70 max_dist = 100 def color(dist): r = 255 - int(min(dist, max_dist) / float(max_dist) * 255.0) return '#' + (hex(r)[2:] * 3) for y in range(0, w): for z in range(0, h): sln = intersect_ray_sphere(pt, Vector(100, y - w / 2, z - h / 2), sphere_center, sphere_radius) img.put(sln and color(sln) or '#000000', (y, z)) mainloop()
class MapCanvas(Canvas): """ Visual representation of map instantiated as a Tkinter.Canvas object. """ def __init__(self, parent, top, lmap): """Constructor. Initialises class attributes, calls drawMap. parent = mapcontainer created in Gui. Ref to Gui (top) supplied in case needed for future use.""" Canvas.__init__(self, parent, width=512, height=512) # Bind drag and drop events to canvas and pack it in mapcontainer self.bind('<ButtonPress-1>', self.grab) self.bind('<ButtonRelease-1>', self.drop) self.bind('<B1-Motion>', self.drag) self.pack(side='left', fill=BOTH, expand=1) self.xpos = 0 # X coord of mouse grab event self.ypos = 0 # Y coord of mouse grab event self.scale = 1 # Current zoom level self.im = None # Ref to original image, on which zoom is based self.original = None # image id, as first added to canvas self.zoomed = None # image id, as zoomed on canvas self.lmap = lmap self.drawMap(lmap) def grab(self, event): """Event handler. Displays fleur cursor and gets grab position""" self.ypos = event.y self.xpos = event.x self.config(cursor='fleur') def drop(self, event): """Event handler. Redisplays arrow cursor""" self.config(cursor='arrow') def drag(self, event): """Event handler. Scrolls canvas to new pos and updates old""" self.yview('scroll', self.ypos - event.y, 'units') self.xview('scroll', self.xpos - event.x, 'units') self.ypos = event.y self.xpos = event.x def reset(self): """Resets canvas to zoomlevel 1 and repositions top left""" self.xview_moveto(0) self.yview_moveto(0) self.zoomMap(1, 0, 0) def colorMap(self, char): """Effectively a switch statement to return color based on char""" return { #'.': 'sienna', #'G': 'sienna', '.': 'moccasin', 'G': 'moccasin', 'O': 'black', '@': 'black', 'S': 'OliveDrab1', 'T': 'green4', 'W': 'SkyBlue3', 'k': 'green3', 'D': 'red' }[char] def drawMap(self, lmap): """Creates new map image based on LogicalMap passed in lmap""" w = lmap.width h = lmap.height # set size of canvas and create bitmap of same size self.config(width=w, height=h, xscrollincrement=1, yscrollincrement=1) self.im = PhotoImage(width=w, height=h) # copy colors corresponding to lmap characters into bitmap and create on canvas for row in range(h): for col in range(w): if lmap.isKey((col, row)): color = 'green3' elif lmap.isDoor((col, row)): color = 'red' else: color = self.colorMap(lmap.getCell((col, row))) self.im.put(color, (col, row)) self.original = self.create_image(0, 0, image=self.im, anchor=NW) def clear(self, points, lmap): """Clears set of points by replacing each point with its original color, based on data in lmap""" for coord in points: if lmap.cellWithinBoundaries(coord): color = self.colorMap(lmap.getCell(coord)) self.im.put(color, coord) self.zoomMap(self.scale) def clearCross(self, coord, lmap): """Clears cross at coord by replacing each point with its original color, based on data in lmap""" for n in range(-3, 3): color = self.colorMap(lmap.getCell((coord[0] + n, coord[1] + n))) self._drawPoint(color, (coord[0] + n, coord[1] + n)) color = self.colorMap(lmap.getCell((coord[0] + n, coord[1] - n))) self._drawPoint(color, (coord[0] + n, coord[1] - n)) self.zoomMap(self.scale) def drawCross(self, coord, color): """Draws cross at coord in nominiated color""" for n in range(-2, 3): self._drawPoint(color, (coord[0] + n, coord[1] + n)) self._drawPoint(color, (coord[0] + n, coord[1] - n)) self.zoomMap(self.scale) def drawSet(self, points, color): """Draws set of points in nominated color""" for coord in points: try: self.im.put(color, coord) except TclError: continue self.zoomMap(self.scale) def drawPoint(self, coord, color): """Draws individual point in nominated color""" try: self.im.put(color, coord) self.zoomMap(self.scale) except TclError: pass def _drawPoint(self, color, coord): """Internal. Draws individual point in nominated color without forcing displayed As elsewhere in view_map, assumes calling prog has checked for validity and forgives errors.""" try: self.im.put(color, coord) except TclError: pass def zoomMap(self, scale, x=0, y=0): """Zooms map to scale. Also used to force changes to be displayed""" if self.zoomed: self.delete(self.zoomed) self.zoomed = self.im.zoom(scale, scale) zoomed_id = self.create_image(x, y, image=self.zoomed, anchor=NW) self.delete(self.original) self.scale = scale def getScale(self): """Getter. Returns scale. :rtype : float """ return self.scale
class mapDrawer: def __init__(self, window): self.window = window self.img_location = "/home/user/catkin_ws/src/navigation/scripts/slam_map.png" self.img = PhotoImage(file=self.img_location) self.old_img = misc.imread(self.img_location) self.WIDTH_OF_IMAGE = self.img.width() self.HEIGHT_OF_IMAGE = self.img.height() self.number_of_particles = np.zeros(shape=(self.HEIGHT_OF_IMAGE, self.WIDTH_OF_IMAGE)) self.canvas = Canvas(window, width=self.WIDTH_OF_IMAGE * 2, height=self.HEIGHT_OF_IMAGE * 2, bg="#000000") self.canvas.pack() self.canvas.create_image( (self.WIDTH_OF_IMAGE / 2, self.HEIGHT_OF_IMAGE / 2), image=self.img, state="normal") self.old_red_pixels = [] self.meter_to_pixel = 30.8 def clamp(self, x): return max(0, min(x, 255)) def convert_to_six_digit_code(self, color): r, g, b = color return "#{0:02x}{1:02x}{2:02x}".format(self.clamp(r), self.clamp(g), self.clamp(b)) def restore_old_image(self): for position in self.old_red_pixels: width, height = position self.img.put( self.convert_to_six_digit_code(self.old_img[height][width]), (width, height)) self.old_red_pixels = [] def draw_circle(self, i, j, diameter): min_width = max(0, i - diameter) max_width = min(self.WIDTH_OF_IMAGE - 1, i + diameter) min_height = max(0, j - diameter) max_height = min(self.HEIGHT_OF_IMAGE - 1, j + diameter) for curr_width in range(int(min_width), int(max_width + 1)): for curr_height in range(int(min_height), int(max_height + 1)): if self.img.get(curr_width, curr_height) == "#ff0000": continue if np.sqrt((i - curr_width)**2 + (j - curr_height)**2) <= diameter: self.img.put("#ff0000", (curr_width, curr_height)) self.old_red_pixels.append((curr_width, curr_height)) def update(self, num_of_particles_per_pixel): total_num_of_particles = 0 for value in num_of_particles_per_pixel: total_num_of_particles += num_of_particles_per_pixel.get(value, 0) self.restore_old_image() for value in num_of_particles_per_pixel: percentage = float(num_of_particles_per_pixel.get( value, 0)) / total_num_of_particles if (percentage > 0): self.draw_circle(value % self.WIDTH_OF_IMAGE, value / self.WIDTH_OF_IMAGE, int(int(percentage / 0.15) + 1)) self.window.update() def update_particles(self, particles): number_of_particles_per_pixel = {} for particle in particles: height_in_pixels = int(particle.get_height() * self.meter_to_pixel) width_in_pixels = int(particle.get_width() * self.meter_to_pixel) index = height_in_pixels * self.WIDTH_OF_IMAGE + width_in_pixels number_of_particles_per_pixel[ index] = number_of_particles_per_pixel.get( index, 0) + particle.get_cnt() self.update(number_of_particles_per_pixel)