0%

Python读取图片并保存的几种方式

这里尝试过pngjpg,为方便保存路径在函数内自动转换,因此需要路径后缀恰为三位。

方法一:Pillow

这里采用pillow读取图片,它默认显示图片采用系统的默认图片显示器。

1
2
3
4
5
6
7
8
9
10
11
def read_image_1(path):
""" Pillow
This will show picture with default image showing program.

Args:
path: path of the image.
"""
image = Image.open(path)
image.show()
new_path = path[:-4] + '-fc1.jpg'
image.save(new_path)

方法二:Matplot

这里用matplotpyplot去读取和显示图片,注意保存图片需要在显示之前执行,否则无法保存。

1
2
3
4
5
6
7
8
9
10
11
12
def read_image_2(path):
""" matplot

Args:
path: path of the image.
"""
image = mpimg.imread(path)
plt.imshow(image)
plt.axis('off')
new_path = path[:-4] + '-fc2.jpg'
mpimg.imsave(new_path, image)
plt.show()

方法三:OpenCV

这里显示图片需要条用cv2.waitKey(),否则图片会显示后立刻消失。

注意:OpenCV读取的图片的排列方式为bgr而非常见的rgb

1
2
3
4
5
6
7
8
9
10
11
def read_image_3(path):
""" OpenCV

Args:
path: path of the image.
"""
image = cv2.imread(path)
cv2.imshow(path, image)
cv2.waitKey()
new_path = path[:-4] + '-fc3.jpg'
cv2.imwrite(new_path, image)

方法四:Imageio

这里imageio只是用于读取和保存,用matplot显示。

1
2
3
4
5
6
7
8
9
10
11
def read_image_4(path):
""" imageio

Args:
path: path of the image.
"""
image = imageio.imread(path)
plt.imshow(image)
plt.show()
new_path = path[:-4] + '-fc4.jpg'
imageio.imsave(new_path, image)

方法五:skimage

1
2
3
4
5
6
7
8
9
10
11
def read_image_5(path):
""" skimage

Args:
path: path of the image.
"""
image = io.imread(path)
io.imshow(image)
new_path = path[:-4] + '-fc5.jpg'
io.imsave(new_path, image)
io.show()

相关加载库

以防万一不知道import什么,这里列一下需要import的库。

1
2
3
4
5
6
7
from PIL import Image
from skimage import io
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import cv2
import imageio