Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tensorflow: How to switch channels of a tensor from RGB to BGR?

Tags:

tensorflow

Is there a quick way to convert tensors which encode an image from RGB to BGR?

In python that would be something like:

image = image[:, :, [2,1,0]]
like image 228
mcExchange Avatar asked Feb 10 '17 14:02

mcExchange


3 Answers

You can use tf.strided_slice or tf.reverse.

For example,

import tensorflow as tf

img = tf.reshape(tf.range(30), [2, 5, 3])

# the following two lines produce equivalent result:
img_channel_swap = img[..., ::-1]
img_channel_swap_1 = tf.reverse(img, axis=[-1])

Note that the api of tf.reverse is changed from tensorflow r1.0.

like image 89
Jenny Avatar answered Nov 01 '22 10:11

Jenny


Assuming the channel is the last dimension.

channels = tf.unstack (image, axis=-1)
image    = tf.stack   ([channels[2], channels[1], channels[0]], axis=-1)
like image 7
etoropov Avatar answered Nov 01 '22 11:11

etoropov


You can use tf.split as well.
Snippet from tensorflow-vgg16/blob/master/vgg16.py#L5:

red, green, blue = tf.split(3, 3, rgb_scaled)
bgr = tf.concat(3, [blue, green, red])
like image 1
Temak Avatar answered Nov 01 '22 11:11

Temak