码迷,mamicode.com
首页 > 其他好文 > 详细

Pillow tutorial

时间:2018-04-28 19:21:16      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:div   .text   region   end   otto   ack   ==   seq   bottom   

from PIL import Image
im = Image.open("hopper.ppm")
from __future__ import print_function
print(im.format, im.size, im.mode)
#打应结果
PPM (512, 512) RGB

  让图片显示,im.show(),因为打开是暂时的所以显示图片效果不太好,而且还有15功能,所以一般用来测试显示

改变图片的后缀,pil可以根据文件内容,自己判断文件类型

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"
    if infile != outfile:
        try:
            Image.open(infile).save(outfile)
        except IOError:
            print("cannot convert", infile)

 

Create JPEG thumbnails

如果后缀不合法会用第二个参数

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)

  

Identify Image Files

先打开文件确认类型,读取/解析会在稍后执行

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

  

Copying a subrectangle from an image

截取图片大小, (left, upper, right, lower),坐标 (0, 0) in the upper left corner,准确来说是300*300pixeels

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

  把图片反转180度再填回去

region = region.transpose(Image.ROTATE_180)
im.paste(region, box)
  

  

Rolling an image

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))
#load是因为crop是个延迟操作,不这样会在第二步保存不到
    part1.load()
    part2.load()
    image.paste(part2, (0, 0, xsize-delta, ysize))
    image.paste(part1, (xsize-delta, 0, xsize, ysize))

    return image

  

Splitting and merging bands

拆分成原生三原色,换位置再合并

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

  简单的几何逆时针旋转,transpose也可以在90度内旋转,也可以水平活垂直旋转

out = im.resize((128, 128))
out = im.rotate(45)
out = im.transpose(Image.FLIP_LEFT_RIGHT)
out = im.transpose(Image.FLIP_TOP_BOTTOM)
out = im.transpose(Image.ROTATE_90)
out = im.transpose(Image.ROTATE_180)
out = im.transpose(Image.ROTATE_270)

  不通像素之间图片

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

  增强图像

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

  改变对比度

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

  循环播放

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

  在打印机上打印

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()

  也可以这样打开

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

在一个比较大的tar文件中打开图片,可以通过seek和read增快找到速度

from PIL import Image, TarIO

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

This is only available for JPEG and MPO files.

from PIL import Image
from __future__ import print_function
im = Image.open(file)
print("original =", im.mode, im.size)

im.draft("L", (100, 100))
print("draft =", im.mode, im.size)


#This prints something like:
original = RGB (512, 512)
draft = L (128, 128)

  

Pillow tutorial

标签:div   .text   region   end   otto   ack   ==   seq   bottom   

原文地址:https://www.cnblogs.com/piaoshi/p/8969135.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!