transforms + PIL實踐裁剪圖片和image和tensor的轉換

截取了pix2pix源代碼的aligned_dataset.py文件中的部分代碼,進行單個圖片測試

import random
import torchvision.transforms as transforms
from PIL import Image


AB = Image.open('fn18.jpg').convert('RGB') #利用Image大家打開圖片,原圖是一張寬高比爲2:1的圖片
print(AB.size)
#AB = AB.resize((512,256), Image.BICUBIC)
AB = transforms.ToTensor()(AB)#圖片轉成tensor
print(AB.shape)
w_total = AB.size(2)
w = int(w_total / 2)
h = AB.size(1)
print("w_total:%d, w:%d, h:%d"%(w_total,w,h))# w_total:512, w:256, h:256
#w_offset = random.randint(0, max(0, 29))#設置隨機裁剪
#h_offset = random.randint(0, max(0, 29))
#A = AB[:, h_offset:h_offset + self.opt.fineSize,w_offset:w_offset + self.opt.fineSize]
#B = AB[:, h_offset:h_offset + self.opt.fineSize,w + w_offset:w + w_offset +self.opt.fineSize]
A = AB[:, 0:h, 0:w]#截取照片三個通道、從0~h的高,從0~w的寬
print(A.shape)
B = AB[:, 0:h, w:w_total]#截取照片三個通道、從0~h的高,從w~w_total的寬
print(B.shape)
#tensor轉換成圖片
imgAB = transforms.ToPILImage()(AB.float())
imgAB.show()
imgA = transforms.ToPILImage()(A.float())
imgA.show()
imgB = transforms.ToPILImage()(B.float())
imgB.show()
# A = transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))(A)#訓練時進行歸一化處理
# B = transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))(B)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章