Converts a PIL.Image (RGB) or numpy.ndarray (H x W x C) in the range [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0]
| 275 | |
| 276 | |
| 277 | class ToTorchFormatTensor(object): |
| 278 | """ Converts a PIL.Image (RGB) or numpy.ndarray (H x W x C) in the range [0, 255] |
| 279 | to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0] """ |
| 280 | def __init__(self, div=True): |
| 281 | self.div = div |
| 282 | |
| 283 | def __call__(self, pic): |
| 284 | if isinstance(pic, np.ndarray): |
| 285 | # handle numpy array |
| 286 | img = torch.from_numpy(pic).permute(2, 3, 0, 1).contiguous() |
| 287 | # img: [L, C, H, W] |
| 288 | else: |
| 289 | # handle PIL Image |
| 290 | img = torch.ByteTensor(torch.ByteStorage.from_buffer(pic.tobytes())) |
| 291 | img = img.view(pic.size[1], pic.size[0], len(pic.mode)) |
| 292 | # put it from HWC to CHW format |
| 293 | # yikes, this transpose takes 80% of the loading time/CPU |
| 294 | img = img.transpose(0, 1).transpose(0, 2).contiguous() |
| 295 | return img.float().div(255) if self.div else img.float() |
| 296 | |
| 297 | |
| 298 | class IdentityTransform(object): |
no outgoing calls
no test coverage detected