Create a halo around text in Python using PIL?

I use watermarks using PIL and it is difficult for me to read part of the text (black text on a dark background). I cannot just change the color of the text, since I have a wide range of background colors. Is there a way to add a halo effect around the text?

For example: http://i.imgur.com/WYxSU.jpg The lower text is what I have, and the upper text is what I hope to get (color to the side). I really need a thin outline around the text. Any ideas? I can download some code if you really think it will matter, but this is just a normal PIL ImageDraw.Draw command. Thank you

+5
source share
1 answer

, :

  • - RGBA image
  • ,
  • "merge"

:

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) ( ) ( ).

+7

All Articles