tensor2im

def tensor2im(image_tensor, imtype=np.uint8, normalize=True):
    if isinstance(image_tensor, list):
        image_numpy = []
        for i in range(len(image_tensor)):
            image_numpy.append(tensor2im(image_tensor[i], imtype, normalize))
        return image_numpy
    image_numpy = image_tensor.cpu().float().numpy()
    if normalize:
        image_numpy = (np.transpose(image_numpy, (1, 2, 0)) + 1) / 2.0 * 255.0
    else:
        image_numpy = np.transpose(image_numpy, (1, 2, 0)) * 255.0      
    image_numpy = np.clip(image_numpy, 0, 255)
    if image_numpy.shape[2] == 1 or image_numpy.shape[2] > 3:        
        image_numpy = image_numpy[:,:,0]
    return image_numpy.astype(imtype)

image_tensor里面的数值为(-1,1),现在需要将图像换成图像格式(0,255)

1、np.transpose()

代码:

import numpy as np

a = np.array(range(30)).reshape(2, 3, 5)
b = a.transpose(1, 0, 2)
print ("a = ")
print (a)
print (a.shape)
print ("===================== \n")
 
print ("a.transpose() = ")
print (b)
print (b.shape)

运行结果:

 

 2、np.clip()

代码:

import numpy as np
x=np.array([1,2,3,5,6,7,8,9])
y=np.clip(x,3,8)
print (y)

运行结果:

 

posted @ 2020-02-18 14:50  皮卡皮卡妞  阅读(811)  评论(0编辑  收藏  举报