如何使用Python图像库(PIL)突出显示图像的一部分?

del*_*zzz 2 python image highlight python-imaging-library

如何突出显示图像的一部分?(位置定义为 4 个数字的元组)。你可以想象它就像我有电脑主板的图像,我需要突出显示例如CPU插槽所在的部分。

mar*_*eau 5

请注意,对于 Python 3,您需要使用PIL 的枕头分叉,它是原始模块的主要向后兼容的分叉,但与它不同的是,目前正在积极维护。

\n\n

下面是一些示例代码,展示了如何使用该类来完成此操作PIL.ImageEnhance.Brightness

\n\n

做你想做的事需要多个步骤:

\n\n
    \n
  • 要突出显示的部分是从图像的 \xe2\x80\x94 中剪切出来或从 \xe2\x80\x94 中裁剪出来的。
  • \n
  • 该类的实例Brightness是根据该裁剪后的图像创建的。
  • \n
  • enhance()通过调用实例的方法对裁剪后的图像进行增亮处理Brightness
  • \n
  • 裁剪后的、现在变亮的图像将被粘贴回其原来的位置。
  • \n
\n\n

为了使所有这些操作更容易重复,下面是一个名为highlight_area()执行它们的函数。\n请注意,我还添加了一个额外功能,该功能可以选择使用彩色边框 \xe2\x80\x94 勾勒出突出显示的区域,您可以当然,如果您不需要或不想要它,请将其删除。

\n\n
from PIL import Image, ImageColor, ImageDraw, ImageEnhance\n\n\ndef highlight_area(img, region, factor, outline_color=None, outline_width=1):\n    """ Highlight specified rectangular region of image by `factor` with an\n        optional colored  boarder drawn around its edges and return the result.\n    """\n    img = img.copy()  # Avoid changing original image.\n    img_crop = img.crop(region)\n\n    brightner = ImageEnhance.Brightness(img_crop)\n    img_crop = brightner.enhance(factor)\n\n    img.paste(img_crop, region)\n\n    # Optionally draw a colored outline around the edge of the rectangular region.\n    if outline_color:\n        draw = ImageDraw.Draw(img)  # Create a drawing context.\n        left, upper, right, lower = region  # Get bounds.\n        coords = [(left, upper), (right, upper), (right, lower), (left, lower),\n                  (left, upper)]\n        draw.line(coords, fill=outline_color, width=outline_width)\n\n    return img\n\n\nif __name__ == \'__main__\':\n\n    img = Image.open(\'motherboard.jpg\')\n\n    red = ImageColor.getrgb(\'red\')\n    cpu_socket_region = 110, 67, 274, 295\n    img2 = highlight_area(img, cpu_socket_region, 2.5, outline_color=red, outline_width=2)\n\n    img2.save(\'motherboard_with_cpu_socket_highlighted.jpg\')\n    img2.show()  # Display the result.\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是使用该函数的示例。原始图像显示在左侧,与使用示例代码中显示的值调用该函数所得到的图像相对。

\n\n

突出显示之前和之后

\n