Skip to content
Advertisement

How to highlight part of image with Python Imaging Library (PIL)?

How can I highlight part of image? (Location defined as tuple of 4 numbers). You can imagine it like I have image of pc motherboard, and I need to highlight for example part where CPU Socket is located.

Advertisement

Answer

Note that for Python 3, you need to use the pillow fork of PIL, which is a mostly backwards compatible fork of the original module but, unlike it, is currently actively being maintained.

Here’s some sample code that shows how to do it using the PIL.ImageEnhance.Brightness class.

Doing what you want requires multiple steps:

  • The portion to be highlighted is cut out of — or cropped from — the image.
  • An instance of the Brightness class is created from this cropped image.
  • The cropped image is the lightened by calling the enhance() method of the Brightness instance.
  • The cropped and now lightened image is pasted back into the location it came from.

To make doing them all easier to repeat, below is a function named highlight_area() to perform them. Note that I’ve also added a bonus feature that will optionally outline the highlighted region with a colored border — which you can of course remove if you don’t need or want it.

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.

Here’s an example of using the function. The original image is shown on the left opposite the one resulting from calling the function on it with the values shown in the sample code.

before and after hightlighting

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement