MCPcopy
hub / github.com/open-mmlab/mmpose / to_numpy

Function to_numpy

mmpose/utils/tensor_utils.py:11–53  ·  view source on GitHub ↗

Convert torch tensor to numpy.ndarray. Args: x (Tensor | Sequence[Tensor]): A single tensor or a sequence of tensors return_device (bool): Whether return the tensor device. Defaults to ``False`` unzip (bool): Whether unzip the input sequence. Defa

(x: Union[Tensor, Sequence[Tensor]],
             return_device: bool = False,
             unzip: bool = False)

Source from the content-addressed store, hash-verified

9
10
11def to_numpy(x: Union[Tensor, Sequence[Tensor]],
12 return_device: bool = False,
13 unzip: bool = False) -> Union[np.ndarray, tuple]:
14 """Convert torch tensor to numpy.ndarray.
15
16 Args:
17 x (Tensor | Sequence[Tensor]): A single tensor or a sequence of
18 tensors
19 return_device (bool): Whether return the tensor device. Defaults to
20 ``False``
21 unzip (bool): Whether unzip the input sequence. Defaults to ``False``
22
23 Returns:
24 np.ndarray | tuple: If ``return_device`` is ``True``, return a tuple
25 of converted numpy array(s) and the device indicator; otherwise only
26 return the numpy array(s)
27 """
28
29 if isinstance(x, Tensor):
30 arrays = x.detach().cpu().numpy()
31 device = x.device
32 elif isinstance(x, np.ndarray) or is_seq_of(x, np.ndarray):
33 arrays = x
34 device = 'cpu'
35 elif is_seq_of(x, Tensor):
36 if unzip:
37 # convert (A, B) -> [(A[0], B[0]), (A[1], B[1]), ...]
38 arrays = [
39 tuple(to_numpy(_x[None, :]) for _x in _each)
40 for _each in zip(*x)
41 ]
42 else:
43 arrays = [to_numpy(_x) for _x in x]
44
45 device = x[0].device
46
47 else:
48 raise ValueError(f'Invalid input type {type(x)}')
49
50 if return_device:
51 return arrays, device
52 else:
53 return arrays
54
55
56def to_tensor(x: Union[np.ndarray, Sequence[np.ndarray]],

Callers 15

head_lossMethod · 0.90
decodeMethod · 0.90
lossMethod · 0.90
lossMethod · 0.90
lossMethod · 0.90
lossMethod · 0.90
lossMethod · 0.90
lossMethod · 0.90
lossMethod · 0.90
lossMethod · 0.90
decodeMethod · 0.90
lossMethod · 0.90

Calls 3

numpyMethod · 0.80
cpuMethod · 0.80
detachMethod · 0.80

Tested by 1