背景:
有时候,我们希望在某一些图片上,打上水印,因此,需要使用 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’’