日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

Pytorch如何把Tensor轉(zhuǎn)化成圖像可視化_python

作者:亂覺先森 ? 更新時間: 2023-01-11 編程語言

Pytorch把Tensor轉(zhuǎn)化成圖像可視化

在調(diào)試程序的時候經(jīng)常想把tensor可視化成來看看,可以這樣操作:

from torchvision import transforms
unloader = transforms.ToPILImage()
image = original_tensor.cpu().clone() ?# clone the tensor
image = image.squeeze(0) ?# remove the fake batch dimension
image = unloader(image)
image.save('example.jpg')

pytorch標(biāo)準(zhǔn)化的Tensor轉(zhuǎn)圖像問題

常常在工作之中遇到將dataloader中出來的tensor成image,numpy格式的數(shù)據(jù),然后可以可視化出來

但是這種tensor往往經(jīng)過了channel變換(RGB2BGR),以及歸一化(減均值除方差),

然后維度的順序也發(fā)生變化(HWC變成CHW)。為了可視化這種變化比較多的數(shù)據(jù),

在tensor轉(zhuǎn)numpy之前需要對tensor做一些處理

如下是一個簡單的函數(shù),可以可視化tensor,下次直接拿來用就行

def tensor2im(input_image, imtype=np.uint8):
    """"
    Parameters:
        input_image (tensor) --  輸入的tensor,維度為CHW,注意這里沒有batch size的維度
        imtype (type)        --  轉(zhuǎn)換后的numpy的數(shù)據(jù)類型
    """
    mean = [0.485, 0.456, 0.406] # dataLoader中設(shè)置的mean參數(shù),需要從dataloader中拷貝過來
    std = [0.229, 0.224, 0.225]  # dataLoader中設(shè)置的std參數(shù),需要從dataloader中拷貝過來
    if not isinstance(input_image, np.ndarray):
        if isinstance(input_image, torch.Tensor): # 如果傳入的圖片類型為torch.Tensor,則讀取其數(shù)據(jù)進(jìn)行下面的處理
            image_tensor = input_image.data
        else:
            return input_image
        image_numpy = image_tensor.cpu().float().numpy()  # convert it into a numpy array
        if image_numpy.shape[0] == 1:  # grayscale to RGB
            image_numpy = np.tile(image_numpy, (3, 1, 1))
        for i in range(len(mean)): # 反標(biāo)準(zhǔn)化,乘以方差,加上均值
            image_numpy[i] = image_numpy[i] * std[i] + mean[i]
        image_numpy = image_numpy * 255 #反ToTensor(),從[0,1]轉(zhuǎn)為[0,255]
        image_numpy = np.transpose(image_numpy, (1, 2, 0))  # 從(channels, height, width)變?yōu)?height, width, channels)
    else:  # 如果傳入的是numpy數(shù)組,則不做處理
        image_numpy = input_image
    return image_numpy.astype(imtype)

總結(jié)

原文鏈接:https://blog.csdn.net/weixin_40520963/article/details/105783025

欄目分類
最近更新