在我的 Keras CNN 中,我像这样添加输入层:
model.add(Conv2D(32, (3, 3), input_shape=(img_width, img_height, nb_channel)))
nb_channel = 3 用于 RGB 输入,nb_channel = 1 用于灰度输入以及 flow_from_directory 和 ImageDataGenerator
但是,我想指定一组颜色 channel 输入到我的 CNN,例如,只允许绿色和红色 channel ,我该怎么做?
我正在使用带有 tensorflow 后端的 Keras
除了@Minh-Tuan Nguyen 的简洁解决方案,我们还可以按照以下方式进行切片
#custom filter
def filter_layer(x):
red_x = x[:,:,:,0]
blue_x = x[:,:,:,2]
green_x = x[:,:,:,1]
red_x = tf.expand_dims(red_x, axis=3)
blue_x = tf.expand_dims(blue_x, axis=3)
green_x = tf.expand_dims(green_x, axis=3)
output = tf.concat([red_x, blue_x], axis=3)
return output
#model
input = Input(shape=(img_height, img_width, img_channels))
在连接步骤中,我们可以选择我们想要的切片。
请您参考如下方法:
您可以在自定义 Lambda 中对输入张量进行切片层。假设您只想要红色和绿色:
model.add(Lambda(lambda x: x[:,:,:,:2], input_shape=(w, h, channels)))
TensorFlow 允许与 NumPy 进行类似的切片,对于 Keras,您需要将其包裹在 Lambda 层周围以合并到您的模型中。
