def create_img(font_name: str simsun.ttc , char: str None, width 64, height 64, font_size 64, random_location True, noise True):
创建图片。
Parameters
----------
font_name : str, optional
字体文件全路径, by default simsun.ttc
char : str, optional
文本 为 None 时随机汉字、数字、符号或字母, by default None
width : int, optional
图片宽度, by default 64
height : int, optional
图片高度, by default 64
font_size : int, optional
文字高度, by default 64
random_location : bool, optional
是否随机化文字位置, by default True
noise : bool, optional
是否添加噪声, by default True
Returns
-------
np.ndarray, str
图片和文字。
if char is None:
char rand_char()
fsize int(font_size*(random.rand()*.2 .9))
offset int(font_size*.1)
font ImageFont.truetype(font_name, fsize, encoding unic )
w, h font.getsize(char)
bg Image.new( L , (width, height), color #000000 )
while True:
fore Image.new( L , (int(width*1.5), int(height*1.5)), color #000000 )
wp, hp fore.size
draw ImageDraw.Draw(fore)
if random_location:
loc ((wp - w) / 2 random.randint(-offset, offset 1), (hp - h) / 2 random.randint(-offset, offset 1))
else:
loc ((wp - w) / 2, (hp - h) / 2)
draw.text(loc, char, fill #ffffff , font font)
for x in [1, 0, -1]:
for y in [1, 0, -1]:
if x 0 and y 0:
continue
char_ rand_char()
if x 0 and y 0:
tmp_w, tmp_h w, h
else:
tmp_w, tmp_h font.getsize(char_)
draw.text((loc[0] x*tmp_w, loc[1] y*tmp_h), char_, fill #ffffff , font font)
if random_location:
warpR mat(
random.randint(-14, 15), random.randint(-14, 15),
random.randint(-14, 15), random.randint(0, 75),
wp, hp
fore cv2.warpPerspective(np.array(fore), warpR, (hp, wp))
bg np.array(fore)[int(height*.25):int(height*.25) width, int(width*.25):int(width*.25) height]
if np.sum(bg) 0:
continue
break
if noise and random.rand() .05:
noise_img random.randn(int(height*.85), int(width*.85))*224
noise_img Image.fromarray(noise_img, L ).resize((width, height))
alpha .75*random.rand()
noise_img alpha*np.array(noise_img)
bg bg * np.array(noise_img)
bg bg noise_img
bg np.where(bg 255, 255, bg)
return bg, char