使用PIL和真字库在文本中进行抖动处理
考虑以下代码:
从PIL库导入图像、绘图和字体
def addText(img, lTxt):
FONT_SIZE = 10
INTERLINE_DISTANCE = FONT_SIZE + 1
font = ImageFont.truetype('arial.ttf', FONT_SIZE)
lTxtImageHeight = INTERLINE_DISTANCE * len(lTxt)
# create text image
lTxtImg = Image.new('RGBA', (img.size[1], lTxtImageHeight), 255)
lTxtImgDraw = ImageDraw.Draw(lTxtImg, )
for (i, line) in enumerate(lTxt):
lTxtImgDraw.text((5, i * INTERLINE_DISTANCE), line, font=font, fill='#000000')
# rotate text image
lTxtImg = lTxtImg.rotate(90)
# create new transparent image ret
ret = Image.new('RGBA', (img.size[0] + lTxtImageHeight, img.size[1]), 255)
# paste the image to ret
ret.paste(img, (0,0))
# paste the text to ret
ret.paste(lTxtImg, (img.size[0], 0), lTxtImg)
return ret
img = Image.open('in.png')
addText(img, ['lorem', 'ipsum', 'dolores']).save('out.png')
这是输入文件:
输入文件链接 http://img16.imageshack.us/img16/8229/73936270.png
这是输出文件:
输出文件链接 http://img94.imageshack.us/img94/531/outj.png
你可能会注意到,输出的图像在文字周围有很多红色的噪点。如何才能消除这种杂色呢?
1 个回答
0
我建议把中间的文本图像保存到文件里(先保存文本,然后保存旋转后的文本),这样可以更清楚地找到问题出现的地方。
还有一种可能性是,png格式的编码使用了没有灰度值的调色板,所以那些红色是最接近的选择。不过我在imageshack上检查了文件的编码,感觉没问题,所以我觉得这不是原因。