Python PIL.ImageFont.truetype() Examples
The following are 30
code examples of PIL.ImageFont.truetype().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
PIL.ImageFont
, or try the search function
.
Example #1
Source File: polapizero_03.py From polapi-zero with MIT License | 7 votes |
def displayImageFileOnLCD(filename): print 'displays ', filename title = 'Review Mode' # resize/dither to screen resolution and send to LCD image = Image.open(filename) im_width, im_height = image.size if im_width < im_height: image = image.rotate(90) image.thumbnail(S_SIZE, Image.ANTIALIAS) image_sized = Image.new('RGB', S_SIZE, (0, 0, 0)) image_sized.paste(image,((S_SIZE[0] - image.size[0]) / 2, (S_SIZE[1] - image.size[1]) / 2)) # draw filename draw = ImageDraw.Draw(image_sized) font = ImageFont.truetype('arial.ttf', 18) draw.rectangle([(0, 0), (115, 22)], fill=(255,255,255), outline=(0,0,0)) draw.text((2, 2), title, fill='black', font=font) draw.rectangle([(279, 217), (399, 239)], fill=(255,255,255), outline=(0,0,0)) draw.text((290, 218), filename, fill='black', font=font) # display on LCD image_sized = ImageOps.invert(image_sized) image_sized = image_sized.convert('1') # convert image to black and white lcd.write(image_sized.tobytes())
Example #2
Source File: deceptiveidn.py From deceptiveidn with Apache License 2.0 | 6 votes |
def render_idn(text, font_name, font_size): width = 500 height = 100 bgcolor = (255, 255, 255, 255) color = (0,0,0, 255) image = Image.new("RGBA", (width, height), bgcolor) draw = ImageDraw.Draw(image) font = ImageFont.truetype(font_name, font_size, encoding="unic") draw.text((0, 0), text, font=font, fill=color) out_file = tempfile.NamedTemporaryFile(suffix=".png") image.save(out_file.name) return out_file
Example #3
Source File: mapping.py From Zabbix-Network-Weathermap with GNU General Public License v3.0 | 6 votes |
def __init__(self, fontfile, bgcolor='white', fontcolor='black', fontsize=10, outline='black', label=None, point=None): self.outline = outline self.bgcolor = bgcolor self.fontcolor = fontcolor self.fontsize = fontsize self.fontfile = fontfile self.font = ImageFont.truetype(self.fontfile, size=self.fontsize) self.name = str(label) self.points = [0, 0, 0, 0] self.point_name = [0, 0] self.font_width = {8: 6, 10: 7.4, 12: 8, 14: 9, 16: 11, 18: 12, 20: 13} try: self.font_width[self.fontsize] except KeyError: self.fontsize = 10 if point: self.label_xy(point) log.debug('Object Label created')
Example #4
Source File: tabledraw.py From MangoByte with MIT License | 6 votes |
def __init__(self, text, **kwargs): Cell.__init__(self, **kwargs) if text is None: text = "" self.text = str(text) self.color = kwargs.get('color', '#ffffff') self.font = ImageFont.truetype(table_font, kwargs.get("font_size", 28)) self.border_color = kwargs.get('border_color', self.color) self.border_size = kwargs.get('border_size', 2) self.rotation = kwargs.get('rotation', 45) self.rotation_rad = math.radians(self.rotation) self.padding = get_padding(kwargs, [ 10, 10, 10, 10 ]) self.text_size = self.font.getsize(self.text) if not self.width: self.width = self.padding[1] + self.text_size[1] + self.padding[3] if not self.height: self.height = self.padding[0] + int(math.sin(self.rotation_rad) * self.text_size[0]) + self.text_size[1] + self.padding[2]
Example #5
Source File: tabledraw.py From MangoByte with MIT License | 6 votes |
def __init__(self, text, **kwargs): Cell.__init__(self, **kwargs) if text is None: text = "" self.text = str(text) if isinstance(text, int) and 'horizontal_align' not in kwargs: kwargs['horizontal_align'] = 'center' self.color = kwargs.get('color', '#ffffff') self.font = ImageFont.truetype(table_font, kwargs.get("font_size", 28)) self.wrap = kwargs.get('wrap', False) self.horizontal_align = kwargs.get('horizontal_align', 'left') # left center right self.vertical_align = kwargs.get('vertical_align', 'middle') # top middle bottom self.padding = get_padding(kwargs, [ 0, 5, 0, 5 ]) self.text_size = self.font.getsize(self.text) if not self.width: self.width = self.padding[1] + self.text_size[0] + self.padding[3] if not self.height: self.height = self.padding[0] + self.text_size[1] + self.padding[2]
Example #6
Source File: mapping.py From Zabbix-Network-Weathermap with GNU General Public License v3.0 | 6 votes |
def __init__(self, fontfile, x=0, y=0, palette=Palette().palette_default, fontsize=12, dt=True): self.x = x self.y = y self.width_palet = 30 self.height_palet = 20 self.yt = y + self.height_palet self.indent_x = 5 self.indent_y = 3 self.palette = palette self.text_label = 'Traffic Load' self.rect_xy = [] self.table_xy() self.text = ('0-0%', '0-1%', '1-10%', '10-25%', '25-40%', '40-55%', '55-70%', '70-85%', '85-100%') self.fontfile = fontfile self.fontcolor = 'black' self.fontsize = fontsize self.font = ImageFont.truetype(self.fontfile, size=self.fontsize) self.dt = dt self.dt_obj = None self.date_now = None self.time_now = None log.debug('Object Table created')
Example #7
Source File: polapizero_04.py From polapi-zero with MIT License | 6 votes |
def displayImageFileOnLCD(filename): print 'displays ', filename title = 'Review Mode' # resize/dither to screen resolution and send to LCD image = Image.open(filename) im_width, im_height = image.size if im_width < im_height: image = image.rotate(90) image.thumbnail(S_SIZE, Image.ANTIALIAS) image_sized = Image.new('RGB', S_SIZE, (0, 0, 0)) image_sized.paste(image,((S_SIZE[0] - image.size[0]) / 2, (S_SIZE[1] - image.size[1]) / 2)) # draw filename draw = ImageDraw.Draw(image_sized) font = ImageFont.truetype('arial.ttf', 18) draw.rectangle([(0, 0), (115, 22)], fill=(255,255,255), outline=(0,0,0)) draw.text((2, 2), title, fill='black', font=font) draw.rectangle([(279, 217), (399, 239)], fill=(255,255,255), outline=(0,0,0)) draw.text((290, 218), filename, fill='black', font=font) # display on LCD image_sized = ImageOps.invert(image_sized) image_sized = image_sized.convert('1') # convert image to black and white lcd.write(image_sized.tobytes())
Example #8
Source File: main.py From epd-library-python with GNU General Public License v3.0 | 6 votes |
def main(): epd = epd4in2b.EPD() epd.init() # For simplicity, the arguments are explicit numerical coordinates image_red = Image.new('1', (epd4in2b.EPD_WIDTH, epd4in2b.EPD_HEIGHT), 255) # 255: clear the frame draw_red = ImageDraw.Draw(image_red) image_black = Image.new('1', (epd4in2b.EPD_WIDTH, epd4in2b.EPD_HEIGHT), 255) # 255: clear the frame draw_black = ImageDraw.Draw(image_black) font = ImageFont.truetype('/usr/share/fonts/truetype/freefont/FreeMonoBold.ttf', 24) draw_black.rectangle((0, 6, 400, 30), fill = 0) draw_black.text((100, 10), 'e-Paper demo', font = font, fill = 255) draw_black.arc((40, 80, 180, 220), 0, 360, fill = 0) draw_red.rectangle((200, 80, 360, 280), fill = 0) draw_red.arc((240, 80, 380, 220), 0, 360, fill = 255) # display the frames epd.display_frame(epd.get_frame_buffer(image_black), epd.get_frame_buffer(image_red)) # display images frame_black = epd.get_frame_buffer(Image.open('black.bmp')) frame_red = epd.get_frame_buffer(Image.open('red.bmp')) epd.display_frame(frame_black, frame_red)
Example #9
Source File: work_vcode.py From TaiwanTrainVerificationCode2text with Apache License 2.0 | 6 votes |
def draw(self, image): fontpath = FONTPATH[ random.sample(range(2),1)[0] ] color = (self.color[0], self.color[1], self.color[2], 255) font = ImageFont.truetype( fontpath , randint(25, 27) * 10) text = Image.new("RGBA", (250, 300), (0, 0, 0, 0)) textdraw = ImageDraw.Draw(text) textdraw.text((0, 0), str(self.number), font=font, fill=color) #textdraw.text((0, 0), 'j', font=font, fill=color) text = text.rotate(self.angle, expand=True) text = text.resize((int(text.size[0] / 10), int(text.size[1] / 10))) base = int(self.priority * (200 / 6)) rand_min = (self.offset - base - 2) if (self.offset - base - 2) >= -15 else -15 rand_min = 0 if self.priority == 0 else rand_min rand_max = (33 - text.size[0]) if self.priority == 5 else (33 - text.size[0] + 10) try: displace = randint(rand_min, rand_max) except: displace = rand_max location = (base + displace, randint(3, 23)) self.next_offset = location[0] + text.size[0] image.paste(text, location, text) # plt.imshow(image)
Example #10
Source File: main copy.py From epd-library-python with GNU General Public License v3.0 | 6 votes |
def main(): epd = epd9in7.EPD() epd.init() # For simplicity, the arguments are explicit numerical coordinates image = Image.new('1', (EPD_WIDTH, EPD_HEIGHT), 1) # 1: clear the frame draw = ImageDraw.Draw(image) font = ImageFont.truetype('/usr/share/fonts/truetype/freefont/FreeMonoBold.ttf', 24) draw.rectangle((0, 6, 1200, 30), fill = 0) draw.text((200, 10), 'e-Paper demo', font = font, fill = 255) draw.rectangle((200, 80, 600, 280), fill = 0) draw.arc((240, 120, 580, 220), 0, 360, fill = 255) draw.rectangle((0, 80, 160, 280), fill = 255) draw.arc((40, 80, 180, 220), 0, 360, fill = 0) epd.display_frame(epd.get_frame_buffer(image)) image = Image.open('monocolor.bmp') epd.display_frame(epd.get_frame_buffer(image)) # You can get frame buffer from an image or import the buffer directly: #epd.display_frame(imagedata.MONOCOLOR_BITMAP)
Example #11
Source File: utils.py From PythonHomework with MIT License | 6 votes |
def draw_text( img: Image, text: str, location: tuple = (0, 0), text_color=(0, 0, 0) ) -> Image: draw = ImageDraw.Draw(img) try: # For Linux font = ImageFont.truetype("DejaVuSans.ttf", 20) except Exception: logger.warning("No font DejaVuSans; use default instead") # For others font = ImageFont.load_default() draw.text(location, text, font=font, fill=text_color) return img
Example #12
Source File: captcha.py From Jtyoui with MIT License | 6 votes |
def make_photo(self, dir_): """生成验证码 :param dir_: 存放验证码照片的文件夹 """ from PIL import Image # 安装pillow: pip install pillow from PIL import ImageFont from PIL import ImageDraw from PIL import ImageFilter image = Image.new('RGB', (self.width, self.height), (255, 255, 255)) font = ImageFont.truetype('arial.ttf', 36) draw = ImageDraw.Draw(image) for w in range(self.width): for h in range(self.height): draw.point((w, h), fill=self.color1()) for index, t in enumerate(self.flag): draw.text(((self.width - 10) // self.number * index + 10, 10), t, font=font, fill=self.color2()) image = image.filter(ImageFilter.BLUR) image.save(dir_ + sep + ''.join(self.flag) + '.jpg', 'jpeg') return image
Example #13
Source File: main.py From epd-library-python with GNU General Public License v3.0 | 6 votes |
def main(): epd = epd7in5b.EPD() epd.init() # For simplicity, the arguments are explicit numerical coordinates image = Image.new('L', (EPD_WIDTH, EPD_HEIGHT), 255) # 255: clear the frame draw = ImageDraw.Draw(image) font = ImageFont.truetype('/usr/share/fonts/truetype/freefont/FreeMonoBold.ttf', 24) draw.rectangle((0, 6, 640, 40), fill = 127) draw.text((200, 10), 'e-Paper demo', font = font, fill = 255) draw.rectangle((200, 80, 600, 280), fill = 127) draw.chord((240, 120, 580, 220), 0, 360, fill = 255) draw.rectangle((20, 80, 160, 280), fill = 0) draw.chord((40, 80, 180, 220), 0, 360, fill = 127) epd.display_frame(epd.get_frame_buffer(image)) image = Image.open('640x384.bmp') epd.display_frame(epd.get_frame_buffer(image)) # You can get frame buffer from an image or import the buffer directly: #epd.display_frame(imagedata.MONOCOLOR_BITMAP)
Example #14
Source File: main.py From epd-library-python with GNU General Public License v3.0 | 6 votes |
def main(): epd = epd2in7.EPD() epd.init() # For simplicity, the arguments are explicit numerical coordinates image = Image.new('1', (epd2in7.EPD_WIDTH, epd2in7.EPD_HEIGHT), 255) # 255: clear the image with white draw = ImageDraw.Draw(image) font = ImageFont.truetype('/usr/share/fonts/truetype/freefont/FreeMonoBold.ttf', 18) draw.text((20, 50), 'e-Paper demo', font = font, fill = 0) draw.rectangle((0, 76, 176, 96), fill = 0) draw.text((18, 80), 'Hello world!', font = font, fill = 255) draw.line((10, 130, 10, 180), fill = 0) draw.line((10, 130, 50, 130), fill = 0) draw.line((50, 130, 50, 180), fill = 0) draw.line((10, 180, 50, 180), fill = 0) draw.line((10, 130, 50, 180), fill = 0) draw.line((50, 130, 10, 180), fill = 0) draw.arc((90, 190, 150, 250), 0, 360, fill = 0) draw.chord((90, 120, 150, 180), 0, 360, fill = 0) draw.rectangle((10, 200, 50, 250), fill = 0) epd.display_frame(epd.get_frame_buffer(image)) # display images epd.display_frame(epd.get_frame_buffer(Image.open('monocolor.bmp')))
Example #15
Source File: main.py From epd-library-python with GNU General Public License v3.0 | 6 votes |
def main(): epd = epd4in2.EPD() epd.init() # For simplicity, the arguments are explicit numerical coordinates image = Image.new('1', (EPD_WIDTH, EPD_HEIGHT), 1) # 1: clear the frame draw = ImageDraw.Draw(image) font = ImageFont.truetype('/usr/share/fonts/truetype/freefont/FreeMonoBold.ttf', 24) draw.rectangle((0, 6, 400, 30), fill = 0) draw.text((100, 10), 'e-Paper demo', font = font, fill = 255) draw.rectangle((200, 80, 360, 280), fill = 0) draw.arc((240, 80, 380, 220), 0, 360, fill = 255) draw.rectangle((0, 80, 160, 280), fill = 255) draw.arc((40, 80, 180, 220), 0, 360, fill = 0) epd.display_frame(epd.get_frame_buffer(image)) image = Image.open('monocolor.bmp') epd.display_frame(epd.get_frame_buffer(image)) # You can get frame buffer from an image or import the buffer directly: #epd.display_frame(imagedata.MONOCOLOR_BITMAP)
Example #16
Source File: main.py From epd-library-python with GNU General Public License v3.0 | 6 votes |
def main(): epd = epd7in5.EPD() epd.init() # For simplicity, the arguments are explicit numerical coordinates image = Image.new('1', (EPD_WIDTH, EPD_HEIGHT), 1) # 1: clear the frame draw = ImageDraw.Draw(image) font = ImageFont.truetype('/usr/share/fonts/truetype/freefont/FreeMonoBold.ttf', 24) draw.rectangle((0, 6, 640, 30), fill = 0) draw.text((200, 10), 'e-Paper demo', font = font, fill = 255) draw.rectangle((200, 80, 600, 280), fill = 0) draw.arc((240, 120, 580, 220), 0, 360, fill = 255) draw.rectangle((0, 80, 160, 280), fill = 255) draw.arc((40, 80, 180, 220), 0, 360, fill = 0) epd.display_frame(epd.get_frame_buffer(image)) image = Image.open('monocolor.bmp') epd.display_frame(epd.get_frame_buffer(image)) # You can get frame buffer from an image or import the buffer directly: #epd.display_frame(imagedata.MONOCOLOR_BITMAP)
Example #17
Source File: line_generator.py From calamari with Apache License 2.0 | 6 votes |
def __init__(self, base_font_ttf: str, font_size: int): self.font_name = base_font_ttf if not base_font_ttf.endswith('.ttf') else base_font_ttf[:-4] self.default_font = Font(ImageFont.truetype(self.font_name + '.ttf', size=font_size)) def font_or_default(ttf): try: return Font(ImageFont.truetype(ttf, size=font_size)) except OSError: print("Error loading font {}. Using default font.".format(ttf)) return self.default_font self.variants = [ self.default_font, font_or_default(self.font_name + '-Bold.ttf'), font_or_default(self.font_name + '-Italic.ttf'), font_or_default(self.font_name + '-BoldItalic.ttf'), ]
Example #18
Source File: render_text_on_signs.py From stn-ocr with GNU General Public License v3.0 | 6 votes |
def find_font_size(draw, text_lines, max_width, max_height, spacing): # start with a default font size that should be large enough to be too large font_size = 35 # reload the font until the word fits or the font size would be too small while True: font = ImageFont.truetype(random.choice(FONTS), size=font_size, encoding='unic') text_width, text_height = draw.multiline_textsize(text_lines, font, spacing=spacing) if text_width <= max_width and text_height <= max_height: return font, (text_width, text_height) font_size -= 1 if font_size <= 1: raise ValueError('Can not draw Text on given image')
Example #19
Source File: lgtm.py From pyconjpbot with MIT License | 6 votes |
def get_font_size(size, font_file, text): """ 指定したテキストを画像に配置する時にいい感じのフォントサイズを返す :params size: 画像の幅と高さの短い方 :params font_file: フォントファイルのフルパス :params text: 描画する文字列(LGTM等) :return: フォントサイズ """ # フォントのサイズを5ポイント刻みで大きくする for font_size in range(10, 200, 5): font = ImageFont.truetype(font_file, font_size, encoding="utf-8") # テキストの描画サイズを取得 width, height = font.getsize(text) # テキストの幅が、画像の短い方の半分のサイズを越えたら終了 if width > size / 2: break return font_size
Example #20
Source File: demo.py From StackGAN with MIT License | 6 votes |
def drawCaption(img, caption): img_txt = Image.fromarray(img) # get a font fnt = ImageFont.truetype('Pillow/Tests/fonts/FreeMono.ttf', 50) # get a drawing context d = ImageDraw.Draw(img_txt) # draw text, half opacity d.text((10, 256), 'Stage-I', font=fnt, fill=(255, 255, 255, 255)) d.text((10, 512), 'Stage-II', font=fnt, fill=(255, 255, 255, 255)) if img.shape[0] > 832: d.text((10, 832), 'Stage-I', font=fnt, fill=(255, 255, 255, 255)) d.text((10, 1088), 'Stage-II', font=fnt, fill=(255, 255, 255, 255)) idx = caption.find(' ', 60) if idx == -1: d.text((256, 10), caption, font=fnt, fill=(255, 255, 255, 255)) else: cap1 = caption[:idx] cap2 = caption[idx+1:] d.text((256, 10), cap1, font=fnt, fill=(255, 255, 255, 255)) d.text((256, 60), cap2, font=fnt, fill=(255, 255, 255, 255)) return img_txt
Example #21
Source File: birds_skip_thought_demo.py From StackGAN with MIT License | 6 votes |
def drawCaption(img, caption): img_txt = Image.fromarray(img) # get a font fnt = ImageFont.truetype('Pillow/Tests/fonts/FreeMono.ttf', 50) # get a drawing context d = ImageDraw.Draw(img_txt) # draw text, half opacity d.text((10, 256), 'Stage-I', font=fnt, fill=(255, 255, 255, 255)) d.text((10, 512), 'Stage-II', font=fnt, fill=(255, 255, 255, 255)) if img.shape[0] > 832: d.text((10, 832), 'Stage-I', font=fnt, fill=(255, 255, 255, 255)) d.text((10, 1088), 'Stage-II', font=fnt, fill=(255, 255, 255, 255)) idx = caption.find(' ', 60) if idx == -1: d.text((256, 10), caption, font=fnt, fill=(255, 255, 255, 255)) else: cap1 = caption[:idx] cap2 = caption[idx+1:] d.text((256, 10), cap1, font=fnt, fill=(255, 255, 255, 255)) d.text((256, 60), cap2, font=fnt, fill=(255, 255, 255, 255)) return img_txt
Example #22
Source File: trainer.py From StackGAN with MIT License | 6 votes |
def drawCaption(self, img, caption): img_txt = Image.fromarray(img) # get a font fnt = ImageFont.truetype('Pillow/Tests/fonts/FreeMono.ttf', 50) # get a drawing context d = ImageDraw.Draw(img_txt) # draw text, half opacity d.text((10, 256), 'Stage-I', font=fnt, fill=(255, 255, 255, 255)) d.text((10, 512), 'Stage-II', font=fnt, fill=(255, 255, 255, 255)) if img.shape[0] > 832: d.text((10, 832), 'Stage-I', font=fnt, fill=(255, 255, 255, 255)) d.text((10, 1088), 'Stage-II', font=fnt, fill=(255, 255, 255, 255)) idx = caption.find(' ', 60) if idx == -1: d.text((256, 10), caption, font=fnt, fill=(255, 255, 255, 255)) else: cap1 = caption[:idx] cap2 = caption[idx+1:] d.text((256, 10), cap1, font=fnt, fill=(255, 255, 255, 255)) d.text((256, 60), cap2, font=fnt, fill=(255, 255, 255, 255)) return img_txt
Example #23
Source File: show_my_ip.py From unicorn-hat-hd with MIT License | 6 votes |
def create_image_from_text(in_text): colours = (255, 255, 250) font_file = '/usr/share/fonts/truetype/freefont/FreeSansBold.ttf' font_size = 12 font = ImageFont.truetype(font_file, font_size) w, h = font.getsize(in_text) text_x, text_y = width, 0 text_width, text_height = width, 0 text_width += w + width # add some padding so the ip scrolls off the unicorn hat text_height = max(text_height, h, 16) # no more than the size of the unicorn hat image = Image.new('RGB', (text_width, text_height), (0, 0, 0)) draw = ImageDraw.Draw(image) draw.text((text_x, text_y), in_text, colours, font=font) return (image, text_width) # DISPLAY
Example #24
Source File: gauge.py From Reinforcement-Learning-for-Self-Driving-Cars with Apache License 2.0 | 5 votes |
def get_font(font_path, font_size): try: font = ImageFont.truetype(font_path, font_size) except IOError: font = ImageFont.load_default() return font
Example #25
Source File: visualization.py From bop_toolkit with MIT License | 5 votes |
def write_text_on_image(im, txt_list, loc=(3, 0), color=(1.0, 1.0, 1.0), size=20): """Writes text info on an image. :param im: ndarray on which the text info will be written. :param txt_list: List of dictionaries, each describing one info line: - 'name': Entry name. - 'val': Entry value. - 'fmt': String format for the value. :param loc: Location of the top left corner of the text box. :param color: Font color. :param size: Font size. :return: Image with written text info. """ im_pil = Image.fromarray(im) # Load font. try: font_path = os.path.join(os.path.dirname(__file__), 'droid_sans_mono.ttf') font = ImageFont.truetype(font_path, size) except IOError: misc.log('Warning: Loading a fallback font.') font = ImageFont.load_default() draw = ImageDraw.Draw(im_pil) for info in txt_list: if info['name'] != '': txt_tpl = '{}:{' + info['fmt'] + '}' else: txt_tpl = '{}{' + info['fmt'] + '}' txt = txt_tpl.format(info['name'], info['val']) draw.text(loc, txt, fill=tuple([int(c * 255) for c in color]), font=font) text_width, text_height = font.getsize(txt) loc = (loc[0], loc[1] + text_height) del draw return np.array(im_pil)
Example #26
Source File: detection_3d_metrics.py From lingvo with Apache License 2.0 | 5 votes |
def DrawDifficulty(self, images, gt_bboxes, gt_box_weights, difficulties): """Draw the difficulty values on each ground truth box.""" batch_size = np.shape(images)[0] try: font = ImageFont.truetype('arial.ttf', size=20) except IOError: font = ImageFont.load_default() for batch_id in range(batch_size): image = images[batch_id, :, :, :] original_image = image image = Image.fromarray(np.uint8(original_image)).convert('RGB') draw = ImageDraw.Draw(image) difficulty_vector = difficulties[batch_id] box_data = gt_bboxes[batch_id] for box_id in range(box_data.shape[0]): box_weight = gt_box_weights[batch_id, box_id] if box_weight == 0: continue center_x = box_data[box_id, 0] center_y = box_data[box_id, 1] difficulty_value = str(difficulty_vector[box_id]) # Draw a rectangle background slightly larger than the text. text_width, text_height = font.getsize(difficulty_value) draw.rectangle( [(center_x - text_width / 1.8, center_y - text_height / 1.8), (center_x + text_width / 1.8, center_y + text_height / 1.8)], fill='darkcyan') # Center the text in the rectangle draw.text((center_x - text_width / 2, center_y - text_height / 2), str(difficulty_value), fill='lightcyan', font=font) np.copyto(original_image, np.array(image))
Example #27
Source File: draw.py From hexgen with GNU General Public License v3.0 | 5 votes |
def draw_hexagon(self, cx, cy, x, y): origin = (cx + HEX_RADIUS, cy) pointer = (cx + HEX_RECT_WIDTH, cy + HEX_HEIGHT) pointer_2 = (cx + HEX_RECT_WIDTH, cy + HEX_HEIGHT + SIDE_LENGTH) pointer_3 = (cx + HEX_RADIUS, cy + HEX_RECT_HEIGHT) pointer_4 = (cx, cy + SIDE_LENGTH + HEX_HEIGHT) pointer_5 = (cx, cy + HEX_HEIGHT) h = self.Grid.hex_grid.find_hex(x, y) self.draw.polygon([origin, pointer, pointer_2, pointer_3, pointer_4, pointer_5], outline=None, fill=self.color_func(h)) self.make_line(origin, pointer) self.make_line(pointer, pointer_2) self.make_line(pointer_2, pointer_3) self.make_line(pointer_3, pointer_4) self.make_line(pointer_4, pointer_5) self.make_line(pointer_5, origin) if self.numbers: self.draw.text((cx + 10, cy + 3), str(h.altitude), fill=(200, 200, 200)) self.draw.text((cx + 4, cy + 11), str(x), fill=(200, 200, 200)) self.draw.text((cx + 4, cy + 19), str(y), fill=(200, 200, 200)) self.draw.text((cx + 18, cy + 11), str(h.moisture), fill=(200, 200, 200)) self.draw.text((cx + 18, cy + 19), str(h.temperature), fill=(200, 200, 200)) if self.text_func: font = ImageFont.truetype("FreeSans.ttf", 14) self.draw.text((cx + 5, cy + 5), str(self.text_func(h)), fill=(200, 200, 200), font=font)
Example #28
Source File: img_utils.py From pdftotree with MIT License | 5 votes |
def lazy_load_font(font_size=default_font_size): """ Lazy loading font according to system platform """ if font_size not in _font_cache: if _platform.startswith("darwin"): font_path = "/Library/Fonts/Arial.ttf" elif _platform.startswith("linux"): font_path = "/usr/share/fonts/truetype/ubuntu-font-family/UbuntuMono-R.ttf" elif _platform.startswith("win32"): font_path = "C:\\Windows\\Fonts\\arial.ttf" _font_cache[font_size] = ImageFont.truetype(font_path, font_size) return _font_cache[font_size]
Example #29
Source File: fun.py From cyberdisc-bot with MIT License | 5 votes |
def create_text_image(self, ctx: Context, person: str, text: str): """ Creates an image of a given person with the specified text. """ if len(text) > 100: return await ctx.send( ":no_entry_sign: Your text must be shorter than 100 characters." ) drawing_text = textwrap.fill(text, 20) font = ImageFont.truetype("cdbot/resources/Dosis-SemiBold.ttf", 150) text_layer = Image.new("RGBA", (1920, 1080), (0, 0, 0, 0)) text_layer_drawing = ImageDraw.Draw(text_layer) text_layer_drawing.text( (0, 0), drawing_text, fill=(0, 0, 0), align="center", font=font ) cropped_text_layer = text_layer.crop(text_layer.getbbox()) cropped_text_layer.thumbnail((170, 110)) image = Image.open(f"cdbot/resources/{person}SaysBlank.png") x = int((image.width / 5 + 20) - (cropped_text_layer.width / 2)) y = int((image.height / 5 + 50 / 2) - (cropped_text_layer.height / 2)) image.paste(cropped_text_layer, (x, y), cropped_text_layer) image_bytes = BytesIO() image.save(image_bytes, format="PNG") image_bytes.seek(0) await ctx.send(file=File(image_bytes, filename=f"{person}.png"))
Example #30
Source File: lgtm.py From pyconjpbot with MIT License | 5 votes |
def generate_lgtm_image(im, text): """ LGTM画像を生成して返す :params im: PillowのImageオブジェクト :return: LGTM画像のImageオブジェクトのリスト """ # 画像が大きかったらリサイズする im.thumbnail((400, 400)) width, height = im.size # フォント生成 font_file = str(Path(__file__).parent / 'fonts' / FONT) font_size = get_font_size(min(width, height), font_file, text) font = ImageFont.truetype(font_file, font_size, encoding="utf-8") # テキストの描画位置の計算 x, y_center, y_top, y_bottom = get_text_xy(width, height, font, text) images = [] # 中央、上、下にテキストを描画する for y in y_center, y_top, y_bottom: copied_im = im.copy() images.append(copied_im) draw_im = ImageDraw.Draw(copied_im) # 枠線を描画 draw_im.text((x-1, y-1), text, font=font, fill=SHADOW) draw_im.text((x+1, y-1), text, font=font, fill=SHADOW) draw_im.text((x-1, y+1), text, font=font, fill=SHADOW) draw_im.text((x+1, y+1), text, font=font, fill=SHADOW) # テキストを描画 draw_im.text((x, y), text, font=font, fill=FILL) return images