Keras.preprocessing.image中的img_to_array执行的具体操作

顾名思义:img_to_array就是讲图片转化成数组,约等于numpy.asarray。

以下用一个小例子分享:

from keras.preprocessing.image import img_to_array
from keras.applications.imagenet_utils import preprocess_input
from PIL import Image
import numpy as np
image =  Image.open("./lena.jpg")
target = (512,512)

 

image = image.resize(target)
image = img_to_array(image)

得到结果:

 

Keras.preprocessing.image中的img_to_array执行的具体操作_第1张图片...
    img_to_array(image)
改为
    np.asarray(image)
 
得到结果:
Keras.preprocessing.image中的img_to_array执行的具体操作_第2张图片...
如果不修改继续进行预处理:
image = np.expand_dims(image, axis=0)  #拓展维度
image=preprocess_input(image)          #预处理
 
就会报错:

 

TypeError: Cannot cast ufunc subtract output from dtype('float64') to dtype('uint8') with casting rule 'same_kind'
 
 
所以要将图片转化为浮点型数组: image = np.asarray(image,'f')
 

 

 
如果出现报错:
 

ValueError: output array is read-only

这是只需要在加上:
image.flags.writeable = True

就可以啦。

image = image.resize(target)
image = np.asarray(image,'f')
#image.flags.writeable = True
image = np.expand_dims(image, axis=0)  #拓展维度
image=preprocess_input(image)          #预处理

 

 

你可能感兴趣的:(keras)