MCPcopy Create free account
hub / github.com/THUYimingLi/BackdoorBox / _any2tensor

Function _any2tensor

core/utils/any2tensor.py:8–33  ·  view source on GitHub ↗

Convert a strpath, PIL.Image.Image, numpy.ndarray, torch.Tensor object to a torch.Tensor object. Args: x (strpath | PIL.Image.Image | numpy.ndarray | torch.Tensor): numpy.ndarray and torch.Tensor can have any shape. Hint: For strpath, x is converted to a torch.Tensor with shape

(x)

Source from the content-addressed store, hash-verified

6
7
8def _any2tensor(x):
9 """Convert a strpath, PIL.Image.Image, numpy.ndarray, torch.Tensor object to a torch.Tensor object.
10
11 Args:
12 x (strpath | PIL.Image.Image | numpy.ndarray | torch.Tensor): numpy.ndarray and torch.Tensor can have any shape.
13 Hint: For strpath, x is converted to a torch.Tensor with shape (C, H, W), the channel order is decided by opencv.
14 For PIL.Image.Image, x is converted to a torch.Tensor with shape (C, H, W), the channel order is decided by x itself.
15 The channel order between opencv and PIL is different.
16
17 Returns:
18 torch.Tensor: The converted object.
19 """
20 if type(x) == str:
21 tmp = cv2.imread(x, cv2.IMREAD_UNCHANGED)
22 if tmp.ndim == 2:
23 return torch.from_numpy(tmp.reshape(1, tmp.shape[0], tmp.shape[1]))
24 else:
25 return torch.from_numpy(tmp.transpose((2, 0, 1)))
26 elif type(x) == PIL.Image.Image:
27 return F.pil_to_tensor(x)
28 elif type(x) == numpy.ndarray:
29 return torch.from_numpy(x)
30 elif type(x) == torch.Tensor:
31 return x.clone().detach()
32 else:
33 raise TypeError('x is an unsupported type, x should be strpath or PIL.Image.Image or numpy.ndarray or torch.Tensor. But got {}'.format(type(x)))
34
35
36def any2tensor(imgs):

Callers 1

any2tensorFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected