- 
                Notifications
    You must be signed in to change notification settings 
- Fork 7.2k
Add pil_to_tensor to functionals #2092
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
Changes from all commits
286e316
              f7eb489
              f90b3bc
              9c2fd3b
              08ab5ec
              cb19ed4
              38ad5f3
              1fa91a8
              0fefbcb
              7662b23
              75be7bb
              123503a
              eff1db0
              266860a
              610fc1e
              b9cca77
              1b10f77
              fbf661c
              598107f
              d69048e
              fa1084c
              2cb7a4f
              3d565fd
              File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | 
|---|---|---|
|  | @@ -82,6 +82,33 @@ def to_tensor(pic): | |
| return img | ||
|  | ||
|  | ||
| def pil_to_tensor(pic): | ||
| """Convert a ``PIL Image`` to a tensor of the same type. | ||
|  | ||
| See ``AsTensor`` for more details. | ||
|  | ||
| Args: | ||
| pic (PIL Image): Image to be converted to tensor. | ||
|  | ||
| Returns: | ||
| Tensor: Converted image. | ||
| """ | ||
| if not(_is_pil_image(pic)): | ||
| raise TypeError('pic should be PIL Image. Got {}'.format(type(pic))) | ||
|  | ||
| if accimage is not None and isinstance(pic, accimage.Image): | ||
| nppic = np.zeros([pic.channels, pic.height, pic.width], dtype=np.float32) | ||
| pic.copyto(nppic) | ||
| return torch.as_tensor(nppic) | ||
|  | ||
| # handle PIL Image | ||
| img = torch.as_tensor(np.asarray(pic)) | ||
| There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This line will still produce the same bug mentioned in #2194. Converting to numpy with  There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think we will wait until PyTorch fixes this behavior in master, as making a copy would be fairly expensive. If the warnings are too annoying, an alternative would be to only use  | ||
| img = img.view(pic.size[1], pic.size[0], len(pic.getbands())) | ||
| # put it from HWC to CHW format | ||
| img = img.permute((2, 0, 1)) | ||
| return img | ||
|  | ||
|  | ||
| def to_pil_image(pic, mode=None): | ||
| """Convert a tensor or an ndarray to PIL Image. | ||
|  | ||
|  | ||
Uh oh!
There was an error while loading. Please reload this page.