Home > Software design >  Strange result when subtracting two tensors
Strange result when subtracting two tensors

Time:10-09

I try to subtract two tensors and then convert every negative value to zero using relu function, but i cannot do that because when i subtract two tensors, tensorflow for some reason add 256 to every negative value !!

img = mpimg.imread('/home/moumenshobaky/tensorflow_files/virtualenv/archive/training/Dessert/82 
 7.jpg')
img2 = tf.math.floordiv(img,64)*64
img3 = img2-img
# showing an example of the Flatten class and operation
from tensorflow.keras.layers import Flatten
flatten = Flatten(dtype='float32')

print(flatten(img2))   
print(img3)

now the result is

tf.Tensor(
[[ 0  0  0 ... 64 64  0]
[ 0  0  0 ... 64  0  0]
[64 64  0 ... 64  0  0]
...
[64 64 64 ... 64 64 64]
[64 64 64 ... 64 64 64]
[64 64 64 ... 64 64 64]], shape=(384, 1536), dtype=uint8)
tf.Tensor(
[[198 197 213 ... 229 252 202]
[194 193 207 ... 235 193 207]
[250 253 198 ... 238 193 207]
...
[227 217 207 ... 218 230 242]
[226 216 206 ... 217 230 239]
[225 215 203 ... 214 227 235]], shape=(384, 1536), dtype=uint8)

CodePudding user response:

I could make it work using tf.keras.utils.img_to_array to convert the image into a numpy array to avoid any unknown behaviour.

I used this image from i presume the same dataset.

img = mpimg.imread('C:/Users/as/Downloads/15.jpg')
img2 = tf.math.floordiv(img,64)*64

# convert to arrays
img = tf.keras.utils.img_to_array(img)
img2 = tf.keras.utils.img_to_array(img2)

img3 = img2-img
# showing an example of the Flatten class and operation
from tensorflow.keras.layers import Flatten
flatten = Flatten(dtype='float32')

print(flatten(img2))   
print(img3)

output:

tf.Tensor(
[[192. 128.  64. ...   0.   0.   0.]
 [192. 128.  64. ...   0.   0.   0.]
 [192. 128. 128. ...   0.   0.   0.]
 ...
 [ 64.   0.   0. ...  64.   0.   0.]
 [ 64.   0.   0. ...  64.   0.   0.]
 [ 64.   0.   0. ...  64.   0.   0.]], shape=(512, 1536), dtype=float32)
[[[-17. -43. -58.]
  [-23. -51.  -3.]
  [-31. -61. -16.]
  ...
  [-20.  -7. -14.]
  [-20.  -7. -14.]
  [-20.  -7. -14.]]

 [[-19. -45. -60.]
  [-25. -53.  -5.]
  [-33. -63. -18.]
  ...
  [-20.  -7. -14.]
  [-20.  -7. -14.]
  [-21.  -8. -15.]]
 [[-21. -49.  -1.]
show more (open the raw output data in a text editor) ...
[-32. -31. -11.]
  ...
  [-30. -60. -15.]
  [-30. -60. -15.]
  [-30. -60. -15.]]]

The problem occured because the image dtype is uint which is unsigned, so it doesn't allow negative values (check a similar issue here).

so I found out you could also solve the problem with tf.cast(img, dtype=tf.float32).

  • Related