MCPcopy Create free account
hub / github.com/MaureenZOU/TSAM / ToTorchFormatTensor

Class ToTorchFormatTensor

src/data_loader/transform.py:277–295  ·  view source on GitHub ↗

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]

Source from the content-addressed store, hash-verified

275
276
277class 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
298class IdentityTransform(object):

Callers 2

evaluate_fid_scoreFunction · 0.90
transform.pyFile · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected