首页 > 解决方案 > Select specific a set of RGB channel in Keras training model image input

问题描述

In my Keras CNN, I add the Input layer like this:

model.add(Conv2D(32, (3, 3), input_shape=(img_width, img_height, nb_channel)))

with nb_channel = 3 for RGB input and = 1 for grayscale input and the flow_from_directory and ImageDataGenerator

However, I want to specify a set of color to channel to input to my CNN, for example, only green and red channels are permitted, how can I do so?

I'm using Keras with tensorflow Backend

Beside from the neat solution of @Minh-Tuan Nguyen, we can also do the slicing as follow

#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))

at the concat step we can choose the slice we want.

标签: pythonimagetensorflowkeras

解决方案


您可以在自定义Lambda层内对输入张量进行切片。假设您只想要红色和绿色:

model.add(Lambda(lambda x: x[:,:,:,:2], input_shape=(w, h, channels)))

TensorFlow 允许与 NumPy 进行类似的切片,对于 Keras,您需要将其包裹在 Lambda 层以合并到您的模型中。


推荐阅读