Pillow tutorial

from PIL import Image
im = Image.open("hopper.ppm")
from __future__ import print_function
print(im.format, im.size, im.mode)
# hit the result
PPM (512, 512) RGB

  Let the picture display, im.show(), because the opening is temporary, the effect of displaying the picture is not very good, and there are 15 functions, so it is generally used to test the display

Change the suffix of the picture, pil can judge the file type by itself according to the content of the file

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

If the suffix is ​​invalid, the second parameter will be used

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

Open the file first to confirm the type, read/parse will be performed later

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

Capture image size, (left, upper, right, lower), coordinates (0, 0) in the upper left corner, exactly 300*300pixels

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

  Invert the image 180 degrees and fill it back in

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 is because crop is a delayed operation, otherwise it will not be saved in the second step
    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

Split into native three primary colors, change positions and then merge

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

  Simple geometric rotation counterclockwise, transpose can also rotate within 90 degrees, and can also rotate horizontally or vertically

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)

  Pictures between different pixels

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

  Enhance image

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

  change contrast

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

  Specific operation pictures

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

  You can adjust contrast, brightness, color balance and sharpness this way

from PIL import ImageEnhance

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

  Open the dynamic graph, and skip the frame and play it once to end

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

  Loop

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

  print on printer

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

  You can also open it like this

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

Open the picture in a relatively large tar file, you can increase the speed of finding through seek and 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)

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325090489&siteId=291194637