Skip to content

[bug] trying to save a tensor to image, changes its content #1719

@mattans

Description

@mattans

I have a float tensor in range 0-1 that I want to save as binary image.
I get this stack trace:

b=batch(4)
C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.3\helpers\pydev\pydevconsole.py:75: RuntimeWarning: invalid value encountered in double_scalars
  m = save_main_module('<input>', 'pydevconsole')
c = b[2]
c.max()
Out[136]: tensor(1., dtype=torch.float64)

c = c.view(-1 ,256, 256)
c.max()
Out[138]: tensor(1., dtype=torch.float64)

torchvision.utils.save_image(c, r"C:\shrec\temp.png")
Traceback (most recent call last):
  File "C:\Users\t-maserr\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\Image.py", line 2533, in fromarray
    mode, rawmode = _fromarray_typemap[typekey]
KeyError: ((1, 1, 32), '|u1')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "C:\Users\t-maserr\AppData\Local\Programs\Python\Python37\lib\site-packages\IPython\core\interactiveshell.py", line 3319, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-139-fe16f2ca20a4>", line 1, in <module>
    torchvision.utils.save_image(c, r"C:\shrec\temp.png")
  File "C:\Users\t-maserr\AppData\Local\Programs\Python\Python37\lib\site-packages\torchvision\utils.py", line 104, in save_image
    im = Image.fromarray(ndarr)
  File "C:\Users\t-maserr\AppData\Local\Programs\Python\Python37\lib\site-packages\PIL\Image.py", line 2535, in fromarray
    raise TypeError("Cannot handle this data type")
TypeError: Cannot handle this data type

c.max()
Out[140]: tensor(255., dtype=torch.float64)

Notice how the maximum value of the tensor is 1 before trying to save it, then it changes to 255.
It somehow scaled from 0:1 to the 127:255 range.

Latest PyTorch + TorchVision, on Python 3.7, Windows.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions