Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
DavidFM43 opened this issue Dec 23, 2023 · 1 comment · May be fixed by #8369
Open

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

DavidFM43 opened this issue Dec 23, 2023 · 1 comment · May be fixed by #8369
Labels

Comments

@DavidFM43
Copy link

🐛 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.

# handle PIL Image
img = torch.as_tensor(np.array(pic, copy=True))

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.

# handle PIL Image
mode_to_nptype = {"I": np.int32, "I;16" if sys.byteorder == "little" else "I;16B": np.int16, "F": np.float32}
img = torch.from_numpy(np.array(pic, mode_to_nptype.get(pic.mode, np.uint8), copy=True))

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

@NicolasHug
Copy link
Member

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):

# handle PIL Image
mode_to_nptype = {"I": np.int32, "I;16" if sys.byteorder == "little" else "I;16B": np.int16, "F": np.float32}
img = torch.from_numpy(np.array(pic, mode_to_nptype.get(pic.mode, np.uint8), copy=True))

"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 991bad2.

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 NicolasHug added the bug label Mar 13, 2024
@NicolasHug NicolasHug linked a pull request Apr 3, 2024 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
Status: Must
Development

Successfully merging a pull request may close this issue.

2 participants