transforms可以用來改變樣本的多樣性,例如:旋轉、平移等等,訓練圖像辨識時,一定會用到的工具,現在來跟大家介紹他有哪些用法!我拿還未處理過的資料來當示範。這裡我把圖片都轉換成400*400的大小。
from torchvision import transforms
from PIL import Image
def img_loader(img_path):
image = Image.open(img_path)
img = image.resize((400, 400),Image.ANTIALIAS)
return img.convert('RGB')
img = img_loader(r"C:\Users\Frank\PycharmProjects\practice\mountain\train\5_拓.jpg")
img.show()
tranform = transforms.Compose([transforms.CenterCrop(size=((200,200)))])
img = tranform(img)
img.show()
img = img_loader(r"C:\Users\Frank\PycharmProjects\practice\mountain\train\5_拓.jpg")
img.show()
tranform = transforms.Compose([transforms.CenterCrop(size=((750,500)))])
img = tranform(img)
img.show()
隨機裁剪:transforms.RandomCrop
將圖檔隨機裁剪你設定的size。
img = img_loader(r"C:\Users\Frank\PycharmProjects\practice\mountain\train\5_拓.jpg")
img.show()
tranform = transforms.Compose([transforms.RandomCrop(size=((200,200)),padding=100)])
img = tranform(img)
img.show()
img = img_loader(r"C:\Users\Frank\PycharmProjects\practice\mountain\train\5_拓.jpg")
img.show()
tranform = transforms.Compose([transforms.RandomCrop(size=((200,200)),padding=100,fill = (255,0,0))])
img = tranform(img)
img.show()
隨機大小及隨機長寬比裁剪原始圖片,最後再resize到設定好的size。
img = img_loader(r"C:\Users\Frank\PycharmProjects\practice\mountain\train\5_拓.jpg")
img.show()
tranform = transforms.Compose([transforms.RandomResizedCrop(size = (200,200),scale=(0.2, 1.0), ratio=(0.5, 1.1))])
img = tranform(img)
img.show()
依照P的機率,資料集的P倍圖片會被水平翻轉。
img = img_loader(r"C:\Users\Frank\PycharmProjects\practice\mountain\train\5_拓.jpg")
img.show()
tranform = transforms.Compose([transforms.RandomVerticalFlip(p = 0.9)])
img = tranform(img)
img.show()
垂直翻轉:RandomHorizontalFlip
依照P的機率,資料集的P倍圖片會被垂直翻轉。
img = img_loader(r"C:\Users\Frank\PycharmProjects\practice\mountain\train\5_拓.jpg")
tranform = transforms.Compose([transforms.RandomHorizontalFlip(p = 0.9)])
img = tranform(img)
img.show()
隨機旋轉:RandomRotation
依照設置的degrees,隨機旋轉圖片。
img = img_loader(r"C:\Users\Frank\PycharmProjects\practice\mountain\train\5_拓.jpg")
tranform = transforms.Compose([transforms.RandomRotation(degrees = 30,center=(0,0))])
img = tranform(img)
img.show()
填補:Pad
img = img_loader(r"C:\Users\Frank\PycharmProjects\practice\mountain\train\5_拓.jpg")
tranform = transforms.Compose([transforms.Pad(padding = 30,fill=(255,200,0))])
img = tranform(img)
img.show()