Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
iperov
GitHub Repository: iperov/deepfacelab
Path: blob/master/core/imagelib/text.py
628 views
1
import localization
2
import numpy as np
3
from PIL import Image, ImageDraw, ImageFont
4
5
pil_fonts = {}
6
def _get_pil_font (font, size):
7
global pil_fonts
8
try:
9
font_str_id = '%s_%d' % (font, size)
10
if font_str_id not in pil_fonts.keys():
11
pil_fonts[font_str_id] = ImageFont.truetype(font + ".ttf", size=size, encoding="unic")
12
pil_font = pil_fonts[font_str_id]
13
return pil_font
14
except:
15
return ImageFont.load_default()
16
17
def get_text_image( shape, text, color=(1,1,1), border=0.2, font=None):
18
h,w,c = shape
19
try:
20
pil_font = _get_pil_font( localization.get_default_ttf_font_name() , h-2)
21
22
canvas = Image.new('RGB', (w,h) , (0,0,0) )
23
draw = ImageDraw.Draw(canvas)
24
offset = ( 0, 0)
25
draw.text(offset, text, font=pil_font, fill=tuple((np.array(color)*255).astype(np.int)) )
26
27
result = np.asarray(canvas) / 255
28
29
if c > 3:
30
result = np.concatenate ( (result, np.ones ((h,w,c-3)) ), axis=-1 )
31
elif c < 3:
32
result = result[...,0:c]
33
return result
34
except:
35
return np.zeros ( (h,w,c) )
36
37
def draw_text( image, rect, text, color=(1,1,1), border=0.2, font=None):
38
h,w,c = image.shape
39
40
l,t,r,b = rect
41
l = np.clip (l, 0, w-1)
42
r = np.clip (r, 0, w-1)
43
t = np.clip (t, 0, h-1)
44
b = np.clip (b, 0, h-1)
45
46
image[t:b, l:r] += get_text_image ( (b-t,r-l,c) , text, color, border, font )
47
48
49
def draw_text_lines (image, rect, text_lines, color=(1,1,1), border=0.2, font=None):
50
text_lines_len = len(text_lines)
51
if text_lines_len == 0:
52
return
53
54
l,t,r,b = rect
55
h = b-t
56
h_per_line = h // text_lines_len
57
58
for i in range(0, text_lines_len):
59
draw_text (image, (l, i*h_per_line, r, (i+1)*h_per_line), text_lines[i], color, border, font)
60
61
def get_draw_text_lines ( image, rect, text_lines, color=(1,1,1), border=0.2, font=None):
62
image = np.zeros ( image.shape, dtype=np.float )
63
draw_text_lines ( image, rect, text_lines, color, border, font)
64
return image
65
66