本文整理汇总了Python中PIL.ImageFont.load_default方法的典型用法代码示例。如果您正苦于以下问题:Python ImageFont.load_default方法的具体用法?Python ImageFont.load_default怎么用?Python ImageFont.load_default使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PIL.ImageFont
的用法示例。
在下文中一共展示了ImageFont.load_default方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: draw_text
# 需要导入模块: from PIL import ImageFont [as 别名]
# 或者: from PIL.ImageFont import load_default [as 别名]
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
示例2: add_timestamp
# 需要导入模块: from PIL import ImageFont [as 别名]
# 或者: from PIL.ImageFont import load_default [as 别名]
def add_timestamp(image, timestamp, margin=2):
"""
Return an image object with timestamp bar added at the bottom.
param image: pillow image object
param timestamp: timestamp in seconds since the Epoch
param margin: timestamp margin, default is 2
"""
width, height = image.size
font = ImageFont.load_default()
watermark = time.strftime('%c', time.localtime(timestamp))
# bar height = text height + top margin + bottom margin
bar_height = font.getsize(watermark)[1] + 2 * margin
# place bar at the bottom
new_image = ImageOps.expand(image, border=(0, 0, 0, bar_height),
fill='lightgrey')
draw = ImageDraw.Draw(new_image)
# place timestamp at the left side of the bar
x, y = margin, height + margin
draw.text((x, y), watermark, font=font, fill='black')
return new_image
示例3: _draw_single_box
# 需要导入模块: from PIL import ImageFont [as 别名]
# 或者: from PIL.ImageFont import load_default [as 别名]
def _draw_single_box(image, xmin, ymin, xmax, ymax, display_str, color='black', color_text='black', thickness=2):
from PIL import ImageDraw, ImageFont
font = ImageFont.load_default()
draw = ImageDraw.Draw(image)
(left, right, top, bottom) = (xmin, xmax, ymin, ymax)
draw.line([(left, top), (left, bottom), (right, bottom),
(right, top), (left, top)], width=thickness, fill=color)
if display_str:
text_bottom = bottom
# Reverse list and print from bottom to top.
text_width, text_height = font.getsize(display_str)
margin = np.ceil(0.05 * text_height)
draw.rectangle(
[(left, text_bottom - text_height - 2 * margin),
(left + text_width, text_bottom)], fill=color
)
draw.text(
(left + margin, text_bottom - text_height - margin),
display_str, fill=color_text, font=font
)
return image
示例4: weather
# 需要导入模块: from PIL import ImageFont [as 别名]
# 或者: from PIL.ImageFont import load_default [as 别名]
def weather(debugStatus):
print("Starting live weather stream...")
TempDisp = 1
HumidDisp = 0
while GPIO.input(homeb) == True:
font = ImageFont.load_default()
url = "http://api.openweathermap.org/data/2.5/weather?id=524901&APPID=6d711345f94972e7ac62fc8f43cc648c&lat=24.19&lon=55.76"
fetched_data = requests.get(url)
fetched_data_json = fetched_data.json()
main_data = fetched_data_json.get('main')
current_tempK = main_data.get('temp')
current_humidity = main_data.get('humidity')
current_temp = round(current_tempK - 273, 1)
CurrTemp = int(current_temp)
FinalTemp = "Temperature: " + (str(current_temp))
FinalHumid = "Humidity: " + (str(current_humidity))
VisionEngine.disptext(FinalTemp, FinalHumid, " ", " ",0,0,0,0, 0, 12,24,36, debugStatus, '0')
示例5: create_watermark
# 需要导入模块: from PIL import ImageFont [as 别名]
# 或者: from PIL.ImageFont import load_default [as 别名]
def create_watermark(watermarked_by):
print('Creating a watermark')
mask = Image.new('L', WATERMARK_SIZE, 0)
draw = ImageDraw.Draw(mask)
font = ImageFont.load_default()
text = 'WATERMARKED BY {}\n{}'.format(watermarked_by, datetime.now())
draw.multiline_text((0, 100), text, 55, font=font)
watermark = Image.new('RGB', WATERMARK_SIZE)
watermark.putalpha(mask)
watermark = watermark.resize((1950, 1950))
watermark = watermark.rotate(45)
# Crop to only the watermark
bbox = watermark.getbbox()
watermark = watermark.crop(bbox)
return watermark
示例6: generate
# 需要导入模块: from PIL import ImageFont [as 别名]
# 或者: from PIL.ImageFont import load_default [as 别名]
def generate(cls, size, string, filetype="JPEG"):
"""
Generates a squared avatar with random background color.
:param size: size of the avatar, in pixels
:param string: string to be used to print text and seed the random
:param filetype: the file format of the image (i.e. JPEG, PNG)
"""
render_size = max(size, Avatar.MIN_RENDER_SIZE)
image = Image.new('RGB', (render_size, render_size),
cls._background_color(string))
draw = ImageDraw.Draw(image)
# font = cls._font(render_size)
font = ImageFont.load_default()
text = cls._text(string)
draw.text(cls._text_position(render_size, text, font),
text,
fill=cls.FONT_COLOR,
font=font)
stream = BytesIO()
image = image.resize((size, size), Image.ANTIALIAS)
image.save(stream, format=filetype, optimize=True)
return stream.getvalue()
示例7: load_font
# 需要导入模块: from PIL import ImageFont [as 别名]
# 或者: from PIL.ImageFont import load_default [as 别名]
def load_font(args, font_path, font_size, default_font_path):
"""Loads given font and defaults to fallback fonts if that fails."""
if args.is_verbose:
print("Loading font...")
fonts = [font_path] + FALLBACK_FONTS
if font_path == default_font_path:
for font in fonts:
if args.is_verbose:
print("Trying to load font:", font)
if os.path.exists(font):
try:
return ImageFont.truetype(font, font_size)
except OSError:
pass
print("Falling back to default font.")
return ImageFont.load_default()
else:
try:
return ImageFont.truetype(font_path, font_size)
except OSError:
error_exit("Cannot load font: {}".format(font_path))
示例8: task_8
# 需要导入模块: from PIL import ImageFont [as 别名]
# 或者: from PIL.ImageFont import load_default [as 别名]
def task_8(
img_url: str = 'https://i.imgur.com/B75zq0x.jpg'
) -> object:
'''
Task 8: Module
Args:
img_url: address of an image
Returns:
result_img: an PIL Image
Hints:
* Make sure you have installed the PIL package
* Take a look at utils.py first
* You could easily find answers with Google
'''
from PIL import Image, ImageFont, ImageDraw
from urllib import request
result_img = Image.open(request.urlopen(img_url))
draw = ImageDraw.Draw(result_img)
font = ImageFont.load_default().font
draw.text((0, 0), "B06902079", (0, 0, 0), font=font)
# TODO: download the image from img_url with the request module
# and add your student ID on it with draw_name() in the utils module
# under src/.
# You are allowed to change the img_url to your own image URL.
# Display the image:
# result_img.show()
# Note: please comment this line when hand in.
# If you are running on a server, use
# result.save('test.jpg')
# and copy the file to local or use Jupyter Notebook to render.
# End of TODO
return result_img
示例9: drawtext
# 需要导入模块: from PIL import ImageFont [as 别名]
# 或者: from PIL.ImageFont import load_default [as 别名]
def drawtext(img, pos, text, bgcolor=(255,255,255), font=None):
if font is None:
font = ImageFont.load_default().font
(tw, th) = font.getsize(text)
box_img = Image.new('RGB', (tw+2, th+2), bgcolor)
ImageDraw.Draw(box_img).text((0, 0), text, fill=(0,0,0,255), font=font)
if img.mode != 'RGB':
img = img.convert('RGB')
sx, sy = int(pos[0]),int(pos[1]-th-2)
if sx<0:
sx=0
if sy<0:
sy=0
img.paste(box_img, (sx, sy))
示例10: draw_copying_path
# 需要导入模块: from PIL import ImageFont [as 别名]
# 或者: from PIL.ImageFont import load_default [as 别名]
def draw_copying_path(self, filename, child_row, parents, breakpoints):
origin = self.haplotype_origin
b = self.box_size
m = self.num_sites
image = self.base_image.copy()
draw = ImageDraw.Draw(image)
y = self.row_map[child_row] * b + origin[1]
x = origin[0]
draw.rectangle(
[(x, y), (x + m * b, y + b)], outline=self.copying_outline_colour
)
for k in range(m):
if parents[k] != -1:
row = self.row_map[parents[k]]
y = row * b + origin[1]
x = k * b + origin[0]
a = self.ancestors[parents[k], k]
draw.rectangle([(x, y), (x + b, y + b)], fill=self.copy_colours[a])
for position in breakpoints:
x = self.x_coordinate_map[position]
y1 = origin[0] + self.row_map[0] * b
y2 = origin[1] + (self.row_map[len(self.row_map) - 1] + 1) * b
draw.line([(x, y1), (x, y2)], fill="black")
# Draw the positions of the sites.
font = ImageFont.load_default()
for site in self.original_ts.sites():
label = "{} {:.6f}".format(site.id, site.position)
img_txt = Image.new("L", font.getsize(label), color="white")
draw_txt = ImageDraw.Draw(img_txt)
draw_txt.text((0, 0), label, font=font)
t = img_txt.rotate(90, expand=1)
x = origin[0] + site.id * b
y = origin[1] - b
image.paste(t, (x, y))
# print("Saving", filename)
image.save(filename)
示例11: DrawDifficulty
# 需要导入模块: from PIL import ImageFont [as 别名]
# 或者: from PIL.ImageFont import load_default [as 别名]
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))
示例12: get_font
# 需要导入模块: from PIL import ImageFont [as 别名]
# 或者: from PIL.ImageFont import load_default [as 别名]
def get_font(font_path, font_size):
try:
font = ImageFont.truetype(font_path, font_size)
except IOError:
font = ImageFont.load_default()
return font
示例13: write_text_on_image
# 需要导入模块: from PIL import ImageFont [as 别名]
# 或者: from PIL.ImageFont import load_default [as 别名]
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)
示例14: draw_bounding_box
# 需要导入模块: from PIL import ImageFont [as 别名]
# 或者: from PIL.ImageFont import load_default [as 别名]
def draw_bounding_box(img, bbox, labels):
draw = ImageDraw.Draw(img)
font = ImageFont.load_default()
color = tuple(np.random.choice(range(100, 256), size=3))
draw.rectangle((bbox[0], bbox[1], bbox[2], bbox[3]), outline=color)
for i, k in enumerate(labels.keys()):
w, h = font.getsize(labels[k])
# draw.rectangle((bbox[0], bbox[1] + i*h, bbox[0] + w, bbox[1] + (i+2)*h), fill=color)
draw.text((bbox[0], bbox[1] + i*h), "{0}:{1:.3} ".format(k, labels[k]), fill=color)
return img
示例15: __init__
# 需要导入模块: from PIL import ImageFont [as 别名]
# 或者: from PIL.ImageFont import load_default [as 别名]
def __init__(self, width=50, height=12):
self.width = width
self.height = height
# 新图片对象
self.im = Image.new('RGB', (width, height), 'white')
# 字体
self.font = ImageFont.load_default()
# draw对象
self.draw = ImageDraw.Draw(self.im)