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

2024-10-01 15:32:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我用PIL给一些图片加水印,我很难阅读其中的一些文字(黑色背景的黑色文字)。我不能只改变文本颜色,因为我有很多背景颜色。有没有办法在文本周围添加光环效果?在

例如: http://i.imgur.com/WYxSU.jpg 下面的文字是我得到的,上面的文字是我希望得到的(颜色除外)。我真的只需要在课文周围画一个轮廓。有什么想法吗?我可以上传一些代码,如果你真的认为这会有所不同,但这只是一个正常的PIL图像绘制。绘制命令。谢谢!在


Tags: 文本comhttppil颜色绘制图片背景
1条回答
网友
1楼 · 发布于 2024-10-01 15:32:08

如果你不太在意速度,你可以使用合成:

  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来获得不同的“光环”
  • 它甚至可以使用非常大的字体,而且看起来仍然很棒

要获得更厚的光环,可以使用如下过滤器:

^{pr2}$

部分scale = 0.1 * sum(kernel)使光晕变厚(小值)或暗(大值)。在

相关问题 更多 >

    热门问题