2

With the code below I read the same image with OpenCV and with Tensorflow.

import tensorflow as tf
import cv2

def get_image(image_path):
    """Reads the jpg image from image_path.
    Returns the image as a tf.float32 tensor
    Args:
        image_path: tf.string tensor
    Reuturn:
        the decoded jpeg image casted to float32
    """
    return tf.image.convert_image_dtype(
        tf.image.decode_jpeg(
            tf.read_file(image_path), channels=3),
        dtype=tf.uint8)


path = "./images/2010_006748.jpg"
original_image = cv2.imread(path)

image_tensor = get_image(tf.constant(path))
# convert to uint8
image_tensor = tf.image.convert_image_dtype(image_tensor, dtype=tf.uint8)
with tf.Session() as sess:
    image = sess.run(image_tensor)

cv2.imshow("tf", image)
cv2.imshow("original", original_image)
cv2.waitKey(0)

As you can see from the image, ther's a difference between the image read by OpenCV (right colors) and by Tensorflow (wrong colors).

tensorflow vs opencv

I tried to normalize the colors of the Tensorflow image using cv2.normalize(image, image, 0, 255, cv2.NORM_MINMAX, dtype=cv2.CV_8UC3) but nothing changed.

I've also tryed to read the image as tf.uint8 (removing the initiall cast to tf.float32) but no changes.

How can I display the image read with Tensorflow, using OpenCV properly?

3
  • it looks like the red and blue channels are swapped, what is the default order for reading RGB images in tensorflow? is it BGR or RGB? Commented Aug 11, 2016 at 8:08
  • You're right! Tensorflow format is RGB whilst OpenCV format is BGR. So, how can I convert between these 2 color spaces? Commented Aug 11, 2016 at 8:26
  • I'm just looking at the docs now, you may have to swap the channels yourself after loading as I can't see any options to specify the channel order Commented Aug 11, 2016 at 8:34

1 Answer 1

6

Try:

bgr_img = cv2.cvtColor(original_image, cv2.COLOR_RGB2BGR)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.