Python 将文本作为图像获取的有效方法?

Python 将文本作为图像获取的有效方法?,python,matplotlib,Python,Matplotlib,我有一个机器学习任务,我需要创建由表示为灰度图像的短文本字符串组成的训练数据。最后,我想要2D numpy数组中的数据。我目前的方法是使用matplotlib在空白轴上写入生成的文本,然后使用一些技巧将底层数据捕获到numpy数组中。不过这有点慢,matplotlib会为每个示例显示和删除图形(我确实隐藏了图形,但没有显示)。有没有更有效的方法?虽然有各种方法,但您可以尝试使用 使用枕头(称为PIL),您可以控制要绘制的文本/数字、其大小、字体、位置和背景颜色等。 枕头网站可以提供更多的选择,以

我有一个机器学习任务,我需要创建由表示为灰度图像的短文本字符串组成的训练数据。最后,我想要2D numpy数组中的数据。我目前的方法是使用matplotlib在空白轴上写入生成的文本,然后使用一些技巧将底层数据捕获到numpy数组中。不过这有点慢,matplotlib会为每个示例显示和删除图形(我确实隐藏了图形,但没有显示)。有没有更有效的方法?

虽然有各种方法,但您可以尝试使用

使用枕头(称为PIL),您可以控制要绘制的文本/数字、其大小、字体、位置和背景颜色等。 枕头网站可以提供更多的选择,以建立一个强大和多样的数据集

您可以根据自己的要求更改常数

这是工作代码-我们正在为文本“100”创建图像

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

#Number to draw
number_to_draw = "100"

#define image width , height and color
image_width, image_height = (300,200)
image_background = "grey"

#Set font size and type
fontsize = 35
font = ImageFont.truetype('/Library/Fonts/Arial.ttf', 45)

#prep image
im = Image.new("L",(image_width,image_height),image_background)

#Convert to numpy array
im2arr = np.array(im)
print(im2arr)

#Draw image
draw = ImageDraw.Draw(im)

#Set position and draw image
w, h = draw.textsize(number_to_draw)
draw.text(((image_width-w)/2,(image_height-h)/2), number_to_draw, font=font)

#Save to file
im.save("100.png", "PNG")

#show image to screen
im.show()
输出和保存图像

$python text2image.py 
[[128 128 128 ... 128 128 128]
 [128 128 128 ... 128 128 128]
 [128 128 128 ... 128 128 128]
 ...
 [128 128 128 ... 128 128 128]
 [128 128 128 ... 128 128 128]
 [128 128 128 ... 128 128 128]]

欢迎来到StackOverflow,而且。。。在这里申请。StackOverflow是针对特定编程问题的知识库,而不是设计、编码、研究或教程资源。这是应用程序设计中一个非常广泛的问题。谢谢。有没有一种方法可以直接进入numpy阵列而不首先保存到磁盘?我也可以自己研究这个…是的-非常简单。只需导入numpy并将im转换为arry
将numpy作为np导入
im2arr=np.array(im)
。答复也相应更新。