通过python让打印出来的字体看起来像手写

老婆因工作原因要写书写大量文字,时间久了手累到瘫痪

某天在zhihu上看到一篇文章https://www.zhihu.com/question/20308770(如何让打印出来的字体看起来像手写的?)

其中一位Gsllchb介绍了python的Handright

https://github.com/Gsllchb/Handright

研究了一下感觉十分符合需求,生成的字迹,每个字都会有细微的差别,排好序后直接打印看起来是真的像手写

在原作者的基础上简单修改了一下代码,直接从word的docx文档直接读取内容

from PIL import Image, ImageFont

from handright import Template, handwrite

import docx

# 自动缩进排版,如果已在word里设置缩进可以注释本段
# indent_size控制缩进,file_path文档路径
def get_text(file_path, indent_size=4):  
    doc = docx.Document(file_path)
    texts = []
    indent = ''
    for i in range(0, indent_size):
        indent = indent + ' '
    for paragraph in doc.paragraphs:
        texts.append(indent + paragraph.text)
    return '\n'.join(texts)

# 根目录下的word文档
text = get_text('1.docx') 


template = Template(
    background=Image.open('016.jpg'),  # 自定义背景图片
    font_size=100,
    font=ImageFont.truetype("path/to/my/font.ttf"), # 字体选择手写体
    line_spacing=150,
    fill=(0, 0, 0),  # 字体颜色,括号内为RGB的值
    left_margin=100,
    top_margin=100,
    right_margin=100,
    bottom_margin=100,
    word_spacing=15,
    line_spacing_sigma=6,  # 行间距随机扰动
    font_size_sigma=20,  # 字体大小随机扰动
    word_spacing_sigma=3,  # 字间距随机扰动
    end_chars=",。",  # 防止特定字符因排版算法的自动换行而出现在行首
    perturb_x_sigma=4,  # 笔画横向偏移随机扰动
    perturb_y_sigma=4,  # 笔画纵向偏移随机扰动
    perturb_theta_sigma=0.05,  # 笔画旋转偏移随机扰动
)
images = handwrite(text, template)
for i, im in enumerate(images):
    assert isinstance(im, Image.Image)
    im.show()
    im.save("{}.jpg".format(i))  # 生成的图片生成在当前目录下

 

  • 12
    点赞
  • 51
    收藏
    觉得还不错? 一键收藏
  • 32
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 32
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值