基于图像预处理的几个库

python 里面有第三方库PIL

Python第三方库使用 —— PIL

1.PIL 读取获得的图像矩阵与 numpy 下的多维数组

import numpy as np
from PIL import Image
img = Image.open(open('./images/3wolfmoon.jpg'))
# Image.open 接受一个文件句柄
img = np.asarray(img, dtype='float64')/255.
img.shape
# (639, 516, 3)
# 做到这一步还不够,如果是彩色图像
# img.shape = (height, width, ndim)
# 并不是 numpy 中所习惯的维度配置

img = img.transpose(2, 0, 1)
img.shape
# (3, 639, 516)

当使用PIL.Image.open()打开图片后,如果要使用img.shape函数,需要先将image形式转换成array数组

 

2.kears图片处理

from keras.preprocessing.image import img_to_array
from keras.applications.imagenet_utils import preprocess_input
from PIL import Image
import numpy as np

  1. image =  Image.open("./lena.jpg")
  2.  target = (512,512)

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

得到结果:

    img_to_array(image)
改为
    np.asarray(image)
 
得到结果:

如果不修改继续进行预处理:

所以要将图片转化为浮点型数组: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) #预处理

暂时总结这一些  

 

posted @ 2019-03-16 15:28  python之路漫漫  阅读(944)  评论(0编辑  收藏  举报