python中图像处理相关库有很多,这里简单介绍PIL、cv2、scipy.imageio 、matplotlib.image、skimage等常用库,其中PIL库使用最方便,cv2库功能最强大。
PIL:Python Imaging Library
python安装:pip install Pillow
这里只给出读取、形状变化、图像转array、array转图像,以及保存图像的方法。
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
%matplotlib inline
# read image
raw_image = Image.open("panda.jpg")
# image resize
image_resize = raw_image.resize((128, 128))
# image to array
image_array = np.array(image_resize)
# array to image
image_output = Image.fromarray(image_array)
# save image
image_output.save("new_panda.jpg")
plt.imshow(raw_image)
plt.axis("off")
plt.show()
cv2: opencv-python
python下安装:pip install opencv-python
python中的openCV库,非常强大,可以对图像做各种处理,这里暂时只给出读取和保存的方法。
import cv2
# read image, return np.array with BGR
raw_image = cv2.imread("panda.jpg")
# BGR to RGB
image_rgb = cv2.cvtColor(raw_image,cv2.COLOR_BGR2RGB)
# image resize
image_resize = cv2.resize(raw_image, (128, 128))
# save image
cv2.imwrite("new_panda.jpg", image_resize)
keras.preprocessing
keras中处理图像的工具,其实底层处理用的PIL,不过多讲解。
from keras.preprocessing import image
# read image
raw_image = image.load_img("panda.jpg", target_size=(128, 128))
# image to array
image_array = image.img_to_array(raw_image)
# array to image
image_output = image.array_to_img(image_array)
# save image
image_output.save("new_panda.jpg")
scipy.imageio
安装:pip install imageio
科学计算库scipy中的方法,之前是scipy.misc,新版用imageio,misc弃用。
from imageio import imread, imsave
# read image
raw_image = imread("panda.jpg")
# save image
imsave("new_panda.jpg", image_resize)
# show image
plt.imshow(image_resize)
plt.axis("off")
plt.show()
matplotlib.image
绘图工具库matplotlib中的方法
import matplotlib.image as mpimg
# read image , return np.array
raw_image = mpimg.imread("panda.jpg")
# save image
mpimg.imsave("new_panda.jpg", raw_image)
# show image
plt.imshow(raw_image)
plt.axis("off")
plt.show()
skimage: Scikit-Image
安装:pip install -U scikit-image
Scikit-Image图像处理是在scipy基础上扩展的,有兴趣可以了解。
from skimage import io
# read image
raw_image = io.imread("panda.jpg")
# save image
io.imsave("new_panda.jpg", raw_image)
# show image
io.imshow(raw_image)