pytorch / pytorch/vision

Float PILImage not converted as writeable

Open
#2,194 8 comments 9 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
17.9k
Forks
7.3k
Avg merge
1d 15h
Merged PRs (30d)
13

Description

🐛 Bug

When we have a float PIL-Image (e.g. mode='F'), e.g. for the purpose of applying transforms to it, and finally convert it with ToTensor then it will print the warning

/opt/conda/conda-bld/pytorch_1587428094786/work/torch/csrc/utils/tensor_numpy.cpp:141: UserWarning: The given NumPy array is not writeable, and PyTorch does not support non-writeable tensors. This means you can write to the underlying (supposedly non-writeable) NumPy array using the tensor. You may want to copy the array to protect its data or make it writeable before converting it to a tensor. This type of warning will be suppressed for the rest of this program.

The writeability of the numpy array got lost somewhere when converting a numpy array to PILImage with Image.fromarray(numpy_array, mode='F') and then after some transforms to a tensor with ToTensor.
This does not happen with PIL Images other than float (e.g. mode='RGB').

This warning is especially annoying since it gets printed every epoch.

To Reproduce

Steps to reproduce the behavior:

    from torchvision.transforms import ToTensor
    import numpy as np
    from PIL import Image
    a = np.array([[1.0,0.5], [1.0,0.5]])
    print(a.flags.writeable)
    pilimg = Image.fromarray(a, mode='F')
    tensor = ToTensor()(pilimg)
    print(tensor.numpy().flags)

    b = np.asarray(pilimg)
    c = np.array(pilimg)
    print(b.flags)
    print(c.flags)

This code will print above warning.

Also note the following:

  • the numpy array b is NOT writeable, the numpy array c is writeable.
  • This suggests that the error is located in the conversion from numpy to PIL.
  • But since I do not have the easy possibility to convert PIL to numpy and then to tensor within a transforms Compose and since numpy array c is writeable, I open this issue here.

As workaround I do the following:

class ToNumpy(object):
    def __call__(self, sample):
        return np.array(sample)

def fix_compose_transform(transform):
        if isinstance(transform.transforms[-1], torchvision.transforms.ToTensor):
            transform = torchvision.transforms.Compose([
                *transform.transforms[:-1],
                ToNumpy(),
                torchvision.transforms.ToTensor()
            ])
        return transform

Expected behavior

Warning is not printed and ToTensor method can deal with the misbehaviour of PIL image.

Environment

Collecting environment information...
PyTorch version: 1.5.0
Is debug build: No
CUDA used to build PyTorch: 10.1

OS: Ubuntu 18.04.4 LTS
GCC version: (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0
CMake version: version 3.10.2

Python version: 3.8
Is CUDA available: Yes
CUDA runtime version: 10.1.243
GPU models and configuration: GPU 0: GeForce GTX 970
Nvidia driver version: 418.87.01
cuDNN version: Could not collect

Versions of relevant libraries:
[pip3] numpy==1.18.3
[conda] blas                      1.0                         mkl  
[conda] cudatoolkit               10.1.243             h6bb024c_0  
[conda] mkl                       2020.0                      166  
[conda] mkl-service               2.3.0            py38he904b0f_0  
[conda] mkl_fft                   1.0.15           py38ha843d7b_0  
[conda] mkl_random                1.1.0            py38h962f231_0  
[conda] numpy                     1.18.1           py38h4f9e942_0  
[conda] numpy-base                1.18.1           py38hde5b4d6_1  
[conda] numpydoc                  0.9.2                      py_0  
[conda] pytorch                   1.5.0           py3.8_cuda10.1.243_cudnn7.6.3_0    pytorch
[conda] pytorch3d                 0.1.1                    pypi_0    pypi
[conda] torchvision               0.6.0                py38_cu101    pytorch

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at torchvision.transforms.ToTensor and reproduce the reported conversion with a float PIL image in mode='F', comparing it with the RGB case and the writable copy from np.array. Done means the float-image conversion no longer emits the non-writeable NumPy warning while preserving the expected tensor result.

Written by the indexing model from the issue text.

Assessment

Tech stack
numpy, python
Domain
computer-vision
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.