Python中读取图片并转化为numpy.ndarray()数据的6种方式
方式: 返回类型
OpenCV np.ndarray
PIL PIL.JpegImagePlugin.JpegImageFile
keras.preprocessing.image PIL.JpegImagePlugin.JpegImageFile
Skimage.io np.ndarray
matplotlib.pyplot np.ndarray
matplotlib.image np.ndarray
import numpy as np
import cv2
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
from PIL import Image
import skimage.io as io
import matplotlib.pyplot as plt
import matplotlib.image as mpig
'''
方式: 返回类型
OpenCV np.ndarray
PIL PIL.JpegImagePlugin.JpegImageFile
keras.preprocessing.image PIL.JpegImagePlugin.JpegImageFile
Skimage.io np.ndarray
matplotlib.pyplot np.ndarray
matplotlib.image np.ndarray
'''
imagePath="E:/DataSet/test1/trainSet/bus/300.jpg"
'''
方式一:使用OpenCV
'''
img1=cv2.imread(imagePath)
print("img1:",img1.shape)
print("img1:",type(img1))
print("-"*10)
'''
方式二:使用PIL
'''
img2=Image.open(imagePath)
print("img2:",img2)
print("img2:",type(img2))
#转换成np.ndarray格式
img2=np.array(img2)
print("img2:",img2.shape)
print("img2:",type(img2))
print("-"*10)
'''
方式三:使用keras.preprocessing.image
'''
img3=load_img(imagePath)
print("img3:",img3)
print("img3:",type(img3))
#转换成np.ndarray格式,使用np.array(),或者使用keras里的img_to_array()
#使用np.array()
#img3=np.array(img2)
#使用keras里的img_to_array()
img3=img_to_array(img3)
print("img3:",img3.shape)
print("img3:",type(img3))
print("-"*10)
'''
方式四:使用Skimage.io
'''
img4=io.imread(imagePath)
print("img4:",img4.shape)
print("img4:",type(img4))
print("-"*10)
'''
方式五:使用matplotlib.pyplot
'''
img5=plt.imread(imagePath)
print("img5:",img5.shape)
print("img5:",type(img5))
print("-"*10)
'''
方式六:使用matplotlib.image
'''
img6=mpig.imread(imagePath)
print("img6:",img6.shape)
print("img6:",type(img6))
print("-"*10)
运行结果:
Using TensorFlow backend.
img1: (256, 384, 3)
img1:
----------
img2:
img2:
img2: (256, 384, 3)
img2:
----------
img3:
img3:
img3: (256, 384, 3)
img3:
----------
img4: (256, 384, 3)
img4:
----------
img5: (256, 384, 3)
img5:
----------
img6: (256, 384, 3)
img6:
----------