pillow
image
本文字数:427 字 | 阅读时长 ≈ 2 min

pillow

image
本文字数:427 字 | 阅读时长 ≈ 2 min

1. 安装

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

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

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

安装:pip install pillow

2. 基本操作

2.1 open

Image.open(filename)

加载并识别一个 image 文件

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

PIL image 的属性

1.图像尺寸

img.width img.height img.size

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

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

3.图像模式

img.mode

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

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

2. show

PIL Image.show()

显示图片

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

3. save

save(filename)

保存图片

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

4. Numpy 与 PIL Image 的转化

numpy→PIL

Image.fromarray(ndarray)

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)

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

4月 06, 2025
3月 10, 2025
12月 31, 2024