MCPcopy Create free account
hub / github.com/RylonW/DocNLC / tensor2img

Function tensor2img

utils/util.py:112–136  ·  view source on GitHub ↗

Converts a torch Tensor into an image Numpy array Input: 4D(B,(3/1),H,W), 3D(C,H,W), or 2D(H,W), any range, RGB channel order Output: 3D(H,W,C) or 2D(H,W), [0,255], np.uint8 (default)

(tensor, out_type=np.uint8, min_max=(0, 1))

Source from the content-addressed store, hash-verified

110
111
112def tensor2img(tensor, out_type=np.uint8, min_max=(0, 1)):
113 '''
114 Converts a torch Tensor into an image Numpy array
115 Input: 4D(B,(3/1),H,W), 3D(C,H,W), or 2D(H,W), any range, RGB channel order
116 Output: 3D(H,W,C) or 2D(H,W), [0,255], np.uint8 (default)
117 '''
118 tensor = tensor.squeeze().float().cpu().clamp_(*min_max) # clamp
119 tensor = (tensor - min_max[0]) / (min_max[1] - min_max[0]) # to range [0,1]
120 n_dim = tensor.dim()
121 if n_dim == 4:
122 n_img = len(tensor)
123 img_np = make_grid(tensor, nrow=int(math.sqrt(n_img)), normalize=False).numpy()
124 img_np = np.transpose(img_np[[2, 1, 0], :, :], (1, 2, 0)) # HWC, BGR
125 elif n_dim == 3:
126 img_np = tensor.numpy()
127 img_np = np.transpose(img_np[[2, 1, 0], :, :], (1, 2, 0)) # HWC, BGR
128 elif n_dim == 2:
129 img_np = tensor.numpy()
130 else:
131 raise TypeError(
132 'Only support 4D, 3D and 2D tensor. But received with dimension: {:d}'.format(n_dim))
133 if out_type == np.uint8:
134 img_np = (img_np * 255.0).round()
135 # Important. Unlike matlab, numpy.unit8() WILL NOT round by default.
136 return img_np.astype(out_type)
137
138
139def save_img(img, img_path, mode='RGB'):

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected