6

我正在使用 PIL 为一些图片添加水印,但我很难阅读一些文本(深色背景上的黑色文本)。我不能只更改文本颜色,因为我有多种背景颜色。有什么方法可以在文本周围添加光环效果?

例如: http: //i.imgur.com/WYxSU.jpg 底部的文字是我得到的,顶部的文字是我希望得到的(除了颜色)。我真的只需要在文本周围画一个细轮廓。有任何想法吗?如果您真的认为它会有所作为,我可以上传一些代码,但这只是一个普通的 PIL ImageDraw.Draw 命令。谢谢!

4

1 回答 1

12

如果您不太关心速度,可以使用组合来完成:

  1. RGBA在空白图像上绘制带有光晕颜色的文本
  2. 模糊它
  3. 用文字颜色再次绘制
  4. 反转此图像以获得合成蒙版
  5. 与原始图像“合并”

例如:

import sys
import Image, ImageChops, ImageDraw, ImageFont, ImageFilter

def draw_text_with_halo(img, position, text, font, col, halo_col):
    halo = Image.new('RGBA', img.size, (0, 0, 0, 0))
    ImageDraw.Draw(halo).text(position, text, font = font, fill = halo_col)
    blurred_halo = halo.filter(ImageFilter.BLUR)
    ImageDraw.Draw(blurred_halo).text(position, text, font = font, fill = col)
    return Image.composite(img, blurred_halo, ImageChops.invert(blurred_halo))

if __name__ == '__main__':
    i = Image.open(sys.argv[1])
    font = ImageFont.load_default()
    txt = 'Example 1234'
    text_col = (0, 255, 0) # bright green
    halo_col = (0, 0, 0)   # black
    i2 = draw_text_with_halo(i, (20, 20), txt, font, text_col, halo_col)
    i2.save('halo.png')

它有很多优点:

  • 结果很光滑,看起来不错
  • 您可以选择不同的过滤器而不是BLUR获得不同的“光环”
  • 它甚至可以使用非常大的字体并且看起来仍然很棒

要获得更厚的光环,您可以使用这样的过滤器:

kernel = [
    0, 1, 2, 1, 0,
    1, 2, 4, 2, 1,
    2, 4, 8, 4, 1,
    1, 2, 4, 2, 1,
    0, 1, 2, 1, 0]
kernelsum = sum(kernel)
myfilter = ImageFilter.Kernel((5, 5), kernel, scale = 0.1 * sum(kernel))
blurred_halo = halo.filter(myfilter)

该零件scale = 0.1 * sum(kernel)使光晕变厚(小值)或变暗(大值)。

于 2012-08-17T17:02:56.227 回答