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]
| 179 | |
| 180 | |
| 181 | class ToTorchFormatTensor(object): |
| 182 | """ Converts a PIL.Image (RGB) or numpy.ndarray (H x W x C) in the range [0, 255] |
| 183 | to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0] """ |
| 184 | def __init__(self, div=True): |
| 185 | self.div = div |
| 186 | |
| 187 | def __call__(self, pic_tuple): |
| 188 | pic, label = pic_tuple |
| 189 | |
| 190 | if isinstance(pic, np.ndarray): |
| 191 | # handle numpy array |
| 192 | img = torch.from_numpy(pic).permute(2, 0, 1).contiguous() |
| 193 | else: |
| 194 | # handle PIL Image |
| 195 | img = torch.ByteTensor(torch.ByteStorage.from_buffer(pic.tobytes())) |
| 196 | img = img.view(pic.size[1], pic.size[0], len(pic.mode)) |
| 197 | # put it from HWC to CHW format |
| 198 | # yikes, this transpose takes 80% of the loading time/CPU |
| 199 | img = img.transpose(0, 1).transpose(0, 2).contiguous() |
| 200 | return (img.float().div(255.) if self.div else img.float(), label) |
| 201 | |
| 202 | |
| 203 | class IdentityTransform(object): |