Keras 在网络中添加 图像decode层 resize 图片
任务:输入decode以后的图片数据,使用tf.decode_png等进行解码,进行resize,然后进入网络预测
难点1 添加decode 层
- 替换模型input,添加decode 需要使用 keras.layers.Input(),tf中使用tf.placehoder
- keras.layers.Input() 会自动添加batch维度,但是tf.image.decode_jpeg不需要batch维度
- tf.image.convert_image_dtype 会自动将图片归一化
- decode以后需要tf.expand_dims再次添加维度
难点1 代码展示
shape = (1,)
jpeg_data = keras.layers.Input(shape=shape,dtype = tf.string,name='input1')
# jpeg_data = tf.placeholder(tf.string,name = 'input')
print(jpeg_data)
shape2 = (2,)
inputs2 =keras.layers.Input(shape=shape2,dtype=tf.int32,name='input_2')
def decode(args):
jpeg_data,inputs2 = args
image_data = tf.image.decode_jpeg(jpeg_data[0][0], channels=3)
image_data = tf.cast(image_data, tf.float32) ##cast 不会自动归一化
shape_image_data = keras.backend.shape(image_data)[:-1]
t_int_shape = keras.backend.int_shape(image_data)
image_data = resize_image(inputs2[0], t_int_shape)(image_data)
return tf.expand_dims(image_data, 0)
难点2 获取张量动态shape 进行resize
获取张量动态shape,使用到的函数:
keras.backend.shape(image_data)
keras.backend.int_shape(image_data)
tf.shape
tf.get_shape()
无效代码展示
## 无效代码展示
image_data = tf.image.decode_jpeg(jpeg_data[0][0], channels=3)
image_data = tf.cast(image_data, tf.float32)
shape_image_data = keras.backend.shape(image_data)[:-1]
t_int_shape = keras.backend.int_shape(image_data)
print(shape_image_data,'shape_image_data')
scaley = 1
scalex = 1
if t_int_shape[0] is None:
new_height = None
else:
new_height = t_int_shape[0] // 32 * 32
scalex = t_int_shape[0] / new_height
if t_int_shape[1] is None:
new_width = None
else:
new_width = t_int_shape[1] // 32 * 32
scaley = t_int_shape[1] / new_width
shape_image_data = tf.constant(np.array([new_height, new_width], dtype=np.float32))
t_int_shape = (new_height, new_width)
以上代码 获取不了shape 反正我是没做到
解决方案
shape 获取不了,没办法计算新的宽高 只能曲线救国
设置多输入,将需要resize的宽高传入
## 无效代码展示
from keras.layers import Lambda
shape = (1,)
jpeg_data = keras.layers.Input(shape=shape,dtype = tf.string,name='input1')
# jpeg_data = tf.placeholder(tf.string,name = 'input')
print(jpeg_data)
def mean_substraction1(args):
jpeg_data,inputs2 = args
image_data = tf.image.decode_jpeg(jpeg_data[0][0], channels=3)
image_data = tf.cast(image_data, tf.float32)
shape_image_data = keras.backend.shape(image_data)[:-1]
t_int_shape = keras.backend.int_shape(image_data)
image_data = resize_image(inputs2[0], t_int_shape)(image_data)
return tf.expand_dims(image_data, 0)
inputs1 = Lambda(mean_substraction1,name='input_1')([jpeg_data,inputs2])
shape2 = (2,)
inputs2 =keras.layers.Input(shape=shape2,dtype=tf.int32,name='input_2')
model = keras.models.Model([jpeg_data,inputs2],inputs1)
model.summary()