Pillow 是一个强大的图像处理库,这里学习记录几个图像处理示例.

Python库 - PIL 之 Image 模块 - AIUAI

Python - 利用PIL添加图片水印 - AIUAI

[1] - 图像转换为灰度图.

from PIL import Image

img_pil = Image.open("test.jpg")
img_pil = img_pil.convert("1")

img_pil.save("test_grayscale.jpg")
img_pil.show()

[2] - 更换颜色,如白色像素替换为黄色.

from PIL import Image

img_pil = Image.open("test.jpg").convert("RGB")

new_image_data = []
for item in img_pil.getdata():
    #
    if item[0] in list(range(190, 256)):
        new_image_data.append((255, 204, 100))
    else:
        new_image_data.append(item)
#
img_pil.putdata(new_image_data)
img_pil.save("test_background.jpg")
img_pil.show()

[3] - 图像加边缘

from PIL import Image, ImageOps

img_pil = Image.open("test.jpg")

# border color
color = "red"
# top, right, bottom, left
border = (10, 5, 6, 8)
new_img = ImageOps.expand(img_pil, border=border, fill=color)
new_img.save("test_border.jpg")
new_img.show()

如:

[4] - 图像边缘模糊

from PIL import Image, ImageFilter

img_pil = Image.open("test.jpg")

#
radius, diameter = 20, 40
blur_size = (img_pil.size[0] + diameter, img_pil.size[1] + diameter)
blur_pil = Image.new('RGB', blur_size, (255, 255, 255))
blur_pil.paste(img_pil, (radius, radius))

#
mask_size = (img_pil.size[0] + diameter, img_pil.size[1] + diameter)
mask = Image.new('L', mask_size, 255)
black_size = (img_pil.size[0] - diameter, img_pil.size[1] - diameter)
black = Image.new('L', black_size, 0)
#
mask.paste(black, (diameter, diameter))
#
blur = blur_pil.filter(ImageFilter.GaussianBlur(radius / 2))
blur_pil.paste(blur, mask=mask)
blur_pil.save("test_blurred.jpg", quality=100)
blur_pil.show()

如:

Last modification:January 4th, 2021 at 03:10 pm