使用PIL绘制多语言文本并保存为1位和8位位图

3
我从这个不错的答案开始。它对于“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

imtype = "1": 输入图像描述

imtype = "L": 输入图像描述

imtype = "RGB": 输入图像描述

1个回答

5

更新:

这个答案建议使用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")

你好!RGB 你好!8位 你好!1位80 你好!1位128


翻译:

看起来TrueType字体不支持低于RGB的颜色模式。

您可以尝试使用PIL的.convert()方法将图像转换为其他模式。

从RGB图像开始,可以得到以下结果:

image.convert("L"): 输入图像描述

image.convert("1"): 输入图像描述

将图像转换为8位灰度图像效果很好,但是如果从TrueType字体或任何基于灰度的字体开始,1位转换始终会显得粗糙。

要获得漂亮的1位图像,可能需要使用专门为数字显示设计的1位位图中文字体。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接