繁体   English   中英

使用 PIL 在 Python 中围绕文本创建光环?

[英]Create a halo around text in Python using PIL?

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

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

如果你不太关心速度,你可以使用组合来做到:

  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)使光晕更厚(小值)或变暗(大值)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM