python - 在 Keras 中定义二进制掩码

标签 python tensorflow keras conv-neural-network mask

我有一个形状为 [X,Y,3] 的输入图像,并且有 2 个坐标 (x,y)。现在我想用这些坐标创建一个蒙版,然后将其与输入图像相乘。掩码应该是一个与图像大小相同的二进制矩阵,其中 1 位于坐标 [x:x+p_size,y:y+p_size] 处,0 位于其他位置。

我的问题是如何在 Keras( tensorflow 后端)中定义掩码?

请注意,此操作发生在模型内(因此仅使用 numpy 没有帮助)。

img = Input(shape=(32,32,3))
xy = Input(shape=(2)) # x and y coordinates for the mask
mask = ?
output = keras.layers.Multiply()([img, mask])

最佳答案

你可以用Lambda来完成整个事情。实现自定义功能的层:

from keras.models import Model
from keras.layers import Input, Lambda
from keras import backend as K
import numpy as np

# Masking function factory
def mask_img(x_size, y_size=None):
    if y_size is None:
        y_size = x_size
    # Masking function
    def mask_func(tensors):
        img, xy = tensors
        img_shape = K.shape(img)
        # Make indexing arrays
        xx = K.arange(img_shape[1])
        yy = K.arange(img_shape[2])
        # Get coordinates
        xy = K.cast(xy, img_shape.dtype)
        x = xy[:, 0:1]
        y = xy[:, 1:2]
        # Make X and Y masks
        mask_x = (xx >= x) & (xx < x + x_size)
        mask_y = (yy >= y) & (yy < y + y_size)
        # Make full mask
        mask = K.expand_dims(mask_x, 2) & K.expand_dims(mask_y, 1)
        # Add channels dimension
        mask = K.expand_dims(mask, -1)
        # Multiply image and mask
        mask = K.cast(mask, img.dtype)
        return img * mask
    return mask_func

# Model
img = Input(shape=(10, 10, 3))  # Small size for test
xy = Input(shape=(2,))
output = Lambda(mask_img(3))([img, xy])
model = Model(inputs=[img, xy], outputs=output)

# Test
img_test = np.arange(100).reshape((1, 10, 10, 1)).repeat(3, axis=-1)
xy_test = np.array([[2, 4]])
output_test = model.predict(x=[img_test, xy_test])
print(output_test[0, :, :, 0])

输出:

[[ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0. 24. 25. 26.  0.  0.  0.]
 [ 0.  0.  0.  0. 34. 35. 36.  0.  0.  0.]
 [ 0.  0.  0.  0. 44. 45. 46.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  0.  0.]]

关于python - 在 Keras 中定义二进制掩码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54093203/

相关文章:

tensorflow - BERT - 池化输出与序列输出的第一个向量不同

Python - 如何保存/加载特定的cookie?

python - 如果任务没有运行超过 10 分钟,如何重新安排任务?

python - 构建 Pandas DataFrame 时避免循环

python - 在 Ubuntu12.04 中使用 Python3 的 lxml 内存泄漏

python - bert-serving-start 给出错误 TypeError : cannot unpack non-iterable NoneType object - tried multiple paths to the model

python - 使用 Lime R 包解释我的 keras 对象的功能

python - Google Cloud ML Engine + Tensorflow 在 input_fn() 中执行预处理/标记化

matrix - Tensorflow:使用多个 tf.concat 创建矩阵

python - Keras:model.fit 中的冗长(值 1)显示较少的训练数据