简体   繁体   中英

How to get the shape of an image after decode_jpeg in Tensorflow?

I have an image which I have feed into tf.image.decode_jpeg:

img = tf.io.read_file(file_path)
img = tf.image.decode_jpeg(img, channels=3)

and I am trying to get its height and with width img.shape[0] and img.shape[1] , but both return None . Actually, img.shape returns (None, None, 3) .

I am using this inside a function that is mapped into a tf.data.Dataset . How can I get the real shape of the image?

update:

At the moment, I have found a solution that consists in wrapping the code with tf.py_function to execute it eagerly because the dataset creates an internal graph. I would appreciate If anyone has another solution to do it in a pure graph way, which would improve performance.

Since you have already found a solution to get the shape of the image by wrapping your code around tf.py_function . Providing the solution here for the benefit of the community.

However, since eager execution is enabled by default in TensorFlow 2, you can get the shape directly like mentioned below without having to wrap it around tf.py_function .

Tensorflow 1.x:

img = tf.io.read_file("sample.jpg")
img = tf.image.decode_jpeg(img, channels=3)

with tf.Session() as sess:
  array = img.eval(session=sess)
  height = array.shape[0]
  width = array.shape[1]
  print("Height:",height)
  print("Width:",width) 

Height:320

Width:320

Tensorflow 2:

img = tf.io.read_file("sample.jpg")
img = tf.image.decode_jpeg(img, channels=3)
height = img.shape[0]
width = img.shape[1]

print("Height:",height)
print("Width:",width) 

Height: 320

Width: 320

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM