python - 在 Keras 中定义二进制掩码
问题描述
我有一个形状 [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.]]
推荐阅读
- php - Laravel Lighthouse GraphQL - 在服务器端排序
- psql - 如何将 pSQL 中的输出文件格式从默认更改为 csv?
- android - Firebird 和 Android JDBC 驱动程序
- swiftui - Swift UI 和画布编辑器
- haskell - (Windows) 从库中插入代码时,PutStrLn 停止工作
- python - 如何在 python 3.7 中修复“运行时错误:迭代期间字典更改大小”
- asp.net-mvc - 加载资源失败:net::ERR_INTERNET_DISCONNECTED
- angular - mat-dialog 弹出并将页面导航回应用程序的默认路由
- javascript - react-grid-gallery 组件不起作用
- wolfram-mathematica - System = {A, B, C} 如何在mathematica中使用打印命令得到:A=0, B=0, C=0