pillow

@[TOC](PIL: open show save)

安装

PIL是python图像处理中的常见模块,特别是在深度学习加载数据集的时候也会用到,下面介绍他的基本使用方法

pillow官网:https://pillow.readthedocs.io/en/stable/

一个很好的pillow教程:http://c.biancheng.net/pillow/what-is-pillow.html

安装:pip install pillow

基本操作

一、open

Image.open(filename)

加载并识别一个image文件

1
2
3
from PIL import Image
img = Image.open('color.jpg')
img.show() # 显示图片

PIL image的属性

1.图像尺寸

img.width img.height img.size

1
2
3
4
5
6
7
8
9
img_color = Image.open("color.jpg")
print(img_color)
print("width: %d height: %d" % (img_color.width, img_color.height))
print("size: ", img_color.size)
'''
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=481x321 at 0x7FB6E02C44D0>
width: 481 height: 321
size: (481, 321)
'''

2.图像格式

img.format

1
2
img_color = Image.open("color.jpg")
print("format: ", img_color.format) # JPEG

3.图像模式

img.mode

1
2
img_color = Image.open("color.jpg")
print("mode: ", img_color.mode) # RGB
mode Description
1 1 位像素(取值范围 0-1),0表示黑,1 表示白,单色通道
L 8 位像素(取值范围 0 -255),灰度图,单色通道
RGB 3 x 8位像素,真彩色,三色通道,每个通道的取值范围 0-255

转变mode: convert('L')

1
2
3
4
5
img_color = Image.open("color.jpg")
print("format: ", img_color.mode) # RGB
img_gray = img_color.convert('L') # L
img_color.show()
img_gray.show()

二、show

PIL Image.show()

显示图片

1
2
img_color = Image.open("color.jpg")
img_color.show()

三、save

save(filename)

保存图片

1
2
3
img_color = Image.open("color.jpg")
img_gray = img_color.convert('L')
img_gray.save('gray.jpg')

四、Numpy与PIL Image的转化

numpy→PIL

Image.fromarray(ndarray)

1
2
3
4
5
6
from PIL import Image
import numpy as np
#创建 300*400的图像,3个颜色通道
array = np.zeros([300,400,3],dtype=np.uint8)
img = Image.fromarray(array)
img.show()

PIL→numpy

np.array(PIL Image)

1
2
3
4
img_color   = Image.open("color.jpg")
img_numpy = np.array(img_color)
img_restore = Image.fromarray(img_numpy)
img_restore.show()

Error: API rate limit exceeded for 50.17.198.136. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)