请注意,对于 Python 3,您需要使用pillow https://pypi.org/project/Pillow/PIL 的分支,它是原始模块的一个主要向后兼容的分支,但与它不同的是,目前正在积极维护。
这是一些示例代码,展示了如何使用PIL.ImageEnhance.Brightness https://pillow.readthedocs.io/en/latest/reference/ImageEnhance.html#PIL.ImageEnhance.PIL.ImageEnhance.Brightness class.
做你想做的事需要多个步骤:
- 要突出显示的部分是从图像中剪切或裁剪出来的。
- 的一个实例
Brightness
类是根据这个裁剪后的图像创建的。
- 裁剪后的图像通过调用变亮
enhance()
的方法Brightness
实例。
- 裁剪后的、现在变亮的图像将被粘贴回其原来的位置。
为了使这些操作更容易重复,下面是一个名为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.
这是使用该函数的示例。原始图像显示在左侧,与使用示例代码中显示的值调用该函数所得到的图像相对。