Python 三种主要的图像处理库:
- skimage
- opencv-python
- Pillow PIL
pip install scikit-image
pip install opencv-python
pip install pillow
图像加载
Python 库 | 图片加载函数 | 返回值 | 图像像素格式 | 像素值范围 | 图像矩阵表示 |
---|---|---|---|---|---|
skimage | io.imread | numpy.ndarray | RGB | [0, 255] | H x W x C |
cv2 | cv2.imread | numpy.ndarray | BGR | [0, 255] | H x W x C |
Pillow PIL | Image.open | PIL.Image.Image对象 | 根据图像格式,一般为RGB | [0, 255] | — |
示例:
import skimage.io as io
import cv2
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
# skimage
img_io = io.imread('test.jpg')
print(type(img_io), img_io.shape)
#np.ndarray, (H x W x C), [0, 255],RGB
# opencv
img_cv2 = cv2.imread('test.jpg')
print(type(img_cv2), img_cv2.shape)
#np.array, (H x W xC), [0, 255], BGR
# PIL
img_pil = Image.open('test.jpg')
img_array = np.array(img_pil)
print(type(img_array), img_array.shape)
# (H x W x C), [0, 255], RGB
plt.figure(figsize=(10, 10))
for i, img in enumerate([img_io, img_cv2, img_array]):
plt.subplot(1, 3, i + 1)
plt.imshow(img)
plt.show()
OpenCV && PIL
- OpenCV is 1.4 Times faster than PIL
加载速度对比
基于 PIL 和 OpenCV 分别网内存中编码一个 png 或者 jpeg 图片,通过结果可以简单得出结论:
- 编码 png 格式比 jpeg 格式耗时更多
- 编码 jpeg 格式 pil 与 opencv 相差不大
- 编码 png 格式 pil 与 opencv 相差较大
import cv2
from PIL import Image
from io import StringIO, BytesIO
import numpy as np
import time
img_path = 'test.jpg'
#PIL
img_pil = Image.open(img_path)
print("img size {}, mode {}".format(img_pil.size, img_pil.mode))
#往内存中写JPEG格式图片
t0 = time.time()
with BytesIO() as out:
img_pil.save(out, format='JPEG')
t1 = time.time()
with open('out_test.jpg', 'wb') as fo:
fo.write(out.getvalue())
#往内存中写PNG格式图片
t2 = time.time()
with BytesIO() as out:
img_pil.save(out, format='PNG')
t3 = time.time()
with open('out_test.png', 'wb') as fo:
fo.write(out.getvalue())
print("PIL save image as jpeg : ", t1 - t0)
print("PIL save image as png : ", t3 - t2)
#Opencv
img_cv2 = cv2.imread(img_path)
print("img shape : ", img_cv2.shape)
#往内存中写JPEG格式图片
t0 = time.time()
_, img_bytes = cv2.imencode(".jpg", img_cv2)
img_str = np.array(img_bytes).tobytes()
t1 = time.time()
with open("cv2_test.jpg", "wb") as f:
f.write(img_str)
#往内存中写PNG格式图片
t2 = time.time()
_, img_bytes = cv2.imencode(".png", img_cv2)
img_str = np.array(img_bytes).tobytes()
t3 = time.time()
with open("cv2_test.png", "wb") as f:
f.write(img_str)
print("OpenCV save image as jpeg : ", t1 - t0)
print("OpenCV save image as png : ", t3 - t2)
输出:
img size (512, 512), mode RGB
PIL save image as jpeg : 0.006257534027099609
PIL save image as png : 0.04724311828613281
img shape : (512, 512, 3)
OpenCV save image as jpeg : 0.002417325973510742
OpenCV save image as png : 0.007878780364990234