栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python3 如何为图片添加文字 即粘即用

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python3 如何为图片添加文字 即粘即用

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
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/267547.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号