【问题标题】:How to highlight part of image with Python Imaging Library (PIL)?如何使用 Python 图像库 (PIL) 突出显示部分图像?
【发布时间】:2020-08-28 16:19:09
【问题描述】:

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

【问题讨论】:

  • 看起来PIL 已经死了——似乎没有发布 Python 3 版本。另一方面,似乎有一个来自PIL 的分支,称为Pillow (pillow.readthedocs.io/en/stable),看起来是最新的。
  • @AmitaiIrron:人们经常称 Pillow 为 PIL。

标签: python image python-imaging-library highlight


【解决方案1】:

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

这里有一些示例代码,展示了如何使用 PIL.ImageEnhance.Brightness 类来实现。

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

  • 要突出显示的部分从图像中剪下或裁剪。
  • Brightness 类的一个实例是根据这个裁剪的图像创建的。
  • 通过调用Brightness 实例的enhance() 方法使裁剪后的图像变亮。
  • 裁剪后变亮的图像被粘贴回原来的位置。

为了让它们更容易重复,下面是一个名为highlight_area() 的函数来执行它们。 请注意,我还添加了一个奖励功能,它可以选择用彩色边框勾勒突出显示的区域 - 如果您不需要或不想要它,当然可以将其删除。

from PIL import Image, ImageColor, ImageDraw, ImageEnhance


def highlight_area(img, region, factor, outline_color=None, outline_width=1):
    """ Highlight specified rectangular region of image by `factor` with an
        optional colored  boarder drawn around its edges and return the result.
    """
    img = img.copy()  # Avoid changing original image.
    img_crop = img.crop(region)

    brightner = ImageEnhance.Brightness(img_crop)
    img_crop = brightner.enhance(factor)

    img.paste(img_crop, region)

    # Optionally draw a colored outline around the edge of the rectangular region.
    if outline_color:
        draw = ImageDraw.Draw(img)  # Create a drawing context.
        left, upper, right, lower = region  # Get bounds.
        coords = [(left, upper), (right, upper), (right, lower), (left, lower),
                  (left, upper)]
        draw.line(coords, fill=outline_color, width=outline_width)

    return img


if __name__ == '__main__':

    img = Image.open('motherboard.jpg')

    red = ImageColor.getrgb('red')
    cpu_socket_region = 110, 67, 274, 295
    img2 = highlight_area(img, cpu_socket_region, 2.5, outline_color=red, outline_width=2)

    img2.save('motherboard_with_cpu_socket_highlighted.jpg')
    img2.show()  # Display the result.

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-30
    • 1970-01-01
    • 1970-01-01
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    • 2019-09-24
    • 1970-01-01
    相关资源
    最近更新 更多