Converts a PyTorch tensor to a PIL image. Automatically moves the channel dimension (if it has size 3) to the last axis before converting. Args: tensor (torch.Tensor): Input tensor. Expected shape can be [C, H, W], [H, W, C], or [H, W]. Returns: PIL.Image: The
(tensor)
| 84 | |
| 85 | |
| 86 | def tensor_to_pil(tensor): |
| 87 | """ |
| 88 | Converts a PyTorch tensor to a PIL image. Automatically moves the channel dimension |
| 89 | (if it has size 3) to the last axis before converting. |
| 90 | |
| 91 | Args: |
| 92 | tensor (torch.Tensor): Input tensor. Expected shape can be [C, H, W], [H, W, C], or [H, W]. |
| 93 | |
| 94 | Returns: |
| 95 | PIL.Image: The converted PIL image. |
| 96 | """ |
| 97 | if torch.is_tensor(tensor): |
| 98 | array = tensor.detach().cpu().numpy() |
| 99 | else: |
| 100 | array = tensor |
| 101 | |
| 102 | return array_to_pil(array) |
| 103 | |
| 104 | |
| 105 | def array_to_pil(array): |
nothing calls this directly
no test coverage detected