PIL-图像处理

参考:
1、https://python-pillow.org/
2、https://github.com/python-pillow/Pillow
3、http://pillow.readthedocs.io/en/4.3.x/

  • 1使用Image类
    • 加载图像
  • 2读写图像
    • 将文件转换为JPEG
    • 创建JPEG缩略图
    • 识别图像文件
  • 3剪切粘贴合并图像
    • 从图像复制子矩形
    • 处理一个子矩形并将其粘贴回来
    • 滚动图像
    • 波段拆分和合并
  • 4几何变换
    • 简单的几何变换
    • Transposing an image
  • 5颜色变换
    • 转换模式
  • 6图像增强
    • 滤波
      • 使用滤波器
    • 点操作
      • 应用点变换
      • 单个波段处理
    • 增强
      • 图像增强
    • 图像序列
      • 读取序列
      • 使用ImageSequence迭代器类
  • 7Postscript printing
    • 绘画后记
  • 8More on reading images
    • Reading from an open file
    • Reading from a string
    • 从tar存档读取
  • 9控制解码器
    • Reading in draft mode

1、使用Image类

加载图像

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

from __future__ import print_function

from PIL import Image

im=Image.open('Lenna.png') # 打开图像

print(type(im)) # 

print(im.format, im.size, im.mode) # PNG (512, 512) P

im.show()

2、读写图像

将文件转换为JPEG

from __future__ import print_function
import os, sys
from PIL import Image

for infile in sys.argv[1:]:
    f, e = os.path.splitext(infile)
    outfile = f + ".jpg"  # ".tif" 保存成tif格式
    if infile != outfile:
        try:
            Image.open(infile).save(outfile)
        except IOError:
            print("cannot convert", infile)

创建JPEG缩略图

from __future__ import print_function
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:
            im = Image.open(infile)
            im.thumbnail(size)
            im.save(outfile, "JPEG")
        except IOError:
            print("cannot create thumbnail for", infile)

识别图像文件

from __future__ import print_function
import sys
from PIL import Image

for infile in sys.argv[1:]:
    try:
        with Image.open(infile) as im:
            print(infile, im.format, "%dx%d" % im.size, im.mode)
    except IOError:
        pass

3、剪切、粘贴、合并图像

从图像复制子矩形

box = (100, 100, 400, 400)
region = im.crop(box)

处理一个子矩形,并将其粘贴回来

region = region.transpose(Image.ROTATE_180) # 旋转180度
im.paste(region, box)

完整代码:

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

from __future__ import print_function
import os, sys
from PIL import Image


im=Image.open('Lenna.png')
box = (100, 100, 400, 400)
region = im.crop(box)

region = region.transpose(Image.ROTATE_180) # 旋转180度
im.paste(region, box)

im.show()

滚动图像

def roll(image, delta):
    "Roll an image sideways"

    xsize, ysize = image.size

    delta = delta % xsize
    if delta == 0: return image

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

    return image

波段拆分和合并

r, g, b = im.split() # 灰度图像返回是其本身
im = Image.merge("RGB", (b, g, r))

4、几何变换

简单的几何变换

out = im.resize((128, 128)) # 调整大小
out = im.rotate(45) # degrees counter-clockwise # 逆时针旋转

Transposing an image

out = im.transpose(Image.FLIP_LEFT_RIGHT) # 左右翻转
out = im.transpose(Image.FLIP_TOP_BOTTOM) # 上下翻转
out = im.transpose(Image.ROTATE_90) # 逆时针旋转90度
out = im.transpose(Image.ROTATE_180)# 逆时针旋转180度
out = im.transpose(Image.ROTATE_270)# 逆时针旋转270度

5、颜色变换

转换模式

from PIL import Image
im = Image.open("hopper.ppm").convert("L") # 转成灰度图

6、图像增强

、滤波

使用滤波器

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

点操作

应用点变换

# multiply each pixel by 1.2
out = im.point(lambda i: i * 1.2)

单个波段处理

# split the image into individual bands
source = im.split()

R, G, B = 0, 1, 2

# select regions where red is less than 100
mask = source[R].point(lambda i: i < 100 and 255)

# process the green band
out = source[G].point(lambda i: i * 0.7)

# paste the processed band back, but only where red was < 100
source[G].paste(out, None, mask)

# build a new multiband image
im = Image.merge(im.mode, source)

增强

图像增强

from PIL import ImageEnhance

enh = ImageEnhance.Contrast(im)
enh.enhance(1.3).show("30% more contrast")

图像序列

读取序列

from PIL import Image

im = Image.open("animation.gif")
im.seek(1) # skip to the second frame

try:
    while 1:
        im.seek(im.tell()+1)
        # do something to im
except EOFError:
    pass # end of sequence

使用ImageSequence迭代器类

from PIL import ImageSequence
for frame in ImageSequence.Iterator(im):
    # ...do something to frame...

7、Postscript printing

绘画后记

from PIL import Image
from PIL import PSDraw

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

ps = PSDraw.PSDraw() # default is sys.stdout
ps.begin_document(title)

# draw the image (75 dpi)
ps.image(box, im, 75)
ps.rectangle(box)

# draw title
ps.setfont("HelveticaNarrow-Bold", 36)
ps.text((3*72, 4*72), title)

ps.end_document()

8、More on reading images

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

Reading from an open file

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

Reading from a string

import StringIO

im = Image.open(StringIO.StringIO(buffer))

从tar存档读取

from PIL import Image, TarIO

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

9、控制解码器

Reading in draft mode

from PIL import Image
from PIL import PSDraw

im = Image.open("home.jpg")
print("original =", im.mode, im.size)
# original = RGB (512, 384)

im.draft("L", (100, 100))
print("draft =", im.mode, im.size)
# draft = L (256, 192)
im.show()

你可能感兴趣的:(图像处理,PIL,图像处理,PIL)