python中的图片基础操作

PIL (pillow)

1
2
3
import io
from PIL import Image
import matplotlib.pyplot as plt

基础读写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 读取图片
image = Image.open('/path/to/image.png').convert('RGB')
image2 = Image.open(io.BytesIO(buffer)) # buffer is bytes
image3 = Image.open(requests.get(image_url, stream=True).raw)

# 查看图像实例的属性
print("""
Format: {image.format}
Size: {image.size} = (width, height)
Mode: {image.mode} ∈ (L, RGB, RGBA, CMYK, YCbCr, HSV)
""")

# 保存图片
image.save('/path/to/image.jpg', 'jpg') # 有损压缩存储
image.save('/path/to/image.phg', 'png') # 无损存储

展示图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
def show_one_image(image):
if isinstance(image, str):
image = Image.open(image).convert('RGB')
plt.imshow(image); plt.axis('off'); plt.show()


def show_images(image_files):
if len(image_files) == 0:
return

# 定义每张图片的最大宽度和高度
max_width, max_height = 224, 224
# 打开并缩放图片
images = []
for img_file in image_files:
img = Image.open(img_file)
img = img.resize((max_width, max_height), Image.BILINEAR)
images.append(img)
# 计算拼接后的总宽度和高度
total_width = sum(img.width for img in images)
max_height = max(img.height for img in images)
# 创建新的空白图片
new_image = Image.new('RGB', (total_width, max_height))
# 拼接图片
x_offset = 0
for img in images:
new_image.paste(img, (x_offset, 0))
x_offset += img.width
# 在Jupyter Notebook中展示拼接后的图片
plt.imshow(new_image); plt.axis('off'); plt.show()

def random_show_dir_images(dirname, k=5):
from glob import glob
import random
fnames = glob(dirname.rstrip('/')+'/*.jpg') + glob(dirname.rstrip('/')+'/*.jpeg') + glob(dirname.rstrip('/')+'/*.png')
show_images(random.choices(fnames, k=k))

resize

1
2
# 将图片强制缩放到224x224
img = img.resize((224,224), Image.BILINEAR)