zl程序教程

您现在的位置是:首页 >  其他

当前栏目

将tensor转换为图像_tensor转int

转换 图像 int Tensor
2023-06-13 09:14:43 时间

将tensor转换为numpy

import tensor 
import numpy as np
def tensor2img(tensor, out_type=np.uint8, min_max=(0, 1)):
''' 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) '''
if hasattr(tensor, 'detach'):
tensor = tensor.detach()
tensor = tensor.squeeze().float().cpu().clamp_(*min_max)  # clamp
tensor = (tensor - min_max[0]) / (min_max[1] - min_max[0])  # to range [0,1]
n_dim = tensor.dim()
if n_dim == 4:
n_img = len(tensor)
img_np = make_grid(tensor, nrow=int(math.sqrt(n_img)), normalize=False).numpy()
img_np = np.transpose(img_np[[2, 1, 0], :, :], (1, 2, 0))  # HWC, BGR
elif n_dim == 3:
img_np = tensor.numpy()
img_np = np.transpose(img_np[[2, 1, 0], :, :], (1, 2, 0))  # HWC, BGR
elif n_dim == 2:
img_np = tensor.numpy()
else:
raise TypeError(
'Only support 4D, 3D and 2D tensor. But received with dimension: {:d}'.format(n_dim))
if out_type == np.uint8:
img_np = np.clip((img_np * 255.0).round(), 0, 255)
# Important. Unlike matlab, numpy.unit8() WILL NOT round by default.
return img_np.astype(out_type)

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/183609.html原文链接:https://javaforall.cn