- 打开图片
打开一张图片是一个很快的操作,和图片的尺寸以及压缩方式无关,打开的时候只读取文件header来获取文件格式、模式、尺寸等信息
from PIL import Image
im = Image.open("hopper.ppm")
with open("hopper.ppm", "rb") as fp:
im = Image.open(fp)
# read from binary data
import io
im = Image.open(io.BytesIO(buffer))
# read from url
from PIL import Image
from urllib.request import urlopen
url = "https://python-pillow.org/images/pillow-logo.png"
img = Image.open(urlopen(url))
- 显示图片格式
>>> im.format
PPM
- 图片尺寸
>>> im.size
(512,512)
- 图片模式
>>> im.mode
# L for greyscale,RGB for true color images,CMYK for pre-press images
RGB
- 展示图片
>>> im.show()
- 保存图片
>>> im.save("hopper.jpg")
- 裁切图片
裁切需要使用到一个四元组\((left,up,right,bottom)\),图片的左上坐标是\((0,0)\)
box = (100, 100, 400, 400)
region = im.crop(box)
- 将一张图片粘贴到另一张图片上
此时被粘贴的图片需要大小和box吻合
region = region.transpose(Image.Transpose.ROTATE_180)
im.paste(region, box)
- 改变RGB图像通道的位置
r, g, b = im.split()
im = Image.merge("RGB", (b, g, r))
- 图片缩放,旋转
out = im.resize((128, 128))
out = im.rotate(45) # degrees counter-clockwise
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)
from PIL import ImageEnhance
enh = ImageEnhance.Contrast(im)
enh.enhance(1.3).show("30% more contrast")
- 图片阵列操作
# 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 Image
with Image.open("animation.gif") as im:
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...
标签:常用,PIL,Image,汇总,im,import,图片,Pillow,out
From: https://www.cnblogs.com/eryoyo/p/16746900.html