python—PIL use

introduction

  PIL: The Python Imaging Library is already the de facto image processing standard library for the Python platform. The PIL function is very powerful, but the API is very simple and easy to use. Since PIL only supports Python 2.7 and it has been in disrepair for a long time, a group of volunteers created a compatible version on the basis of PIL, named Pillow, which supports the latest Python 3.x and added many new features. Therefore, we You can install and use Pillow directly.

One, install Pillow

  If Anaconda is installed, Pillow is already available. Otherwise, it needs to be installed via pip under the command line.
I use Anaconda+pycharm, the installation will appear as follows:

(base) C:\Users\admin>activate tf-gpu # 激活当前使用的虚拟环境

(tf-gpu) C:\Users\admin>pip install pillow # 安装
Requirement already satisfied: pillow in d:\softwares\anaconda3\envs\tf-gpu\lib\site-packages (8.0.1)

Second, the operation image

  The most common image zoom operation requires only three or four lines of code.

from PIL import Image

# 打开一个jpg图像文件,注意是当前路径:
im = Image.open('test.jpg')
# 获得图像尺寸:
w, h = im.size
print('Original image size: %sx%s' % (w, h))
# 缩放到50%:
im.thumbnail((w//2, h//2))
print('Resize image to: %sx%s' % (w//2, h//2))
# 把缩放后的图像用jpeg格式保存:
im.save('thumbnail.jpg', 'jpeg')

Other functions such as slice, rotate, filter, output text, palette, etc. are all available.
  The blur effect also requires only a few lines of code:

from PIL import Image, ImageFilter

# 打开一个jpg图像文件,注意是当前路径:
im = Image.open('test.jpg')
# 应用模糊滤镜:
im2 = im.filter(ImageFilter.BLUR)
im2.save('blur.jpg', 'jpeg')

Insert picture description here
  PIL's ImageDraw provides a series of drawing methods, allowing us to draw directly. For example, to generate a letter verification code image:

from PIL import Image, ImageDraw, ImageFont, ImageFilter

import random

# 随机字母:
def rndChar():
    return chr(random.randint(65, 90))

# 随机颜色1:
def rndColor():
    return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))

# 随机颜色2:
def rndColor2():
    return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))

# 240 x 60:
width = 60 * 4
height = 60
image = Image.new('RGB', (width, height), (255, 255, 255))
# 创建Font对象:(字体)
font = ImageFont.truetype('arial.ttf', 36)
# 创建Draw对象:
draw = ImageDraw.Draw(image)
# 填充每个像素:
for x in range(width):
    for y in range(height):
        draw.point((x, y), fill=rndColor())
# 输出文字:
for t in range(4):
    draw.text((60 * t + 10, 10), rndChar(), font=font, fill=rndColor2())
# 模糊:
image = image.filter(ImageFilter.BLUR)
image.save('code.jpg', 'jpeg')

Fill the background with random colors, then draw the text, and finally blur the image to get the verification code picture as follows:
Insert picture description here
  Define a function to save the image (save multiple images to one Image):

# 定义Image保存函数,将多张Image保存到一张Image里面去
def save_images(imgs,name):
    news_im = Image.new('L',(280,280))

    index = 0
    # 将10张Image保存到一张Image里面去
    for i in range(0,280,28):
        for j in range(0,280,28):
            im = imgs[index]
            im = Image.fromarray(im,mode='L')
            news_im.paste(im,(i,j))
            index += 1

        news_im.save(name)

Three, the above operation summary

Image.open(path)
Open the image file of path path
im = Image.open(path)

w, h = im.size to
obtain the size of the image instance

im.thumbnail((w_new, h_new))
scales the original image instance to a new size (w_new, h_new)

im.save('thumbnail.jpg','jpeg')
save the picture, the picture name is thumbnail.jpg, the format is'jpeg'

im.filter(ImageFilter.BLUR)
apply blur filter

Image.new(mode, size, color=0)
mode:https://pillow.readthedocs.io/en/stable/handbook/concepts.html#concept-modes
creates a new image with the given mode and size

Image.fromarray(obj, mode=None)
uses the given mode to convert an array object to an image object
obj – Object with array interface
mode – Mode to use (will be determined from type if None)

ImageFont.truetype(font=None, size=10, index=0, encoding='', layout_engine=None)
This function loads a font object from a given file or file-like object and creates it for a given size font A font object
font: font object
size: font size
index: font to be loaded

reference:

  1. Liao Xuefeng Tutorial
  2. Pillow official website

Guess you like

Origin blog.csdn.net/weixin_46649052/article/details/114256239