使用 PIL 和 truetype 字体在文本中抖动
考虑以下代码: from PIL import Image, ImageDraw, ImageFont
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
正如您所看到的,输出图像在文本周围包含大量红色噪点。如何消除这种抖动?
Consider the following code:
from PIL import Image, ImageDraw, ImageFont
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')
Here are the input and the output files
This is the input
input http://img16.imageshack.us/img16/8229/73936270.png
and this is the output
output http://img94.imageshack.us/img94/531/outj.png
As you may see, the output image contains a lot of reddish noise around the text. How can I eliminate this dithering?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议将中间文本图像写入文件(文本,然后是旋转文本),以隔离人工制品首次出现的位置。
另一种可能性可能是 png 编码使用没有灰度值的调色板,因此这些红色是最接近的可用颜色。我在 imageshack 上检查了文件的编码,看起来没问题,所以我不认为这是问题所在。
I suggest writing the intermediate text images to file (the text, then the rotated text), to isolate where the artefacts first appear.
One other possibility could be that the png encoding is using a pallete with no grayscale values, so those reds are the closest available. I checked the encoding of the files on imageshack though, and it seemed okay, so I don't think this is the problem.