将图片转换为tensorflow中可以使用的批数据
#coding=utf-8
from PIL import Image
import os
import os.path
import numpy as np
import tensorflow as tf
import tensorflow.contrib.slim as slim
import tensorflow.contrib.slim.nets as nets
import inception_resnet_v2
def convert(dir):
filelists=os.listdir(dir)
arr_col=[]
for file in filelists:
file_path=os.path.join(dir,file)
img=Image.open(file_path).resize((299,299)).convert("RGB")
r,g,b=img.split()
r_arr=np.array(r)
g_arr=np.array(g)
b_arr=np.array(b)
img_arr=np.concatenate((r_arr,g_arr,b_arr))
result=img_arr.reshape((299,299,3))
arr_col.append(result)
return arr_col
def convert_3_2_4_dims(arr_):
ret=np.zeros((len(arr_),arr_[0].shape[0],arr_[0].shape[1],arr_[0].shape[2]))
for i in range(len(arr_)):
ret[i,:,:,:]=arr_[i]
return ret
def to_categorial(y,n_classes):
y_std=np.zeros([len(y),n_classes])
for i in range(len(y)):
y_std[i,y[i]]=1.0
return y_std
#注意这儿进行选用list而不是tuple的原因在于后面数据的归一化需要改变值,而tuple不支持这种操作,所以选用list
def batch_list(x,y,batch_size):
batches=[]
for i in range(int(len(x)/batch_size)):
print("enen"+str(i))
batch_data=[x[batch_size*i:batch_size*i+batch_size],y[batch_size*i:batch_size*i+batch_size]]
batches.append(list(batch_data))
if(i+1)*batch_size<len(x):
batch_data=[x[batch_size*(i+1):],y[batch_size*(i+1):]]
batches.append(list(batch_data))
return batches
def load_data(dir,num_classes,batch_size):
arr_col=convert_3_2_4_dims(convert(dir))
arr_col=arr_col.astype(np.float32)
#因为这儿我没指定它的标签,所以就随机指定了一些标签
z=np.random.rand(arr_col.shape[0])*num_classes
z=z.astype("int")
labels=np.array(z)
batches=batch_list(arr_col,to_categorial(labels,num_classes),batch_size)
return batches
#对数据进行归一化
def data_lrn(batches):
for batch in batches:
print(type(batch[0]))
batch[0]/=255
return batches