【问题标题】:Rendering a unicode/ascii character to a numpy array将 unicode/ascii 字符渲染到 numpy 数组
【发布时间】:2018-02-07 09:53:29
【问题描述】:

我想问是否有一种简单有效的方法可以将给定字符呈现到 numpy 数组。我想要的是一个接受字符作为输入并返回一个numpy数组的函数,然后我可以将其用作plt.imshow()函数的参数。在互联网上真的找不到,除了几个需要大量依赖的解决方案,当这似乎是一件容易的事。

【问题讨论】:

  • 我不知道执行此操作的现成方法,但我的建议是找到一些 ascii 字符的图像,使用 scikit-image 将它们转换为二进制(阈值)然后你将自动拥有你的 numpy 数组。

标签: python arrays numpy unicode character


【解决方案1】:

我实现了自己的绘图函数,称为text_draw_np(...),它使用 PIL 库将任何文本(不仅是单个字母,甚至允许多行)绘制到 numpy RGB 数组。它支持文本的着色和拉伸(改变纵横比),还支持可选的间隙(文本周围的空白)删除功能。

要使用下一个代码安装一次pip模块python -m pip install pillow numpy matplotlib,这里matplotlib不是绘图功能本身所必需的,它仅用于测试。

用法/测试示例见代码末尾,就在我的函数之后。代码后还有用不同颜色、字体大小、宽度/高度和拉伸绘制不同字母/文本的示例。

绘制一个或多个字母的最简单用例是 result_numpy_array = text_draw_np('ABC', height = 200),这里生成的图像的高度是 200 像素。

函数接受下一个参数:

  1. text - Python 字符串,可以是一个字母,也可以是多个字母,甚至可以是多行('\n' 里面的字母可以分割行)。
  2. font - 包含字体的文件的文件名或路径(字符串)。字体可以是任何 TrueType 字体,默认情况下我使用来自路径 c:/windows/fonts/arial.ttf 的默认 Windows 字体 Arial,在 Linux/MacOS 上你应该更正这个路径,你也可能想从互联网上下载一些免费的 TrueType 字体,例如from here。也可能支持其他格式,均由 FreeType 库支持,但需要对代码 PIL.ImageFont.truetype(...) 进行单行修改。
  3. fontsize - 要使用的字体大小,大小以给定字体文件特定的单位表示。您只能指定fontsizewidth/height 之一。
  4. width/height - 以像素为单位指定,如果您同时指定两者,则绘制的文本将被拉伸以填充给定的宽度/高度。如果您仅指定其中任何一个(另一个为 None),则会自动计算另一个以保持纵横比,并且文本将不被拉伸。
  5. remove_gaps - 如果此参数为 True,则文本(背景)周围的多余空格将被删除。大多数字体都有额外的空格,例如小写字母m 顶部空间较大,大写字母T 顶部空间较小。需要该空间以使所有字母具有相同的高度,多行文本也需要空间以在行之间留出一些空间。如果 remove_gaps 为 False(这是默认值),则空间将保留在 Font Glyphs 给定的数量内。
  6. color - 前景色(默认为'black'),bg - 背景色(默认为'white'),两者都可以是常见的颜色字符串名称,如'red'/'green'/'blue',或RGB 元组,如 (0, 255, 0) 表示绿色。

Try it online!

def text_draw_np(text, *, width = None, height = None, fontsize = None, font = 'c:/windows/fonts/arial.ttf', bg = (255, 255, 255), color = (0, 0, 0), remove_gaps = False, cache = {}):
    import math, numpy as np, PIL.Image, PIL.ImageDraw, PIL.ImageFont, PIL.ImageColor
    def get_font(fname, size):
        key = ('font', fname, size)
        if key not in cache:
            cache[key] = PIL.ImageFont.truetype(fname, size = size, encoding = 'unic')
        return cache[key]
    def text_size(text, font):
        if 'tsd' not in cache:
            cache['tsi'] = PIL.Image.new('RGB', (1, 1))
            cache['tsd'] = PIL.ImageDraw.Draw(cache['tsi'])
        return cache['tsd'].textsize(text, font)
    if fontsize is not None:
        pil_font = get_font(font, fontsize)
        text_width, text_height = text_size(text, pil_font)
        width, height = text_width, text_height
    else:
        pil_font = get_font(font, 24)
        text_width, text_height = text_size(text, pil_font)
        assert width is not None or height is not None, (width, height)
        width, height = math.ceil(width) if width is not None else None, math.ceil(height) if height is not None else None
        pil_font = get_font(font, math.ceil(1.2 * 24 * max(
            ([width / text_width] if width is not None else []) +
            ([height / text_height] if height is not None else [])
        )))
        text_width, text_height = text_size(text, pil_font)
        if width is None:
            width = math.ceil(height * text_width / text_height)
        if height is None:
            height = math.ceil(width * text_height / text_width)
    canvas = PIL.Image.new('RGB', (text_width, text_height), bg)
    draw = PIL.ImageDraw.Draw(canvas)
    draw.text((0, 0), text, font = pil_font, fill = color)
    if remove_gaps:
        a = np.asarray(canvas)
        bg_rgb = PIL.ImageColor.getrgb(bg)
        b = np.zeros_like(a)
        b[:, :, 0] = bg_rgb[0]; b[:, :, 1] = bg_rgb[1]; b[:, :, 2] = bg_rgb[2]
        t0 = np.any((a != b).reshape(a.shape[0], -1), axis = -1)
        top, bot = np.flatnonzero(t0)[0], np.flatnonzero(t0)[-1]
        t0 = np.any((a != b).transpose(1, 0, 2).reshape(a.shape[1], -1), axis = -1)
        lef, rig = np.flatnonzero(t0)[0], np.flatnonzero(t0)[-1]
        a = a[top : bot, lef : rig]
        canvas = PIL.Image.fromarray(a)
    canvas = canvas.resize((width, height), PIL.Image.LANCZOS)
    return np.asarray(canvas)
    
