Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to fix "TypeError: x and y must have the same dtype, got tf.uint8 != tf.float32" when I try to resize an image in Tensorflow

I try to setup an images pipeline that builds an images dataset for Tensorflow that crops the images, but I fail at cropping the picture. I followed this tutorial but I want to crop the file to a square and not resize it without preserving the aspect ratio.
Here is my code :

#
import tensorflow as tf
#

img_raw = tf.io.read_file('./images/4c34476047bcbbfd10b1fd3342605659.jpeg/')

img_tensor = tf.image.decode_jpeg(img_raw, channels=3)

img_final = tf.image.crop_to_bounding_box(
    img_tensor,
    0,
    0,
    200,
    200
)

img_final /= 255.0  # normalize to [0,1] range

When I use simple image resize as in the tutorial it works:

#
import tensorflow as tf
#

img_raw = tf.io.read_file('./images/4c34476047bcbbfd10b1fd3342605659.jpeg/')

img_tensor = tf.image.decode_jpeg(img_raw, channels=3)

img_final = tf.image.resize(img_tensor, [192, 192])

img_final /= 255.0  #

Here is the log :

    img_final /= 255.0  # normalize to [0,1] range
  File ".../.local/lib/python3.6/site-packages/tensorflow/python/ops/math_ops.py", line 876, in binary_op_wrapper
    return func(x, y, name=name)
  File ".../.local/lib/python3.6/site-packages/tensorflow/python/ops/math_ops.py", line 964, in _truediv_python3
    (x_dtype, y_dtype))
TypeError: x and y must have the same dtype, got tf.uint8 != tf.float32
like image 592
Ant1 Avatar asked Dec 22 '22 22:12

Ant1


1 Answers

Tensorflow doesn't do automatic type casting. It seems that the decoded image is a tensor with dtype tf.uint8, you have to cast it to tf.float32 for the division to work as you expect.

Replace

img_final /= 255.0

with

img_final = tf.cast(img_final, tf.float32) / 255.0

like image 122
Addy Avatar answered Dec 25 '22 12:12

Addy