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("下一個!")

注:本實例根據某論文提供公式判定,但經過實測,如果使用本實例進行鑑黃,自拍照片都有可能被認爲是黃圖( ̄ω ̄;)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章