使用keras的更清晰的方法来批量增白每个图像

时间:2019-02-06 00:23:58

标签: tensorflow keras

我想批量增白每个图像。我要做的代码是这样的:

cat .\out.txt | cat | cat ...

其中x是(?,320,320,1)。我不喜欢带有-1 arg的重塑功能。有没有更清洁的方法可以做到这一点?

1 个答案:

答案 0 :(得分:1)

让我们看看-1的作用。来自Tensorflow文档(因为与来自Tensorflow的文档相比,Keras的文档很少):

  

如果形状的一个分量为特殊值-1,则将计算该尺寸的大小,以便总大小保持恒定。

这意味着什么:

from keras import backend as K

X = tf.constant([1,2,3,4,5])
K.reshape(X, [-1, 5])
# Add one more dimension, the number of columns should be 5, and keep the number of elements to be constant
# [[1 2 3 4 5]]

X = tf.constant([1,2,3,4,5,6])
K.reshape(X, [-1, 3])
# Add one more dimension, the number of columns should be 3
# For the number of elements to be constant the number of rows should be 2
# [[1 2 3]
#  [4 5 6]]

我认为这很简单。那么代码中会发生什么:

# Let's assume we have 5 images, 320x320 with 3 channels
X = tf.ones((5, 320, 320, 3))
shape = X.shape

# Let's flat the tensor so we can perform the rest of the computation
flatten = K.batch_flatten(X)
# What this did is: Turn a nD tensor into a 2D tensor with same 0th dimension. (Taken from the documentation directly, let's see that below)
flatten.shape
# (5, 307200)
# So all the other elements were squeezed in 1 dimension while keeping the batch_size the same

# ...The rest of the stuff in your code is executed here...

# So we did all we wanted and now we want to revert the tensor in the shape it had previously
r = K.reshape(flatten, (-1, shape[1],shape[2],shape[3]))
r.shape
# (5, 320, 320, 3)

此外,我想不出一种更干净的方式来做自己想做的事。如果您问我,您的代码已经足够清楚了。