PIL 库介绍与简单应用

PIL 库是什么?

PIL 库是一种图像处理库,是一个操作简单功能强大的图形处理标准库。
下面介绍一下如何用 PIL 对一个图片进行简单的处理。

简单操作

打开图片

在处理图片之前,我们首先要打开或者叫载入图片:

from PIL import Image

image_path = '/Users/admin/Desktop/image.PNG'
im = Image.open(image_path)

Image.open(path) ---->image
该方法返回 image 类,另外还可以用 im.show() 方法打开该图像。

处理图像

  • 改变像素
#打印图片的像素
print(im.size)
#将图片像素以高质量的方式改为x,y
im01 = im.resize((x,y),Image.ANTIALIAS)
  • 滤镜
from PIL.ImageFilter import BLUR, EMBOSS,EDGE_ENHANCE,DETAIL,CONTOUR

#模糊
im02 = im.filter(BLUR)
im02.show()

#浮雕
im03 = im.filter(EMBOSS)
im03.show()

#边界增强
im04 = im.filter(EDGE_ENHANCE)
im04.show()

#细节
im05 = im.filter(DETAIL)
im05.show()

#轮廓
im06 = im.filter(CONTOUR)
im06.show()

生成图像

#Image.new(mode,size,color)  ----->image类

#生成一个尺寸为 (750,1335)的红色图像
im07 = Image.new('RGB',(750,1335),'RED')
im07.show()

保存

im.save('/Users/admin/Desktop/image.PNG','PNG')

实例 -----验证码的制作

import random
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from PIL.ImageFilter import BLUR


font_path = '/Users/admin/Desktop/font/noteworthy/Noteworthy-Bold.ttf'

# 获得随机颜色
def get_color():
    #返回随机一组三原色
    x = random.randint(0,255)
    y = random.randint(0,255)
    z = random.randint(0,255)
    color = (x,y,z)
    #print(color)
    return color

def get_char():
    #返回一个随机的字符
    random_num = str(random.randint(0,9))
    random_low_char = chr(random.randint(97,122))
    random_uper_char = chr(random.randint(65,90))
    random_char = random.choice([random_num,random_low_char,random_uper_char])
    return random_char


# 创建一个(120,60)的随机颜色图案
im01 = Image.new('RGB',(120,60),get_color())
#将图案载入画布
draw = ImageDraw.Draw(im01)
#载入字体文件
fonts = ImageFont.truetype(font_path,size=32)
#画上字体
for i in range(4):
    draw.text((21+20*i ,8),get_char(),font=fonts,fill=get_color())
#噪点处理
for i in range(20):
    draw.point([random.randint(0, 120), random.randint(0, 60)], fill=get_color())
    x = random.randint(0, 120)
    y = random.randint(0, 60)
    draw.arc((x, y, x + 4, y + 4), 0, 90, fill=get_color())
#画线
for i in range(5):
    x1=random.randint(0,120)
    x2=random.randint(0,120)
    y1=random.randint(0,60)
    y2=random.randint(0,60)
    draw.line((x1,y1,x2,y2),fill=get_color())
#模糊
im01.filter(BLUR)

im01.show()

得到:

你可能感兴趣的:(Image库,python)