Python 三种主要的图像处理库:

  • skimage
  • opencv-python
  • Pillow PIL
pip install scikit-image
pip install opencv-python
pip install pillow

图像加载

Python 库图片加载函数返回值图像像素格式像素值范围图像矩阵表示
skimageio.imreadnumpy.ndarrayRGB[0, 255]H x W x C
cv2cv2.imreadnumpy.ndarrayBGR[0, 255]H x W x C
Pillow PILImage.openPIL.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

Image Processing — OpenCV Vs PIL

  • OpenCV is 1.4 Times faster than PIL

加载速度对比

Use python to compare PIL and OpenCV encoding image speed

基于 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
Last modification:December 14th, 2021 at 04:40 pm