1. 程式人生 > >pytorch中對影象的基本操作

pytorch中對影象的基本操作

Pytorch提供了一個torchvision.transforms的包,可以使用transforms進行如下操作:

1、PIL.image / numpy. ndarray 與Tensor相互轉化

2、進行歸一化

3、對PIL.image進行裁剪、縮放等操作

一、PIL.image / numpy. ndarray 轉化為Tensor,常常在訓練模型階段進行資料讀取

Tensor轉化為PIL.image / numpy. ndarray則使用在驗證模型階段的資料輸出

使用transforms.ToTensor()將PIL.image / numpy. ndarray轉化為torch.FloatTensor,再轉化為【0,1.0】

 

使用transforms.ToPILImage將Tensor轉化為PIL.image

二、對Tensor進行變換

class torchvision.transforms.Normalize(mean, std)

給定均值:(R,G,B);    方差:(R,G,B)   將會把Tensor正則化,即Normalized_image=(image-mean)/std

例如:把一個取值範圍為【0,255】的PIL.Image  或者shape 為(H,W,C)的numpy.ndarray

轉換成形狀為【C,H,W】,其取值範圍為【0,1.0】的troch.FloadTensor

程式碼實現:

data=np.random.randint(0,255,size=300)

img=data.reshape(10,10,3)

print(img.shape)

img_tensor=transforms.ToTensor()(img) #轉換成Tensor

print(img_tensor)

(PS : 其實不太懂這個,到底怎麼用)