Python基础之PIL(pillow)模块实例

Python基础之PIL(pillow)模块实例

pillow模块内容繁杂,因此使用实例展示内容


##1. 安装PIL(windows)
方式一:打开cmd(管理员模式) — 输入“pip install pillow” — 自动下载安装 ---- 出现 “Successfully installed pillow-5.2.0”即安装成功
使用pip list可查看是否安装pillow

C:\Windows\system32>pip list
DEPRECATION: The default format will switch to columns in the future. You can use --format=(legacy|columns) (or define a format=(legacy|columns) in your pip.conf under the [list] section) to disable this warning.
asn1crypto (0.24.0)
cffi (1.11.5)
cryptography (2.2.2)
idna (2.7)
Pillow (5.2.0)
pip (9.0.1)
pycparser (2.18)
pygame (1.9.3)
PyMySQL (0.9.2)
setuptools (28.8.0)
six (1.11.0)

##2. 验证码生成实例

from PIL import Image, ImageDraw, ImageFont
import random

# 添加字母
def creatImg(width,height):
    # 偏移量x
    global x
    # 创建新的画布,透明度为完全透明
    img = Image.new("RGBA", (width, height), (0, 0, 0, 0))
    # 创建画笔
    draw = ImageDraw.Draw(img)
    font = ImageFont.truetype("img/code1.ttf", 50)
    # 创建随机字母并添加至列表
    char = chr(random.randint(65, 91))
    codeList.append(char)
    # 将字母随机写入画布中的指定范围内
    draw.text((x, random.randint(10, 15)), char, font=font, fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
    # 随机旋转[-10,10]度
    img = img.rotate(random.randint(-10, 10))
    # 下一个字符为偏移量
    x += 50
    return img

# 添加随机点
def addPoint(img):
    # 获取宽高
    width, height = img.size
    # 随机添加1000个随机颜色的点
    for i in range(1000):
        img.putpixel((random.randint(0, width-1), random.randint(0, height-1)), (random.randint(0, 100), random.randint(0, 100), random.randint(0, 100)))
    return img

# 创建最底层画布
code = Image.new("RGBA", (200, 100), (255, 255, 255, 255))
# 获取画布尺寸
w, h = code.size
# 创建空列表存放验证字符
codeList = []
# 根据x判定字母偏移量,起始位置为0
x = 0
# 循环创建随机字符图片并与底层画布合并
for i in range(4):
    img = creatImg(w, h)
    code = Image.alpha_composite(code, img)
# 增加随机点
code = addPoint(code)
# 展示验证码
code.show()
# 输出验证字符列表
print(codeList)

##3. 图片鉴黄(简易)

from PIL import Image

# 打开图片
img = Image.open("img/wxq.jpg")
# 将图片模式转化为YCbCr,Y代表亮度,Cb代表蓝色浓度偏移量,Cr代表红色浓度偏移量
img = img.convert("YCbCr")
# 获取图像大小
w, h = img.size
# 设定皮肤初始值
skin = 0
# 遍历图像中每一个像素
for m in range(w):
    for n in range(h):
        # 获取该像素的YCbCr
        y, cb, cr = img.getpixel((m, n))
        # 根据公式判断是否为裸露的皮肤,如果是则皮肤值+1
        if 77 <= cb <= 127 and 133 <= cr <= 173:
            skin += 1
# 遍历完成后判定是否皮肤值占总像素的40%以上,如果是则为不健康的图片(〃ノωノ)
if skin > (w * h) * 0.4:
    print("黄图,禁了!")
else:
    print("下一个!")

注:本实例根据某论文提供公式判定,但经过实测,如果使用本实例进行鉴黄,自拍照片都有可能被认为是黄图( ̄ω ̄;)

你可能感兴趣的:(Python)