Quickly learn python image processing library Pillow and simple cases

What is Pillow

First of all, we need to understand PIL (Python Imaging Library), which is a very powerful image processing standard library in Python2, but only supports Python2.7. Pillow creates a compatible version based on PIL, supports the latest Python 3.x, and adds many new features.

Install

pip install pillow

Among them, Image is a commonly used module of the pillow library, which provides many image processing methods.

Simple use of pillow image processing

Picture information display

from PIL import Image # 操作图片的类型


# 加载图片
image = Image.open('test1.jpg')


# 打开图片
# image.show()

# 查看图像大小(宽度,高度)(6621, 4414)
print(image.size)

# # 获取模式
print(image.mode) # RGB
#
# # 显示的文件的格式 JPEG
print(image.format)
#
# # 图片的详细信息{'jfif': 257, nsity': (72, 72......), 
print(image.info)
#
# # 保存为另一张图片(可以更改图片的格式)
image.save('test2.bmp')

edit picture

Modify image size

from PIL import Image, ImageFilter

# 读取图片
image = Image.open('test.jpg')
print(image.size)
# 修改图片的尺寸,以像素为单位)以二元组表示:(宽度,高度)
image1 = image.resize((image.size[0]//3, image.size[1]//3))
#
image1.show()
# #
# 保存下来
image1.save('test.jpg')

Crop rotated image

from PIL import Image, ImageFilter

# 读取图片
image = Image.open('test1.jpg')
# 裁剪图片
# 设置一个边缘间距[left, upper, right, lower] 左上角和右下角
image1 = image.crop(box=(0, 0, 2000, 2000)) # 600 * 336
image1.show()
# 图片旋转
image2 = image.rotate(45)
image2.show()

Add watermark to pictures

You can add a QR code to a picture

from PIL import Image

# 读取图片
image = Image.open('test.jpg')

# 读取粘贴的图片
paste_image = Image.open('erweima.jpg')
如果需要粘贴的图片较大,可以通过resize()修改一下尺寸
image.paste(paste_image) # 默认把图片粘贴到左上角
image.show()

22c75caedaedd0ecf93e3ad896e196a1.png


from PIL import Image

# 读取图片
image = Image.open('test.jpg')

# 读取粘贴的图片
paste_image = Image.open('erweima.jpg')
# 也可以指定需要粘贴的位置 设置二维码位置为右下角
position = (image.size[0] - paste_image.size[0], image.size[1] - paste_image.size[1])
image.paste(paste_image,position)
image.show()
image.save("syzp.jpg")

3a27c2b4133157e9ee4eeb84f8238254.png

Generate gif image

from PIL import Image

images = []
for i in range(5):
    im = Image.open('mkgif/{}.png'.format(i + 1))
    images.append(im)
images[0].save("test.gif", save_all=True, loop=True, append_images=images[1:], duration=500)

b8a394dc23a5ba92ccab36368395193f.png

c28f9ff84002ffab5694c0677fd8a565.gif

The above are some simple uses of pillow, for other more uses, you can refer to the official document
https://pillow.readthedocs.io/en/stable/

Guess you like

Origin blog.csdn.net/XingLongSKY/article/details/120520661