我从 this nice answer 中的脚本开始.它适用于“RGB”,但 8 位灰度“L”和 1 位黑/白“1”PIL 图像模式只是显示为黑色。我做错了什么?
from PIL import Image, ImageDraw, ImageFont
import numpy as np
w_disp = 128
h_disp = 64
fontsize = 32
text = u"你好!"
for imtype in "1", "L", "RGB":
image = Image.new(imtype, (w_disp, h_disp))
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("/Library/Fonts/Arial Unicode.ttf", fontsize)
w, h = draw.textsize(text, font=font)
draw.text(((w_disp - w)/2, (h_disp - h)/2), text, font=font)
image.save("NiHao! 2 " + imtype + ".bmp")
data = np.array(list(image.getdata()))
print data.shape, data.dtype, "min=", data.min(), "max=", data.max()
输出:
(8192,) int64 min= 0 max= 0
(8192,) int64 min= 0 max= 0
(8192, 3) int64 min= 0 max= 255
最佳答案
更新:
This answer建议使用 PIL 的 Image.point()
方法代替 .convert()
。
整体看起来是这样的:
from PIL import Image, ImageDraw, ImageFont
import numpy as np
w_disp = 128
h_disp = 64
fontsize = 32
text = u"你好!"
imageRGB = Image.new('RGB', (w_disp, h_disp))
draw = ImageDraw.Draw(imageRGB)
font = ImageFont.truetype("/Library/Fonts/Arial Unicode.ttf", fontsize)
w, h = draw.textsize(text, font=font)
draw.text(((w_disp - w)/2, (h_disp - h)/2), text, font=font)
image8bit = imageRGB.convert("L")
imageRGB.save("NiHao! RGB.bmp")
image8bit.save("NiHao! 8bit.bmp")
imagenice_80 = image8bit.point(lambda x: 0 if x < 80 else 1, mode='1')
imagenice_128 = image8bit.point(lambda x: 0 if x < 128 else 1, mode='1')
imagenice_80.save("NiHao! nice 1bit 80.bmp")
imagenice_128.save("NiHao! nice 1bit 128.bmp")
原创:
看起来 TrueType 字体不想使用 RGB 以外的字体。
您可以尝试使用 PIL 的 .convert()
方法对图像进行下转换。
从 RGB 图像开始,这给出:
转换为 8 位灰度效果很好,但从 TrueType 字体或任何基于灰度的字体开始,1 位转换看起来总是很粗糙。
为了好看的 1 位图像,可能有必要从为数字开/关显示器设计的 1 位位图中文字体开始。
关于python-2.7 - 使用 PIL 绘制多语言文本并保存为 1 位和 8 位位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47545359/