import matplotlib.pyplot as plt, matplotlib
fig, axs = plt.subplots(3, 3, constrained_layout = True)
axs[0, 0].imshow(text_draw_np('A', height = 500), interpolation = 'lanczos')
axs[0, 1].imshow(text_draw_np('B', height = 500, color = 'white', bg = 'black'), interpolation = 'lanczos')
axs[0, 2].imshow(text_draw_np('0 Stretch,No-Gaps!', width = 500, height = 500, color = 'green', bg = 'magenta', remove_gaps = True), interpolation = 'lanczos')
axs[1, 0].imshow(text_draw_np('1 Stretch,No-Gaps!', width = 1500, height = 100, color = 'blue', bg = 'yellow', remove_gaps = True), interpolation = 'lanczos')
axs[1, 1].imshow(text_draw_np('2 Stretch,With-Gaps', width = 500, height = 200, color = 'red', bg = 'gray'), interpolation = 'lanczos')
axs[1, 2].imshow(text_draw_np('3 By-Height-300', height = 300, color = 'black', bg = 'lightgray'), interpolation = 'lanczos')
axs[2, 0].imshow(text_draw_np('4 By-FontSize-40', fontsize = 40, color = 'purple', bg = 'lightblue'), interpolation = 'lanczos')
axs[2, 1].imshow(text_draw_np(''.join([(chr(i) + ('' if (j + 1) % 7 != 0 else '\n')) for j, i in enumerate(range(ord('A'), ord('Z') + 1))]),
    fontsize = 40, font = 'c:/windows/fonts/cour.ttf'), interpolation = 'lanczos')
axs[2, 2].imshow(text_draw_np(''.join([(chr(i) + ('' if (j + 1) % 16 != 0 else '\n')) for j, i in enumerate(range(32, 128))]),
    fontsize = 40, font = 'c:/windows/fonts/cour.ttf'), interpolation = 'lanczos')
#plt.tight_layout(pad = 0.05, w_pad = 0.05, h_pad = 0.05)
plt.show()

输出:

【讨论】:

    【解决方案2】:

    ODL 有 text_phantom,它通过一些花里胡哨的功能做到了这一点。

    为了给您一个简化的实现,您可以使用PIL 库。具体来说你需要决定图片大小和字体大小,那么就比较简单了。

    from PIL import Image, ImageDraw, ImageFont
    import numpy as np
    
    def text_phantom(text, size):
        # Availability is platform dependent
        font = 'arial'
        
        # Create font
        pil_font = ImageFont.truetype(font + ".ttf", size=size // len(text),
                                      encoding="unic")
        text_width, text_height = pil_font.getsize(text)
    
        # create a blank canvas with extra space between lines
        canvas = Image.new('RGB', [size, size], (255, 255, 255))
    
        # draw the text onto the canvas
        draw = ImageDraw.Draw(canvas)
        offset = ((size - text_width) // 2,
                  (size - text_height) // 2)
        white = "#000000"
        draw.text(offset, text, font=pil_font, fill=white)
    
        # Convert the canvas into an array with values in [0, 1]
        return (255 - np.asarray(canvas)) / 255.0
    

    这给出了,例如:

    import matplotlib.pyplot as plt
    plt.imshow(text_phantom('A', 100))
    plt.imshow(text_phantom('Longer text', 100))
    

    【讨论】:

    • 有效,只是一个小错字:第一个测试字母应该是plt.imshow(text_phantom('A', 100)),因为size 不是一个数组。
    猜你喜欢
    • 2019-05-10
    • 2015-03-29
    • 2011-09-19
    • 1970-01-01
    • 2019-10-21
    • 1970-01-01
    • 1970-01-01
    • 2015-04-15
    • 2022-07-02
    相关资源
    最近更新 更多