使用 PIL 得到文字信息,并转成 numpy 数据

背景:

有时候,我们希望在某一些图片上,打上水印,因此,需要使用 PIL 产生 Numpy data 进行图片处理。
因此,写了一个 根据 输入文字生成 numpy 的函数。

代码如下。

#!/usr/bin/python

import os
import numpy as np
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw


def get_font_txt_size(txt, font_size=12):
    """ 根据文字信息,得到文字的宽高 """
    # common_folder = os.path.dirname(os.path.dirname(__file__))
    common_folder = r'C:\Windows\Fonts'
    ttf_file = os.path.join(common_folder, r'REFSAN.TTF')
    assert os.path.exists(ttf_file), r'ttf 文件不存在 {}'.format(ttf_file)

    # get txt width and height
    font = ImageFont.truetype(ttf_file, font_size)
    width, height = font.getsize(txt)
    width = int(width / 8 + 1) * 8
    height = int(height / 8 + 1) * 8
    return font, width, height


def get_binary_data(txt, font_size=12):
    """ 根据文字信息产生 numpy 数据 """

    # 得到 font, width, height
    font, txt_width, txt_height = get_font_txt_size(txt, font_size)

    # ImageFont.truetype
    im = Image.new("RGB", (txt_width, txt_height))
    draw = ImageDraw.Draw(im)
    draw.text((0, 0), txt, font=font)

    # rgb image -> binary image
    binary_im = np.sum(np.array(im), axis=2)
    binary_im = (binary_im > 0).astype(np.uint8)
    return binary_im


if __name__ == '__main__':

    txt_data = get_binary_data('hello')
    print(txt_data)

测试结果

numpy 正确的打印出来。注意: 这个路径是需要修改的。
‘’‘common_folder = r’C:\Windows\Fonts’’

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值