我想询问是否有一种简单有效的方法将给定字符呈现为numpy数组.我想要的是一个接受字符作为输入的函数,并返回一个numpy数组,然后我可以将其用作plt.imshow()函数的参数.除了几个需要很多依赖性的解决方案之外,在互联网上真的找不到它,这似乎是一件容易的事. 最佳答案 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, 100]))
plt.imshow(text_phantom('Longer text', 100))