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 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) 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 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) 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 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)
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 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
font = truetype('/usr/share/fonts/truetype/msttcorefonts/arialbd.ttf', int(300 * font_size / 72.0)) smallFont_size = 11 smallFont = truetype('/usr/share/fonts/truetype/msttcorefonts/arialbd.ttf', int(300 * smallFont_size / 72.0)) bigFont_size = 18 bigFont = truetype('/usr/share/fonts/truetype/msttcorefonts/arialbd.ttf', int(300 * bigFont_size / 72.0)) # female text text = str(nwoman) + u"\u2640" + " " + str(nman) + u"\u2642" text_w, text_h = font.getsize(text) draw.text((lmar, umar-text_h), text, fill=cream, font=font) ## male text #text = #draw.text((lmar, h-bmar), text, fill=cream, font=font) # Panel B ncolj1=2 ninfus = int(inDict["ninfus1"]) colcount = float(ninfus) colcount += colcount%ncolj1 colcount /= ncolj1 # import picture of an injection inj = Image.open("injection1.png") injw, injh = inj.size
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
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))