pil示例

Image最重要的类.

>>> from PIL import Image
>>> im = Image.open("hopper.ppm")

检查属性:

>>> print(im.format, im.size, im.mode)
PPM (512, 512) RGB
>>> im.show()
//显示

转换为png

import os, sys
from PIL import Image

for infile in sys.argv[1:]:
    f, e = os.path.splitext(infile)
    outfile = f + ".jpg"
    if infile != outfile:
        try:
            with Image.open(infile) as im:
                im.save(outfile)
//保存文件.
        except OSError:
            print("不能转换", infile)

创建缩略图

import os, sys
from PIL import Image

size = (128, 128)

for infile in sys.argv[1:]:
    outfile = os.path.splitext(infile)[0] + ".thumbnail"
    if infile != outfile:
        try:
            with Image.open(infile) as im:
                im.thumbnail(size)
                im.save(outfile, "JPEG")
        except OSError:
            print("失败", infile)

识别图像文件

import sys
from PIL import Image

for infile in sys.argv[1:]:
    try:
        with Image.open(infile) as im:
            print(infile, im.format, f"{im.size}x{im.mode}")
    except OSError:
        pass

剪切、粘贴和合并图像

box = (100, 100, 400, 400)
region = im.crop(box)
//
region = region.transpose(Image.Transpose.ROTATE_180)
im.paste(region, box)

滚动图像

def roll(im, delta):
    """滚动"""
    xsize, ysize = im.size
    delta = delta % xsize
    if delta == 0:
        return im

    part1 = im.crop((0, 0, delta, ysize))
    part2 = im.crop((delta, 0, xsize, ysize))
    im.paste(part1, (xsize - delta, 0, xsize, ysize))
    im.paste(part2, (0, 0, xsize - delta, ysize))

    return im

合并图像

def merge(im1, im2):
    w = im1.size[0] + im2.size[0]
    h = max(im1.size[1], im2.size[1])
    im = Image.new("RGBA", (w, h))

    im.paste(im1)
    im.paste(im2, (im1.size[0], 0))

    return im

分割

r, g, b = im.split()
im = Image.merge("RGB", (b, g, r))

几何变换

out = im.resize((128, 128))
out = im.rotate(45) 
//旋转

转置

out = im.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
out = im.transpose(Image.Transpose.FLIP_TOP_BOTTOM)
out = im.transpose(Image.Transpose.ROTATE_90)
out = im.transpose(Image.Transpose.ROTATE_180)
out = im.transpose(Image.Transpose.ROTATE_270)

模式变换

from PIL import Image

with Image.open("hopper.ppm") as im:
    im = im.convert("L")

过滤

from PIL import ImageFilter
out = im.filter(ImageFilter.DETAIL)

操作点

# 都乘1.2
out = im.point(lambda i: i * 1.2)

多带

source = im.split()

R, G, B = 0, 1, 2

mask = source[R].point(lambda i: i < 100 and 255)
out = source[G].point(lambda i: i * 0.7)
source[G].paste(out, None, mask)
im = Image.merge(im.mode, source)
//掩码
imout = im.point(lambda i: expression and 255)

增强

from PIL import ImageEnhance

enh = ImageEnhance.Contrast(im)
enh.enhance(1.3).show("30%对比")

读取序列

from PIL import Image

with Image.open("animation.gif") as im:
    im.seek(1)  
// 跳过第2个

    try:
        while 1:
            im.seek(im.tell() + 1)
//干活
    except EOFError:
        pass  //序列外

图像序列迭代

from PIL import ImageSequence
for frame in ImageSequence.Iterator(im):
//干活.

画ps

from PIL import Image
from PIL import PSDraw

with Image.open("hopper.ppm") as im:
    title = "hopper"
    box = (1 * 72, 2 * 72, 7 * 72, 10 * 72)  # in points

    ps = PSDraw.PSDraw()
    ps.begin_document(title)

    //#画
    ps.image(box, im, 75)
    ps.rectangle(box)

    //画标题
    ps.setfont("HelveticaNarrow-Bold", 36)
    ps.text((3 * 72, 4 * 72), title)

    ps.end_document()

打开文件中读

from PIL import Image

with open("hopper.ppm", "rb") as fp:
    im = Image.open(fp)

从二进制中读

from PIL import Image
import io

im = Image.open(io.BytesIO(buffer))

从url中读

from PIL import Image
from urllib.request import urlopen
url = "https://python-pillow.org/images/pillow-logo.png"
img = Image.open(urlopen(url))

从tar中读

from PIL import Image, TarIO

fp = TarIO.TarIO("Tests/images/hopper.tar", "hopper.jpg")
im = Image.open(fp)

批处理

import glob
from PIL import Image

def compress_image(source_path, dest_path):
    with Image.open(source_path) as img:
        if img.mode != "RGB":
            img = img.convert("RGB")
        img.save(dest_path, "JPEG", optimize=True, quality=80)


paths = glob.glob("*.png")
for path in paths:
    compress_image(path, path[:-4] + ".jpg")
//
from pathlib import Path
paths = Path(".").glob("*.png")
for path in paths:
    compress_image(path, path.stem + ".jpg")

你可能感兴趣的:(python,python,pil,示例)