Converts a torch Tensor into an image Numpy array of BGR channel order 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))
| 340 | |
| 341 | # from skimage.io import imread, imsave |
| 342 | def tensor2img(tensor, out_type=np.uint8, min_max=(0, 1)): |
| 343 | ''' |
| 344 | Converts a torch Tensor into an image Numpy array of BGR channel order |
| 345 | Input: 4D(B,(3/1),H,W), 3D(C,H,W), or 2D(H,W), any range, RGB channel order |
| 346 | Output: 3D(H,W,C) or 2D(H,W), [0,255], np.uint8 (default) |
| 347 | ''' |
| 348 | tensor = tensor.squeeze().float().cpu().clamp_(*min_max) # squeeze first, then clamp |
| 349 | tensor = (tensor - min_max[0]) / (min_max[1] - min_max[0]) # to range [0,1] |
| 350 | n_dim = tensor.dim() |
| 351 | if n_dim == 4: |
| 352 | n_img = len(tensor) |
| 353 | img_np = make_grid(tensor, nrow=int(math.sqrt(n_img)), normalize=False).numpy() |
| 354 | img_np = np.transpose(img_np[[2, 1, 0], :, :], (1, 2, 0)) # HWC, BGR |
| 355 | elif n_dim == 3: |
| 356 | img_np = tensor.numpy() |
| 357 | img_np = np.transpose(img_np[[2, 1, 0], :, :], (1, 2, 0)) # HWC, BGR |
| 358 | elif n_dim == 2: |
| 359 | img_np = tensor.numpy() |
| 360 | else: |
| 361 | raise TypeError( |
| 362 | 'Only support 4D, 3D and 2D tensor. But received with dimension: {:d}'.format(n_dim)) |
| 363 | if out_type == np.uint8: |
| 364 | img_np = (img_np * 255.0).round() |
| 365 | # Important. Unlike matlab, numpy.unit8() WILL NOT round by default. |
| 366 | return img_np.astype(out_type) |
| 367 | |
| 368 | |
| 369 | ''' |
nothing calls this directly
no outgoing calls
no test coverage detected