Keras - 用边界上的值填充张量

Bar*_*ich 4 image-processing padding conv-neural-network keras tensorflow

我的图像大小不均匀,所以当卷积将其缩小 2 倍时,然后我这样做Conv2DTranspose,我没有得到一致的大小,这是一个问题。

所以我想我应该用额外的行和列填充中间张量,其值与我在边缘看到的值相同,以尽量减少干扰。我如何在 Keras 中做到这一点,这可能吗?我有什么选择?

ben*_*che 5

使用 Tensorflow 作为背景,您可以使用tf.concat()向张量添加行/列的副本。

假设您想复制最后一行/列:

import tensorflow as tf
from keras.layers import Lambda, Input
from keras.models import Model
import numpy as np

def duplicate_last_row(tensor):
    return tf.concat((tensor, tf.expand_dims(tensor[:, -1, ...], 1)), axis=1)

def duplicate_last_col(tensor):
    return tf.concat((tensor, tf.expand_dims(tensor[:, :, -1, ...], 2)), axis=2)

# --------------
# Demonstrating with TF:

x = tf.convert_to_tensor([[[1, 2, 3], [4, 5, 6]],
                          [[10, 20, 30], [40, 50, 60]]])

x = duplicate_last_row(duplicate_last_col(x))
with tf.Session() as sess:
    print(sess.run(x))
# [[[ 1  2  3  3]
#   [ 4  5  6  6]
#   [ 4  5  6  6]]
#
#  [[10 20 30 30]
#   [40 50 60 60]
#   [40 50 60 60]]]


# --------------
# Using as a Keras Layer:

inputs = Input(shape=(5, 5, 3))
padded = Lambda(lambda t: duplicate_last_row(duplicate_last_col(t)))(inputs)

model = Model(inputs=inputs, outputs=padded)
model.compile(optimizer="adam", loss='mse', metrics=['mse'])
batch = np.random.rand(2, 5, 5, 3)
x = model.predict(batch, batch_size=2)
print(x.shape)
# (2, 6, 6, 3)
Run Code Online (Sandbox Code Playgroud)