gpt4 book ai didi

python - 将 unicode/ascii 字符呈现为 numpy 数组

转载 作者:太空宇宙 更新时间:2023-11-03 11:42:42 25 4
gpt4 key购买 nike

我想问一下是否有一种简单有效的方法可以将给定字符呈现为 numpy 数组。我想要的是一个函数,它接受一个字符作为输入,并返回一个 numpy 数组,然后我可以将其用作 plt.imshow() 函数的参数。除了一些需要大量依赖项的解决方案外,在 Internet 上真的找不到它,而这似乎是一项简单的任务。

最佳答案

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))

enter image description here enter image description here

关于python - 将 unicode/ascii 字符呈现为 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45947608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com