vision icon indicating copy to clipboard operation
vision copied to clipboard

pil_to_tensor() doesn't work for PIL Image with I;16 mode

Open DavidFM43 opened this issue 1 year ago • 1 comments

🐛 Describe the bug

The pil_to_tensor() function doesn't work when converting a PIL image with I;16 mode. Here's an example:

import torchvision
import torch

x = torch.randint(100, (512, 512), dtype=torch.int16)

x_pil = torchvision.transforms.functional.to_pil_image(x)
print("PIL Image mode:", x_pil.mode)  # I;16

torchvision.transforms.functional.pil_to_tensor(x_pil)

The error is the following:

Traceback (most recent call last):
  File "/home/david/ml-projects/pil-image-bug/bug.py", line 9, in <module>
    torchvision.transforms.functional.pil_to_tensor(x_pil)
  File "/home/david/ml-projects/vision/torchvision/transforms/functional.py", line 208, in pil_to_tensor
    img = torch.as_tensor(np.array(pic, copy=True))
TypeError: can't convert np.ndarray of type numpy.uint16. The only supported types are: float64, float32, float16, complex64, complex128, int64, int32, int16, int8, uint8, and bool.

Looking at the source code, it looks like the issue is caused because the PIL image is first converted to a numpy array of dtype np.uint16, and then to a pytorch tensor. Since uint16 is not supported in pytorch, the error occurs.

https://github.com/pytorch/vision/blob/ae6b134c6b395d81916ad47c08b5c64373a6afc5/torchvision/transforms/functional.py#L207-L208

Note that this doesn't happen when using to_tensor() since in that function, we create the numpy array with a pytorch supported dtype before converting it to a pytorch tensor.

https://github.com/pytorch/vision/blob/ae6b134c6b395d81916ad47c08b5c64373a6afc5/torchvision/transforms/functional.py#L165-L167

Replacing these 2 lines should fix the issue.

Versions

PyTorch version: 2.3.0.dev20231223+cpu Is debug build: False CUDA used to build PyTorch: None ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.3 LTS (x86_64) GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0 Clang version: Could not collect CMake version: Could not collect Libc version: glibc-2.35

Python version: 3.10.13 (main, Sep 11 2023, 13:44:35) [GCC 11.2.0] (64-bit runtime) Python platform: Linux-6.2.0-39-generic-x86_64-with-glibc2.35 Is CUDA available: False CUDA runtime version: No CUDA CUDA_MODULE_LOADING set to: N/A GPU models and configuration: No CUDA Nvidia driver version: No CUDA cuDNN version: No CUDA HIP runtime version: N/A MIOpen runtime version: N/A Is XNNPACK available: True

CPU: Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Address sizes: 39 bits physical, 48 bits virtual Byte Order: Little Endian CPU(s): 4 On-line CPU(s) list: 0-3 Vendor ID: GenuineIntel Model name: Intel(R) Core(TM) i7-7500U CPU @ 2.70GHz CPU family: 6 Model: 142 Thread(s) per core: 2 Core(s) per socket: 2 Socket(s): 1 Stepping: 9 CPU max MHz: 3500,0000 CPU min MHz: 400,0000 BogoMIPS: 5799.77 Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb invpcid_single pti ssbd ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid mpx rdseed adx smap clflushopt intel_pt xsaveopt xsavec xgetbv1 xsaves dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp md_clear flush_l1d arch_capabilities Virtualization: VT-x L1d cache: 64 KiB (2 instances) L1i cache: 64 KiB (2 instances) L2 cache: 512 KiB (2 instances) L3 cache: 4 MiB (1 instance) NUMA node(s): 1 NUMA node0 CPU(s): 0-3 Vulnerability Gather data sampling: Mitigation; Microcode Vulnerability Itlb multihit: KVM: Mitigation: VMX disabled Vulnerability L1tf: Mitigation; PTE Inversion; VMX conditional cache flushes, SMT vulnerable Vulnerability Mds: Mitigation; Clear CPU buffers; SMT vulnerable Vulnerability Meltdown: Mitigation; PTI Vulnerability Mmio stale data: Mitigation; Clear CPU buffers; SMT vulnerable Vulnerability Retbleed: Mitigation; IBRS Vulnerability Spec rstack overflow: Not affected Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization Vulnerability Spectre v2: Mitigation; IBRS, IBPB conditional, STIBP conditional, RSB filling, PBRSB-eIBRS Not affected Vulnerability Srbds: Mitigation; Microcode Vulnerability Tsx async abort: Not affected

Versions of relevant libraries: [pip3] flake8==6.1.0 [pip3] mypy==1.8.0 [pip3] mypy-extensions==1.0.0 [pip3] numpy==1.26.2 [pip3] torch==2.3.0.dev20231223+cpu [pip3] torchvision==0.18.0a0+ae6b134 [conda] numpy 1.26.2 pypi_0 pypi [conda] torch 2.3.0.dev20231223+cpu pypi_0 pypi [conda] torchvision 0.18.0a0+ae6b134 dev_0

DavidFM43 avatar Dec 23 '23 18:12 DavidFM43

Thank you for the report @DavidFM43 .

Unless I'm missing something, the way things are done in to_tensor() is just plain wrong (and the error you get in pil_to_tensor is actually a good thing):

https://github.com/pytorch/vision/blob/ae6b134c6b395d81916ad47c08b5c64373a6afc5/torchvision/transforms/functional.py#L165-L167

"I;16" denotes an unsigned 16bits type while np.int16 is signed. So copying the "I;16" pil image into a np.int16 array is going to saturate half of the value-space. This has been introduced way back in https://github.com/pytorch/vision/commit/991bad2f9e3945a9dc8192ed30483306f5f8f3ee.

I'm afraid the only clean way to fix that and to convert a "I:16" image into a int32 tensor? CC @vfdev-5 @pmeier in case you guys have more context on this

NicolasHug avatar Jan 02 '24 11:01 NicolasHug