Search code examples
pythontensorflowpytorchtorchvision

Why do torchvision.transforms.Resize and tensorflow.image.resize_images get different results


I tried to resize the same tensor with these two functions. The interpolation method I'm using is bilinear and I don't understand why I'm getting a different output

I have tried my test code as follows:

import torch 
import torch.nn as nn 

size_psc = 128

torch.manual_seed(123)
x0 = torch.randn(torch.Size([1, 64, 502, 502]))

#using torchvision
import torchvision.transforms as transforms
resize = transforms.Resize((size_psc, size_psc))
torch_resize_out = resize(x0)

#using tensorflow
import tensorflow as tf
tf_x0 = x0.permute(0, 2, 3, 1).contiguous()
tf_resize = tf.image.resize_images(tf_x0, (size_psc, size_psc), 0)
sess = tf.Session()
tf_resize_out = sess.run(tf_resize)
sess.close()
tf_resize_out = torch.Tensor(tf_resize_out)
tf_resize_out = tf_resize_out.permute(0, 3, 1, 2).contiguous()

assert torch.max(abs(torch_resize_out - tf_resize_out)) < 1e-5

The requirements I use are as follows:
torchvision (0.11.2)
torch (1.10.1)
tensorflow (1.10.0)

I want to get the same result. However, the results of these two functions are obviously different.I don't understand why both use bilinear interpolation but get different results


Solution

  • Meh, your code must be quite old.
    I tried this in colab and no error. They are identical.

    import torch 
    import torch.nn as nn 
    
    size_psc = 128
    
    torch.manual_seed(123)
    x0 = torch.randn(torch.Size([1, 64, 502, 502]))
    
    #using torchvision
    import torchvision.transforms as transforms
    resize = transforms.Resize((size_psc, size_psc))
    torch_resize_out = resize(x0)
    
    #using tensorflow
    import tensorflow as tf
    tf_x0 = x0.permute(0, 2, 3, 1).contiguous()
    tf_resize = tf.image.resize(tf_x0, (size_psc, size_psc))
    tf_resize_out = tf_resize.numpy()
    tf_resize_out = torch.Tensor(tf_resize_out)
    tf_resize_out = tf_resize_out.permute(0, 3, 1, 2).contiguous()
    
    assert torch.max(abs(torch_resize_out - tf_resize_out)) < 1e-5