python - 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.
解决方案
您可以在自定义Lambda层内对输入张量进行切片。假设您只想要红色和绿色:
model.add(Lambda(lambda x: x[:,:,:,:2], input_shape=(w, h, channels)))
TensorFlow 允许与 NumPy 进行类似的切片,对于 Keras,您需要将其包裹在 Lambda 层以合并到您的模型中。
推荐阅读
- r - 将单元格颜色映射到 kableExtra 中的数据值以创建热图表
- apache-kafka - Confluent Load Connector 无效 JSON - 解析错误:第 1 行第 7 列的数字文字无效
- c++ - 内存泄漏。如何正确使用删除?BN_bn2hex _CrtIsValidHeapPointer(块)
- reactjs - 有没有办法可以从包装的组件更改父状态
- google-apps-script - 触发 Gmail 的报告网络钓鱼功能
- r - 在大型数据集上更改窗口大小的滚动平均值
- c# - 如何通过 IEnumerable 使用 TableQuery 进行查询?
- asp.net-mvc - 使用迁移将表添加到数据库
- javascript - 只克隆一个字段,每次点击追加一次
- python - Python:在整个 Excel 表中查找值/数据