清洁的方式使用keras美白每个图像批处理

问题描述 投票:0回答:1

我想在一个批次美白每个图像。我必须这样做的代码是这样的:

def whiten(self, x):
    shape = x.shape
    x = K.batch_flatten(x)
    mn = K.mean(x, 0)
    std = K.std(x, 0) + K.epsilon()
    r = (x - mn) / std
    r = K.reshape(x, (-1,shape[1],shape[2],shape[3]))
    return r
#

其中x是(?,320,320,1)。我并不热衷于用-1 ARG的重塑功能。是否有一个更清洁的方式做到这一点?

tensorflow keras
1个回答
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)

除此之外,我想不出一个更清洁的方式做你想做的事情。如果你问我,你的代码已经足够清晰。

© www.soinside.com 2019 - 2024. All rights reserved.