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

标签 python image python-imaging-library highlight

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

最佳答案

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

这里有一些示例代码,展示了如何使用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.

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

before and after hightlighting

关于python - 如何使用Python图像库(PIL)突出显示图像的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61758263/

相关文章:

python - 简单的Python函数跟踪

python - Pandas 数据框从窄到宽,数据透视表没有聚合

java - 如何使用 apache poi 将背景图像设置为居中

python - 如何更改图像的不透明度并在 Python 中与另一个图像合并

Python PIL - 画圆

python - 包含数字的 python 包名称是否可以接受?

python - sqlalchemy:根据条件联合查询多个表中的几列

image - 如何区分原始.BMP/.EMF图片文件与处理后的.BMP/.EMF文件之间的区别?

HTML - 扩展名错误的图像

python - 在 Python 中寻找用于基本图像文件 I/O 和处理的 PIL 的更好替代方案?