def apply_filter(self, image, _config): highgui.cvQueryFrame(self.camera) im = highgui.cvQueryFrame(self.camera) pilwebcam_image = opencv.adaptors.Ipl2PIL(im) pilwebcam_image.thumbnail( (int((pilwebcam_image.size[0] / 100.0) * _config['width']), int((pilwebcam_image.size[1] / 100.0) * _config['height']))) ## Border from ImageDraw import Draw drawing = Draw(pilwebcam_image) # top line drawing.line(((0, 0), (pilwebcam_image.size[0], 0)), fill=_config['border_colour']) # left line drawing.line(((0, 0), (0, pilwebcam_image.size[1])), fill=_config['border_colour']) # right line drawing.line(((pilwebcam_image.size[0] - 1, 0), (pilwebcam_image.size[0] - 1, pilwebcam_image.size[1])), fill=_config['border_colour']) # bottow line drawing.line(((0, pilwebcam_image.size[1] - 1), (pilwebcam_image.size[0], pilwebcam_image.size[1] - 1)), fill=_config['border_colour']) image.paste(pilwebcam_image, (10, 10)) return image
def gen_one(text, size): i = Image.new("RGB", size, (255, 255, 255)) d = Draw(i) y = 0 for line in text.splitlines(): d.text((LMARGIN, y), line, font=FONT, fill='black') y += DELTA_Y i.show()
def createImage(letter, i): size = font.getsize(letter) char = new("L", size, 0) drawChar = Draw(char) drawChar.text((0, 0), letter, font=font, fill=255) path = DIR + "/ascii_" + i + ".bmp" char.save(path) return path
def __init__(self, scheduler, rect): Widget.__init__(self, scheduler, rect) draw = Draw(Image.new('1', (0,0))) for size in xrange(100): self.font = ImageFont.truetype('trebuc.ttf', 100-size) (w,h) = draw.textsize('Wednesday', self.font) if w < self.W: break
def __call__(self, perceived, context): if perceived == None: return ((y0, y1), (x0, x1)) = perceived.region image = open_image(self.source) draw = Draw(image) draw.rectangle((x0, y0, x1, y1), outline=(255, 0, 0)) image.save(self.saveas)
def apply_filter(self, image, _config): highgui.cvQueryFrame(self.camera) im = highgui.cvQueryFrame(self.camera) pilwebcam_image = opencv.adaptors.Ipl2PIL(im) pilwebcam_image.thumbnail( ( int((pilwebcam_image.size[0] / 100.0) * _config['width']), int((pilwebcam_image.size[1] / 100.0) * _config['height']) ) ) ## Border from ImageDraw import Draw drawing = Draw(pilwebcam_image) # top line drawing.line(((0,0), (pilwebcam_image.size[0], 0)), fill = _config['border_colour']) # left line drawing.line(((0,0), (0, pilwebcam_image.size[1])), fill = _config['border_colour']) # right line drawing.line(((pilwebcam_image.size[0]-1,0), (pilwebcam_image.size[0]-1, pilwebcam_image.size[1])), fill = _config['border_colour']) # bottow line drawing.line(((0, pilwebcam_image.size[1]-1), (pilwebcam_image.size[0], pilwebcam_image.size[1]-1)), fill = _config['border_colour']) image.paste(pilwebcam_image, (10,10)) return image
def render(self, text, font): # calculate the buffer size for the ticker text image = Image.new('1', (0, 0)) W, _ = Draw(image).textsize(text=text, font=font) H = self.H # render the ticker image = Image.new('1', (W, H), color=0) Draw(image).text((0, 0), text=text, font=font, fill=0xff) #image.show(command='display') return image
def render(self): (W,H) = (self.W, self.H) image = Image.new('1', (W,H), color=0) draw = Draw(image) t = time.localtime() hour = t.tm_hour%12 if hour == 0: hour = 12 text = '%d:%02d' % (hour, t.tm_min) (w,h) = draw.textsize(text, self.font) draw.text((-3,-h/6), text=text, font=self.font, fill=1) return image
def __init__(self, scheduler, rect): Widget.__init__(self, scheduler, rect) draw = Draw(Image.new('1', (0,0))) for size in xrange(100): self.font = ImageFont.truetype('trebuc.ttf', 100-size) (w,h) = draw.textsize('77', self.font) if w < self.W-36: break # regexes for parsing weather reports self.icontag = re.compile('<icon_url_name>(.+).jpg</icon_url_name>') self.tempftag = re.compile('<temp_f>(\d+)</temp_f>') self.update()
def __init__(self, scheduler, rect, mail=None): Widget.__init__(self, scheduler, rect) draw = Draw(Image.new('1', (0,0))) for size in xrange(100): self.font = ImageFont.truetype('trebuc.ttf', 100-size) (w,h) = draw.textsize('7', self.font) if w < self.W-32: break if mail == None: mail = gmail.GmailStatus() self.mail = mail self.mailicon = Image.open('mail.gif').convert('L').point(lambda x: 255-x, mode='1') self.update()
def apply_filter(self, image, _config): # OpenCV sucks, it keeps all frames cached so when I query them # they are old frames. I delete the camera object and get a new one # so i can query the current frame only. # this is the only solution i could work out to this problem. del self.camera self.camera = cv.CaptureFromCAM(-1) im = cv.QueryFrame(self.camera) # HEY HERE IS SOMETHING REALLY FUNNY # OPENCV USES BGR FOR IT'S INTERNAL IMAGE FORMAT # WOW # SO STANDARD GUYS # FAN-F*****G-TASTIC # I DIDN'T TOTALLY JUST SPEND THREE HOURS WORKING THAT OUT # GREAT STUFF # YOUR OWN EXAMPLE CODE FOR CONVERTING TO A PIL IMAGE DOESN'T TAKE THIS INTO ACCOUNT AT ALL # WTFFFFFFFFFFF pilwebcam_image = Image.fromstring("RGB", cv.GetSize(im), im.tostring()[::-1]).rotate(180) pilwebcam_image = pilwebcam_image.resize( (int((pilwebcam_image.size[0] / 100.0) * _config['width']), int((pilwebcam_image.size[1] / 100.0) * _config['height'])), Image.ANTIALIAS) ## Border drawing = Draw(pilwebcam_image) # top line drawing.line(((0, 0), (pilwebcam_image.size[0], 0)), fill=_config['border_colour']) # left line drawing.line(((0, 0), (0, pilwebcam_image.size[1])), fill=_config['border_colour']) # right line drawing.line(((pilwebcam_image.size[0] - 1, 0), (pilwebcam_image.size[0] - 1, pilwebcam_image.size[1])), fill=_config['border_colour']) # bottow line drawing.line(((0, pilwebcam_image.size[1] - 1), (pilwebcam_image.size[0], pilwebcam_image.size[1] - 1)), fill=_config['border_colour']) image.paste(pilwebcam_image, (10, 10)) return image
def __init__(self, width = 300, height = 300, alpha = 30): # сохраняем высоту и ширину картинки self.width = width self.height = height self.im = Image.new('RGB', (width, height), (255, 255, 255)) # создаем пустое изображение self.draw = Draw(self.im) self.font = ImageFont.truetype(dirname(abspath(__file__)) + '/GOST_A.TTF', 17) self.alpha = alpha
def refresh(self, display): (W, H) = (self.W, self.H) image = Image.new('1', (W, H)) draw = Draw(image) self.render(draw) display.bitmap((self.X, self.Y), image, fill='#fff')
def gen_diff(r1, r2, diff, size): i = Image.new("RGB", size, (255, 255, 255)) d = Draw(i) font = ImageFont.truetype('ProFontWindows.ttf', 12) y = 0 print diff raw_input("is that what you wanted?") for g in groupdiffs(diff): print g raw_input("is that what you wanted?")
def alert(self, interval=10): (W, H) = (self.display.W, self.display.H) image = Image.new('1', (W, H)) draw = Draw(image) self.render(draw) self.display.bitmap((0, 0), image, fill=1) time.sleep(interval) self.display.clear()
def showProc(): # # reduce screen burn in by using some of the real estate to move # the image around # top = random.randint(1, 100) cputype.Y = top top += 40 loadavg.Y = top cpubusy.Y = top cputemp.Y = top top += 40 memfree.Y = top + 0 swapfree.Y = top + 32 diskfree.Y = top diskfree.update() # # for each sample in the interval # for moment in xrange(INTERVAL): # # refresh the indicators # (W, H) = (display.W, display.H) image = Image.new('1', (W, H)) draw = Draw(image) cputype.refresh(draw) loadavg.refresh(draw) cpubusy.refresh(draw) cputemp.refresh(draw) memfree.refresh(draw) swapfree.refresh(draw) diskfree.refresh(draw) display.bitmap((0, 0), image, fill='#fff') #image.save('proc.png') time.sleep(1)
def apply_filter(self, image, _config): # OpenCV sucks, it keeps all frames cached so when I query them # they are old frames. I delete the camera object and get a new one # so i can query the current frame only. # this is the only solution i could work out to this problem. del self.camera self.camera = cv.CaptureFromCAM(-1) im = cv.QueryFrame(self.camera) # HEY HERE IS SOMETHING REALLY FUNNY # OPENCV USES BGR FOR IT'S INTERNAL IMAGE FORMAT # WOW # SO STANDARD GUYS # FAN-F*****G-TASTIC # I DIDN'T TOTALLY JUST SPEND THREE HOURS WORKING THAT OUT # GREAT STUFF # YOUR OWN EXAMPLE CODE FOR CONVERTING TO A PIL IMAGE DOESN'T TAKE THIS INTO ACCOUNT AT ALL # WTFFFFFFFFFFF pilwebcam_image = Image.fromstring("RGB", cv.GetSize(im), im.tostring()[::-1]).rotate(180) pilwebcam_image = pilwebcam_image.resize( ( int((pilwebcam_image.size[0] / 100.0) * _config['width']), int((pilwebcam_image.size[1] / 100.0) * _config['height']) ), Image.ANTIALIAS ) ## Border drawing = Draw(pilwebcam_image) # top line drawing.line(((0,0), (pilwebcam_image.size[0], 0)), fill = _config['border_colour']) # left line drawing.line(((0,0), (0, pilwebcam_image.size[1])), fill = _config['border_colour']) # right line drawing.line(((pilwebcam_image.size[0]-1,0), (pilwebcam_image.size[0]-1, pilwebcam_image.size[1])), fill = _config['border_colour']) # bottow line drawing.line(((0, pilwebcam_image.size[1]-1), (pilwebcam_image.size[0], pilwebcam_image.size[1]-1)), fill = _config['border_colour']) image.paste(pilwebcam_image, (10,10)) return image
def randomPenguin(interval=0): global Px, Py penguin = Image.open('tux.jpg') _, _, w, h = penguin.getbbox() for i in xrange(interval * 2): (W, H) = (display.W, display.H) image = Image.new('1', (W, H)) draw = Draw(image) Px += random.randint(-2, 2) Px = max(Px, 0) Px = min(Px, W - w) Py += random.randint(-2, 2) Py = max(Py, 0) Py = min(Py, H - h) draw.bitmap((Px, Py), penguin, fill=1) display.bitmap((0, 0), image) time.sleep(0.5)
def showMail(): if mail.mail.messages > 0: (W, H) = (display.W, display.H) image = Image.new('1', (W, H)) draw = Draw(image) top = random.randint(1, 200) mail.Y = top mail.refresh(draw) display.bitmap((0, 0), image) time.sleep(INTERVAL)
def render(self): (W,H) = (self.W, self.H) image = Image.new('1', (W,H), color=0) draw = Draw(image) draw.text((0,1), time.strftime('%A'), font=self.font, fill=1) draw.text((0,H*5/11), time.strftime('%d %b %Y'), font=self.font, fill=1) L = W - 93 return image
def render(self): (W,H) = (self.W, self.H) image = Image.new('1', (W,H), color=0) draw = Draw(image) newmail = self.mail.messages if newmail > 0: draw.bitmap((0,2), self.mailicon, fill=1) text = '%d' % newmail (w,h) = draw.textsize(text, self.font) draw.text((30,(32-h)/2), text=text, font=self.font, fill=1) return image
def roll_date_time(data, out, hour_parts=4, lines=4): bg_color = (255, 255, 255) line_color = (220, 220, 220) color=(32,32,255) def date_value(event): return (event.date() - epoch).days def date_coords(event): time_value = event.hour * hour_parts + event.minute * hour_parts / 60 return (date_value(event) - start_value, height - time_value - 1) epoch = date(1970, 1, 1) # find boundarys start = min(data) end = max(data) # calculate value of boundarys start_value = date_value(start) end_value = date_value(end) # calculate geometry width = end_value - start_value + 1 height = 24 * hour_parts # building the image img = Image.new("RGB", (width, height + 10), bg_color) draw = Draw(img) # drawing horizontal (time) lines to enhance readability for line in xrange(lines): y = (height / lines) * (line + 1) draw.line([(0, y), (width - 1, y)], line_color) # drawing vertical (date) lines and captions for month_start in iter_months(start, end): x, _ = date_coords(month_start) draw.line([(x, 0), (x, height - 1)], line_color) draw.text((x + 3, height), month_start.strftime("%m"), line_color) # plotting actual data for event in data: img.putpixel(date_coords(event), color) img.save(out, 'png')
def render(self): (W,H) = (self.W, self.H) image = Image.new('1', (W,H), color=0) draw = Draw(image) try: text = self.tempf (w,h) = draw.textsize(text, self.font) Y = (32-h)/2 draw.text((30,Y), text, font=self.font, fill=1) X = 30 + w draw.ellipse((X-2,2,X+2,6), outline=1, fill=0) icon = Image.open(self.icon+'.gif').convert('L').point(lambda x: 255-x, mode='1') draw.bitmap((0,2), icon, fill=1) except: pass return image
def main(argv): #width, height, iterations, skiplen, how to plot (PIL, pygame, GTK, both?) #scale, x and y offsets, parser = setup_parser() opts, args = parser.parse_args(argv) args = args[1:] #Begin parsing arguments # global VERBOSITY VERBOSITY = opts.verbosity message("Beginning option parsing", V_DEBUG) scale = opts.scale if not scale: parser.error("argument -s/--scale is compulsory!") if not args: parser.error("must specify a .frct file to use!") rules = load_file(args[0]) if opts.autocalc: dim, offsets = calculate_best_settings(rules, scale) print "Dimensions: %dx%d"%(dim[0],dim[1]) print """Offsets: x: %d y: %d"""%(offsets[0],offsets[1]) sys.exit(0) its = opts.iterations if opts.color_file: colors = load_colors_from_file(opts.color_file) else: colors = [] if opts.color_type == COLOR_NORMAL: if opts.color_file: color = colors[0] else: color = string2color(opts.color) elif opts.color_type == COLOR_REGION: if opts.color_file: color = colors elif len(opts.color) > 9: # color = [string2color(x) for x in split_int(opts.color, 9)] #((0,255,0),(0,255,0),(0,0,255),(255,255,255), (255, 255,0), (0, 255, 255), (255, 0,255)) elif opts.color_type == COLOR_FANCY: color = int(opts.color[0]) if opts.color_type == COLOR_GRADIENT: color = make_gradient([int(i) for i in opts.gradient_int.split(',')], [int(i) for i in opts.gradient_start.split(',')],\ [int(i) for i in opts.gradient_end.split(',')]) skip = 500 if not (opts.geometry and opts.x_offset and opts.y_offset): dim, offsets = calculate_best_settings(rules, scale) if opts.geometry: dim = [int(i) for i in opts.geometry.split("x")] else: dim = int(dim[0]), int(dim[1]) if opts.x_offset: x_off = opts.x_offset else: x_off = int(offsets[0]) if opts.y_offset: y_off = opts.y_offset else: y_off = int(offsets[1]) bg_col = tuple(string2color(opts.background)) if opts.save: import Image as im from ImageDraw import Draw image = True screen = im.new("RGB", dim) draw = Draw(screen) draw.rectangle([0,0, dim[0], dim[1]], fill = bg_col) pix = screen.load() else: import pygame image = False screen = pygame.display.set_mode(dim) screen.fill(bg_col) pygame.display.set_caption("pyafg - %s"%args[0]) message("Finished option parsing", V_DEBUG) ##### FINISHED OPTION PARSING ##### def pixel_set(xy, color): color = tuple(color) if image: try: pix[xy[0],xy[1]] = color#(color[0],color[1],color[2],255) except IndexError:pass else: screen.set_at(xy, color) #Use this for pixel counting global pixel_count pixel_count = {} #Drawing methods def normal(x, y, chosen):#THIS IS A HACK (DIM, ETC.) pixel_set((int(x*scale)+x_off, int(dim[1]-(y*scale))+y_off), color) def regions(x, y, chosen): pixel_set((int(x*scale)+x_off, int(dim[1]-(y*scale))+y_off), color[chosen]) def fancy(x, y, chosen): pixel = (int(x*scale)+x_off, int(dim[1]-(y*scale))+y_off) c = [0,0,0] global pixel_count if not pixel_count.has_key(pixel): c[color] = 50 pixel_set(pixel,c) pixel_count[pixel] = 1 else: pixel_count[pixel] += 1 if pixel_count[pixel]*10>205: c[color] = 255 pixel_set(pixel, c) else: c[color] = 50+10*pixel_count[pixel] pixel_set(pixel, c) def gradient(x, y, chosen): pixel = (int(x*scale)+x_off, int(dim[1]-(y*scale))+y_off) global pixel_count if not pixel_count.has_key(pixel): pixel_set(pixel,color[0]) pixel_count[pixel] = 1 else: pixel_count[pixel] += 1 try:pixel_set(pixel, color[pixel_count[pixel]]) except IndexError:pixel_set(pixel, color[-1]) draw_methods = [normal, regions, fancy, gradient] draw = draw_methods[opts.color_type] ##### BEGIN ACTUALLY DRAWING THE IFS ##### for points in generate_IFS(its, skip, rules): x, y, chosen, i = points draw(x, y, chosen) if i%opts.speak_int == 0: if not image: pygame.display.flip() message("%d%% done."%((float(i)/float(its))*100), V_ESSENTIAL) if image: #If we're just generating an image screen.save(opts.save) message("Saved image to %s"%opts.save, V_ESSENTIAL) else: #Semi interactive mode... while 1: for event in pygame.event.get(): if event.type == QUIT: sys.exit() if event.type == KEYDOWN: if event.key == K_s: file = args[0].split('.')[0]+'.png' new_image = pygame.Surface((dim[0], dim[1])) new_image.blit(screen, (0,0)) pygame.image.save(new_image, file) print "Image saved to %s"%file elif event.key == K_q: sys.exit() pygame.display.flip()
def imageop(self, op, *args, **keys): t = time.time() image = self.image.copy() op(Draw(image), *args, **keys) self.refresh(image)
def draw(self, frame, canvas): p = self.positions[frame] Draw(canvas).ellipse((p[0], p[1], p[0] + self.size[0], p[1] + self.size[1]), fill = self.color)
def showHost(): (W, H) = (display.W, display.H) image = Image.new('1', (W, H)) draw = Draw(image) top = random.randint(1, 170) tuxicon.Y = top tuxicon.refresh(draw) hostname = platform.node() ipaddr = getIpAddr() text = '%s %s' % (hostname, ipaddr) (w, h) = draw.textsize(text, font16) draw.text((80, top + 0), text=text, font=font16, fill=111) text = '%s %s' % (platform.system(), platform.release()) (w, h) = draw.textsize(text, font16) draw.text((80, top + 20), text, font=font16, fill=111) (days, hours, minutes) = getUptime() text = 'uptime %dd %dh %dm' % (days, hours, minutes) (w, h) = draw.textsize(text, font16) draw.text((80, top + 40), text, font=font16, fill=111) display.bitmap((0, 0), image) time.sleep(INTERVAL)
class DesignDraw: def __init__(self, width = 300, height = 300, alpha = 30): # сохраняем высоту и ширину картинки self.width = width self.height = height self.im = Image.new('RGB', (width, height), (255, 255, 255)) # создаем пустое изображение self.draw = Draw(self.im) self.font = ImageFont.truetype(dirname(abspath(__file__)) + '/GOST_A.TTF', 17) self.alpha = alpha # функция преобразующая сантиметры в пиксели def sm2px(self, sm): return (sm * self.alpha) # функция преобразующая координаты из декартовой # в экранную систему координат # координаты в пикселях def dec2screen(self, x, y): return (x, self.height - y) def Show(self): invert_im = ImageOps.invert(self.im) bbox = invert_im.getbbox() self.im = self.im.crop((bbox[0] -5, bbox[1] - 5, bbox[2] + 5, bbox[3] + 5)) self.im.show() def Crop(self): invert_im = ImageOps.invert(self.im) bbox = invert_im.getbbox() self.im = self.im.crop((bbox[0] -5, bbox[1] - 5, bbox[2] + 5, bbox[3] + 5)) def Size(self): """ Возвращает (ширину, высоту) изображения. """ return self.im.size def Resize(self, width = 400, height = 400): self.im = self.im.resize((width, height), Image.ANTIALIAS) # функция рисующая точку # принимаемые координаты в декартовой системе координат # в сантиметрах def Dot(self, x, y, radius = 5): halfr = radius / 2 x = self.sm2px(x) y = self.sm2px(y) (x, y) = self.dec2screen(x, y) self.draw.ellipse((x - halfr, y - halfr, x + halfr, y + halfr), fill=(0, 0, 0, 0)) # функция рисующая прямоугольник # принимаемые координаты в декартовой системе координат # в сантиметрах # x, y - нижний левый угол def Rect(self, x, y, width, height): x = self.sm2px(x) y = self.sm2px(y) width = self.sm2px(width) height = self.sm2px(height) (x, y) = self.dec2screen(x, y) self.draw.rectangle((x, y - height, x + width, y), outline="black") # функция рисующая линию с незакрашенной стрелкой в конце # принимаемые координаты в декартовой системе # в сантиметрах def LineStrokeArrow(self, x1, y1, x2, y2, headlen = 10, headwid = 6): [x1, y1, x2, y2] = [self.sm2px(x1), self.sm2px(y1), self.sm2px(x2), self.sm2px(y2)] [x1, y1] = self.dec2screen(x1, y1) [x2, y2] = self.dec2screen(x2, y2) angle = atan2(y2 - y1, x2 - x1) self.draw.line((x1, y1, x2, y2), fill="black") # координаты левого крыла (lwx, lwy) = (x2 - headlen * cos(angle - pi / headwid), y2 - headlen * sin(angle - pi / headwid)) # координаты правого крыла (rwx, rwy) = (x2 - headlen * cos(angle + pi / headwid), y2 - headlen * sin(angle + pi / headwid)) # рисуем крылья self.draw.line((x2, y2, lwx, lwy), fill="black") self.draw.line((x2, y2, rwx, rwy), fill="black") # функция рисующая линию с закрашенной стрелкой в конце # принимаемые координаты в декартовой системе # в сантиметрах def LineFillArrow(self, x1, y1, x2, y2, headlen = 10, headwid = 6, width = 1): [x1, y1, x2, y2] = [self.sm2px(x1), self.sm2px(y1), self.sm2px(x2), self.sm2px(y2)] [x1, y1] = self.dec2screen(x1, y1) [x2, y2] = self.dec2screen(x2, y2) angle = atan2(y2 - y1, x2 - x1) self.draw.line((x1, y1, x2, y2), fill="black", width = width) # координаты левого крыла (lwx, lwy) = (x2 - headlen * cos(angle - pi / headwid), y2 - headlen * sin(angle - pi / headwid)) # координаты правого крыла (rwx, rwy) = (x2 - headlen * cos(angle + pi / headwid), y2 - headlen * sin(angle + pi / headwid)) lines = [(x2, y2), (lwx, lwy), (rwx, rwy)] self.draw.polygon(lines, fill="black") # функция рисующая линию с закрашенными стрелками на концах # принимаемые координаты в декартовой системе # в сантиметрах def Line2FillArrow(self, x1, y1, x2, y2, headlen = 5, headwid = 5): [x1, y1, x2, y2] = [self.sm2px(x1), self.sm2px(y1), self.sm2px(x2), self.sm2px(y2)] [x1, y1] = self.dec2screen(x1, y1) [x2, y2] = self.dec2screen(x2, y2) angle = atan2(y2 - y1, x2 - x1) self.draw.line((x1, y1, x2, y2), fill="black") # первая стрелка # координаты левого крыла (lwx, lwy) = (x2 - headlen * cos(angle - pi / headwid), y2 - headlen * sin(angle - pi / headwid)) # координаты правого крыла (rwx, rwy) = (x2 - headlen * cos(angle + pi / headwid), y2 - headlen * sin(angle + pi / headwid)) lines = [(x2, y2), (lwx, lwy), (rwx, rwy)] self.draw.polygon(lines, fill="black") # вторая стрелка # координаты левого крыла (lwx, lwy) = (x1 + headlen * cos(angle - pi / headwid), y1 + headlen * sin(angle - pi / headwid)) # координаты правого крыла (rwx, rwy) = (x1 + headlen * cos(angle + pi / headwid), y1 + headlen * sin(angle + pi / headwid)) lines = [(x1, y1), (lwx, lwy), (rwx, rwy)] self.draw.polygon(lines, fill="black") # функция рисующая линию с незакрашенной стрелкой в конце # принимаемые координаты в декартовой системе # в сантиметрах def Line(self, x1, y1, x2, y2): [x1, y1, x2, y2] = [self.sm2px(x1), self.sm2px(y1), self.sm2px(x2), self.sm2px(y2)] [x1, y1] = self.dec2screen(x1, y1) [x2, y2] = self.dec2screen(x2, y2) self.draw.line((x1, y1, x2, y2), fill="black") # функция рисующая текст # принимаемые координаты в декартовой системе # в сантиметрах def Text(self, text, x, y): [x, y] = [self.sm2px(x), self.sm2px(y)] [x, y] = self.dec2screen(x, y) self.draw.text((x + 4, y - 18), text, font=self.font, fill="black") def BottomAlignText(self, text, x, y): [x, y] = [self.sm2px(x), self.sm2px(y)] [x, y] = self.dec2screen(x, y) (textw, texth) = self.font.getsize(text) self.draw.text((x - (textw / 2.0), y), text, font=self.font, fill="black") def LeftAlignText(self, text, x, y): [x, y] = [self.sm2px(x), self.sm2px(y)] [x, y] = self.dec2screen(x, y) (textw, texth) = self.font.getsize(text) self.draw.text((x - textw - 2, y - (texth / 2.0)), text, font=self.font, fill="black") def RightAlignText(self, text, x, y): [x, y] = [self.sm2px(x), self.sm2px(y)] [x, y] = self.dec2screen(x, y) (textw, texth) = self.font.getsize(text) self.draw.text((x + 2, y - (texth / 2.0)), text, font=self.font, fill="black") def TopAlignText(self, text, x, y): [x, y] = [self.sm2px(x), self.sm2px(y)] [x, y] = self.dec2screen(x, y) (textw, texth) = self.font.getsize(text) self.draw.text((x - (textw / 2.0), y - texth), text, font=self.font, fill="black") def Polygon(self, xy): screen_xy = [self.dec2screen(self.sm2px(x), self.sm2px(y)) for x, y in xy] self.draw.polygon(screen_xy, outline="black") def TextSize(self, text): return self.font.getsize(text) def Circle(self, x, y, radius): radius = self.sm2px(radius) halfr = radius / 2 x = self.sm2px(x) y = self.sm2px(y) (x, y) = self.dec2screen(x, y) self.draw.ellipse((x - halfr, y - halfr, x + halfr, y + halfr), fill=None, outline=(0, 0, 0, 0))
green = (63, 104, 28) yellow = (254,185,0) cream = (239,233,244) # import data f = open("input.txt", "r") inDict = {x:y for x,y in [v.split() for v in f.readlines()]} g = open("timeFromSx.csv") monthList = [int(v.strip('\n')) for v in g.readlines()] # set output file outName = "infographic.png" out = Image.new("RGB", (w,h), color=yellow) draw = Draw(out) # Panel A ncol=8 # number of columns # This is the people panel nman = int(inDict["nman"]) man = Image.open("man.png") manw,manh = man.size nwoman = int(inDict["nwoman"]) woman = Image.open("woman.png") womanw,womanh = man.size # man/woman height
print "!! Scale must be a positive number !!" sys.exit(1) padding = options.padding + outline size = (scale * len(logo)) + (2 * padding) if invert: background, color = color, background logo = [[not i for i in row] for row in logo] # ------------------------------------------------------------------------------ # Render # ------------------------------------------------------------------------------ im = new('RGB', (size, size), background) draw = Draw(im) if invert: pass if border: start = padding - 1 end = size - padding draw.rectangle([(start, start), (end, end)], outline=border) for y, row in enumerate(logo): for x, pixel in enumerate(row): if pixel: xfactor = (x * scale) + padding yfactor = (y * scale) + padding for px in range(xfactor, xfactor+scale):
def RingTracking2D(data, n_centers, threshold = 0.5, draw_dots = False, draw_mean = False, return_dots = False, outfolder = None, static = True): # tracks a ring pattern in 2D. Locates particles using the Hough transfrom algorithm (center_find) # data is a stack of images to track particles in, stored as xyt hyperstack # n_centers is the number of ring patterns to track # theshold is the treshold used in center_find # draw_dots = True draws a label and a spot on each image from data where each center was found # draw_mean = True Uses the mean coordinate from each track as the position of the spot to be drawn # return_dots = True, retrun the images with the spots drawn on them # outfolder = location to save images with spots/labels # static = True uses first location of a particle to link tracks. Use False if the particle is moving # # # returns an array containing the coordinates of the ring centers at each frame # Also returns the images with a tracks labeled if return_dots = True #find centers from holopy.core.process.centerfinder import center_find coords = [] print('finding particles') #loop through each frame for i in np.arange(0,data.shape[-1]): if i%50 == 0: print(i) coord = center_find(data[:,:,i], centers = n_centers, threshold = threshold) if n_centers ==1: coord = np.reshape(coord, (1,2)) coords.append(coord) coords = np.array(coords) #link up particles between frames print('linking tracks') def get_distance(coords1, coords2): return np.sqrt( (coords1[0]-coords2[0])**2 + (coords1[1]-coords2[1])**2 ) tracks = np.empty(coords.shape) #loop through each particle for particle in np.arange(0,coords.shape[1]): #set initial point tracks[0,particle,:] = coords[0,particle,:] known_coord = tracks[0,particle,:] #location of the particle for comparison #look in subsequent frames to find the closest particle to known_coord for frame in np.arange(1,coords.shape[0]): min_distance = 10000 if not static: known_coord = tracks[frame-1,particle,:] #compare to all center locations for i in np.arange(0,coords.shape[1]): distance = get_distance(known_coord, coords[frame,i,:]) if distance < min_distance: min_distance = distance closest_particle_index = i #set track coordinate tracks[frame,particle,:] = coords[frame, closest_particle_index, :] if not draw_dots: return tracks #Draw a spot at each point that was found else: print('drawing tracks') from Image import fromarray from ImageDraw import Draw #used for scaling images im_max = data.max() im_min = data.min() if return_dots: spot_images = [] if draw_mean: tracksmean = np.mean(tracks,0) #loop through each frame for i in np.arange(0,data.shape[-1]): #convert to an RGB image spot_image = fromarray( 255*(data[:,:,i]-im_min)/(im_max-im_min) ) spot_image = spot_image.convert('RGB') #draw spots and labels draw = Draw(spot_image) for j in np.arange(0,tracks.shape[1]): if draw_mean: spot_coord = [np.round(tracksmean[j,1]), np.round(tracksmean[j,0])] else: spot_coord = [np.round(tracks[i,j,1]), np.round(tracks[i,j,0])] draw.point( (spot_coord[0],spot_coord[1]), (255,0,0)) draw.text( (spot_coord[0]-10,spot_coord[1]-10), str(j),(255,0,0)) if return_dots: spot_images.append(spot_image) if outfolder != None: spot_image.save(outfolder + 'spot_image' + str(i).zfill(5) +'.png') if return_dots: return [tracks, spot_images] else: return tracks
print "!! Scale must be a positive number !!" sys.exit(1) padding = options.padding + outline size = (scale * len(logo)) + (2 * padding) if invert: background, color = color, background logo = [[not i for i in row] for row in logo] # ------------------------------------------------------------------------------ # Render # ------------------------------------------------------------------------------ im = new('RGB', (size, size), background) draw = Draw(im) if invert: pass if border: start = padding - 1 end = size - padding draw.rectangle([(start, start), (end, end)], outline=border) for y, row in enumerate(logo): for x, pixel in enumerate(row): if pixel: xfactor = (x * scale) + padding yfactor = (y * scale) + padding for px in range(xfactor, xfactor + scale):
def EllipseFitting(self,mode): #img = Image.open(self.filename) frames = [self.image] width, height = self.image.size white = 0 ful=width*height for i in range(height): for j in range (width): rgb = self.image.getpixel((j,i)) if rgb!=0: white=white+1 self.por=int((white/ful)*170) #if self.por<100: # self.por = 200 #elif self.por>400: # self.por=400 print "\t==== all pixels = ", ful, " ====" print "\t==== white pixels = ", white, " ====" print "\t==== threshold sensitivity is = ", self.por, " ====" print "\t==== Begining find clusters... ====" img = self.image.convert("RGB") frames = [img] points_to_track = self.ClaNum k_or_guess = points_to_track X, Y = frames[0].size try: for im, n in zip(frames, count()): points = array([array([p.x, p.y], "f") for p in self.red_points(list(im.getdata()), X, Y)]) if len(points) > 0: codebook, distortion = vq.kmeans(points, k_or_guess) draw = Draw(im) assert points_to_track == len(codebook) delt=int(distortion) res = self.UnionClasters(codebook) self.Clusters = res for p in res: draw.line((p[0]-10, p[1]-10) + (p[0]+10, p[1]+10), fill=(255, 0, 0)) draw.line((p[0]-10, p[1]+10) + (p[0]+10, p[1]-10), fill=(255, 0, 0)) draw.ellipse((p[0]-(int(self.por/2)), p[1]-(int(self.por/2)), p[0]+(int(self.por/2)), p[1]+(int(self.por/2))), None, "blue") print finally: if mode=='s': frames[0].show()
def getImage(self, timestamp=0, boldfont=0, textpos='bl'): """Returns a PIL Image instance. timestamp: 0 ... no timestamp (the default) 1 ... simple timestamp 2 ... timestamp with shadow 3 ... timestamp with outline boldfont: 0 ... normal font (the default) 1 ... bold font textpos: The position of the timestamp can be specified by a string containing a combination of two characters. One character must be either t or b, the other one either l, c or r. t ... top b ... bottom l ... left c ... center r ... right The default value is 'bl' """ im = highgui.cvQueryFrame(self.camera) #onlyRed = False #if onlyRed: # r,g,b = opencv.adaptors.Ipl2PIL(im).split() # im = ImageChops.difference(r, g) # im = im.convert("RGB") #else: im = opencv.adaptors.Ipl2PIL(im) if timestamp: width, height = self.resolution textcolor = 0xffffff shadowcolor = 0x000000 text = time.asctime(time.localtime(time.time())) if boldfont: self.font = self.boldfont else: self.font = self.normalfont tw, th = self.font.getsize(text) tw -= 2 th -= 2 if 't' in textpos: y = -1 elif 'b' in textpos: y = height - th - 2 else: raise ValueError, "textpos must contain exactly one out of 't', 'b'" if 'l' in textpos: x = 2 elif 'c' in textpos: x = (width - tw) / 2 elif 'r' in textpos: x = (width - tw) - 2 else: raise ValueError, "textpos must contain exactly one out of 'l', 'c', 'r'" draw = Draw(im) if timestamp == 2: # shadow draw.text((x+1, y), text, font=self.font, fill=shadowcolor) draw.text((x, y+1), text, font=self.font, fill=shadowcolor) draw.text((x+1, y+1), text, font=self.font, fill=shadowcolor) else: if timestamp >= 3: # thin border draw.text((x-1, y), text, font=self.font, fill=shadowcolor) draw.text((x+1, y), text, font=self.font, fill=shadowcolor) draw.text((x, y-1), text, font=self.font, fill=shadowcolor) draw.text((x, y+1), text, font=self.font, fill=shadowcolor) if timestamp == 4: # thick border draw.text((x-1, y-1), text, font=self.font, fill=shadowcolor) draw.text((x+1, y-1), text, font=self.font, fill=shadowcolor) draw.text((x-1, y+1), text, font=self.font, fill=shadowcolor) draw.text((x+1, y+1), text, font=self.font, fill=shadowcolor) draw.text((x, y), text, font=self.font, fill=textcolor) return im
def text(self, xy, text, fill=None, font=None, anchor=None): #text = text.replace(' ','_') # nasty workaround for PIL bug on amd64 image = self.image.copy() Draw(image).text(xy, text, fill, font, anchor) self.refresh(image)