Pytorch筆記:02 torchvision.transforms數據增強

2021-02-20 愛折騰的Lino


2.中心裁剪:transforms.CenterCrop

torchvision.transforms.CenterCrop(size=256)(image)

3.隨機長寬比裁剪:transforms.RandomResizedCrop

torchvision.transforms.RandomResizedCrop(size=256)(image)

4.上下左右中心裁剪:transforms.FiveCrop

images = torchvision.transforms.FiveCrop(size=256)(image)images

5.上下左右中心裁剪後翻轉:transforms.TenCrop

# 跟上面的一樣,第二個參數設置成false為水平翻轉torchvision.transforms.TenCrop(256)(image)

翻轉與旋轉

6.依概率p水平翻轉:transforms.RandomHorizontalFlip

torchvision.transforms.RandomHorizontalFlip(p=0.9)(image)

7.依概率垂直翻轉:transforms.RandomVerticalFlip

torchvision.transforms.RandomVerticalFlip(p=0.9)(image)


8.隨機旋轉:transforms.RandomRotation

torchvision.transforms.RandomRotation((45,90))(image)

degress:旋轉角度,可以是整數或者是區間,整數會在正負間隨機。區間則為區間內隨機

resample:重採樣,可選PIL.Image.NEAREST, PIL.Image.BILINEAR, PIL.Image.BICUBIC,默認為最近鄰

center:可選為中心旋轉還是左上角旋轉




圖像變換


9.resize:transforms.Resize

# 插值方法默認是雙線性插值torchvision.transforms.Resize(256)(image)


10.轉為tensor:transforms.ToTensor

tensor_image = torchvision.transforms.ToTensor()(image)tensor_image

11.標準化:transforms.Normalize

# mean與std是有固定值的,需要看論文torchvision.transforms.Normalize(mean=[0.5,0.5,0.5],std=[0.5,0.5,0.5])(tensor_image)

12.填充:transforms.Pad

torchvision.transforms.Pad(20)(image)

padding:填充多少個參數,可以是單個,2個值的序列以及四個值的序列,2個值時第一個值為左右,第二個值為上下。4個值的時候對應著左上右下。

fill:int時,各通道均填充該值,當長度為3的tuple時,表示RGB通道需要填充的值。

padding_mode:填充模式,這裡提供了4種填充模式,1.constant,常量。2.edge 按照圖片邊緣的像素值來填充。3.reflect 4. symmetric


13.修改亮度、對比度和飽和度:transforms.ColorJitter

torchvision.transforms.ColorJitter(brightness=2,contrast=0,saturation=1)(image)


14.轉灰度圖:transforms.Grayscale

torchvision.transforms.Grayscale()(image)


15.線性變換:transforms.LinearTransformation

使用方形變換矩陣和離線計算的mean_vector變換張量圖像。給定transformation_matrix和mean_vector,將使矩陣變平。從中拉伸並減去mean_vector,然後用變換矩陣計算點積,然後將張量重新整形為其原始形狀。
白化轉換:假設X是列向量零中心數據。然後torch.mm計算數據協方差矩陣[D x D],對該矩陣執行SVD並將其作為transformation_matrix傳遞。(有理論依據,查論文時用)

# 兩個參數未填torchvision.transforms.LinearTransformation()(tensor_image)


16.仿射變換:transforms.RandomAffine

torchvision.transforms.RandomAffine(30)(image)

degrees(sequence 或float或int) -要選擇的度數範圍。如果degrees是一個數字而不是像(min,max)這樣的序列,則度數範圍將是(-degrees,+degrees)。設置為0可停用旋轉。

translate(元組,可選) - 水平和垂直平移的最大絕對分數元組。例如translate =(a,b),然後在範圍-img_width * a <dx <img_width * a中隨機採樣水平移位,並且在-img_height * b <dy <img_height * b範圍內隨機採樣垂直移位。默認情況下不會翻譯。

scale(元組,可選) - 縮放因子間隔,例如(a,b),然後從範圍a <= scale <= b中隨機採樣縮放。默認情況下會保持原始比例。

shear(sequence 或float或int,optional) - 要選擇的度數範圍。如果degrees是一個數字而不是像(min,max)這樣的序列,則度數範圍將是(-degrees,+ degrees)。默認情況下不會應用剪切

resample({PIL.Image.NEAREST ,PIL.Image.BILINEAR ,PIL.Image.BICUBIC} ,可選) - 可選的重採樣過濾器。請參閱過濾器以獲取更多信 如果省略,或者圖像具有模式「1」或「P」,則將其設置為PIL.Image.NEAREST。

fillcolor(int) - 輸出圖像中變換外部區域的可選填充顏色。(Pillow> = 5.0.0)


17.依概率p轉換成灰度圖:transforms.RandomGrayscale

# 沒啥好說的torchvision.transforms.RandomGrayscale(0.8)(image)


18.將數據轉換成PILImage:transforms.ToPILImage

# tensor_image是tensor類型數據torchvision.transforms.ToPILImage()(tensor_image)


19.transforms.Lambda

# 自定義一個左上角裁剪方法class MyCrop:        def __init__(self,size=224):        self.size = size        def __call__(self,img):        ow,oh = img.size        x1,y1 = (0,0)        tw = th = self.size        # 有足夠的大小截取        # img.crop坐標表示 (left, upper, right, lower)        if (ow > tw or oh > th):            return img.crop((x1, y1, x1+tw, y1+th))        return img        def __repr__(self):        return self.__class__.__name__ + '(size={0})'.format(self.size)
img = torchvision.transforms.Lambda(MyCrop(256))(image)img




對transforms組合進行操作

20.組合中隨機選一個進行操作:transforms.RandomChoice

transforms = [    torchvision.transforms.Grayscale(),     torchvision.transforms.CenterCrop(256) ]

torchvision.transforms.RandomChoice(transforms)(image)


21.給一組變換加上概率:transforms.RandomApply

# 數組中所有變換都會應用上去torchvision.transforms.RandomApply(transforms[:],0.8)(image)


22.打亂transforms中的順序:transforms.RandomOrder

# 在本例子中,雖然打亂順序,但是都會執行,所以顯示上無差別torchvision.transforms.RandomOrder(transforms)(image)

網上的講torchvision的變換有很多,但是大多都沒有帶效果,不方便理解。本文參考網上博客加上自己實踐附上效果圖,當做是字典來查,建議大家收藏

參考:

https://blog.csdn.net/qq_38410428/article/details/94719553?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param


相關焦點

  • 視覺工具包torchvision重大更新:支持分割模型、檢測模型,還有許多數據集
    終於來到torchvision 0.3了。torchvision算子就像開頭提到的那樣,torchvision這次有了定製的C++/CUDA算子,計算機視覺專用。_fpn(pretrained=True) 4 5 6model.eval() 7 8image = PIL.Image.open('/path/to/an/image.jpg') 9image_tensor = torchvision.transforms.functional.to_tensor(image)101112
  • PyTorch & 分布式框架 Ray :保姆級入門教程
    RaySGD是一個為數據並行訓練提供分布式訓練包裝的庫。例如,RaySGD TorchTrainer(https://docs.ray.io/en/master/raysgd/raysgd_pytorch.html) 是一個圍繞 torch.distributed.launch 的包裝器。
  • 一個使用pytorch的圖片分類教程——以明信片分類為例
    從分好類別的文件夾中讀取首先我們寫以下內容from torch.utils.data import DataLoaderfrom torchvision import transformsfrom torchvision.datasets import ImageFoldertransform = transforms.Compose(
  • Tensorflow還是PyTorch?哪一個才更適合編程實現深度神經網絡?
    import torchvisionb)導入並預處理數據使用TensorFlow加載和準備數據可以使用以下兩行代碼:(x_trainTF_, y_trainTF_), _ = tf.keras.datasets.mnist.load_data()
  • TensorRT 加速 PyTorch 模型基本方法
    我們以ResNet50為例,代碼如下:import torchvisionimport torchfrom torch.autograd import Variableimport onnxprint(torch.
  • 在PyTorch中使用DeepLabv3進行語義分割的遷移學習
    並且torchvision不僅沒有提供分割數據集,而且也沒有關於DeepLabv3類內部結構的詳細解釋。然而,我是通過自己的研究進行了現有模型的遷移學習,我想分享這個過程,這樣可能會對你們有幫助。在本文中,我將介紹如何使用預先訓練的語義分割DeepLabv3模型,通過使用遷移學習在PyTorch中進行道路裂縫檢測。
  • PyTorch 1.6、TensorFlow 2.3、Pandas 1.1 同日發布!都有哪些新...
    TensorPipe是PyTorch分布式訓練的通信工具,詳情可參閱GitHub:pytorch/tensorpipe。還有其他分布式並行訓練(Distributed Data Parallel,DDP)和(Remote Procedural Call,RPC)包的改進。
  • PyTorch1.5更新發布,與Python配合使用的C ++前端API奇偶校驗
    你可以在下面的連結中找到詳細的發行說明:https://github.com/pytorch/pytorch/releasesC ++前端API(穩定)現在,C ++前端API與Python相當,並且總體功能已移至「穩定」狀態(以前標記為實驗性)。
  • 談談我在PyTorch踩過的12坑
    https://blog.csdn.net/hyk_1996/article/details/84307108使用多GPU時,應該記住pytorch的處理邏輯是:2)前向傳播時,把batch分配到各個GPU上進行計算。3)得到的輸出在主GPU上進行匯總,計算loss並反向傳播,更新主GPU上的權值。
  • 高性能PyTorch是如何煉成的?整理的10條脫坑指南
    數據預處理幾乎每個訓練管道都以 Dataset 類開始。它負責提供數據樣本。任何必要的數據轉換和擴充都可能在此進行。簡而言之,Dataset 能報告其規模大小以及在給定索引時,給出數據樣本。如果你要處理類圖像的數據(2D、3D 掃描),那麼磁碟 I/O 可能會成為瓶頸。為了獲取原始像素數據,你的代碼需要從磁碟中讀取數據並解碼圖像到內存。
  • 高性能PyTorch是如何煉成的?過來人吐血整理的10條避坑指南
    (image).permute(2,0,1).contiguous(), torch.from_numpy(target).permute(2,0,1).contiguous()class Normalize(nn.Module): # https://github.com/BloodAxe/pytorch-toolbelt/blob/develop/pytorch_toolbelt
  • 用NVIDIA DALI 加速PyTorch:訓練速度提升 4 倍
    這使得在 ImageNet 數據集上的單一 GPU 訓練時間減少到幾個小時。而在 202 年,在 ImageNet 上訓練 AlexNet 模型花了 5 天時間!              如此強大的 gpu 使數據預處理管道變得緊張。為了解決這個問題,Tensorflow 發布了一個新的數據加載器:tf.data.Dataset。
  • 【深度學習環境配置】GTX3060 Win10+cuda+cudnn+pytorch+pycharm配置過程
    這也是pytorch目前支持最高版本的一個cuda。那我們下載cuda吧。我知道cuda伺服器在國外,所以可能需要科學上網的方式進行下載,如果和我一樣是3060顯卡,後文有下載方式獲取我的安裝包。常用的鏡像有很多,經過我測試,清華大學的鏡像在pytorch會出現卡頓的情況,不過不知道是不是個例。但是我切換到中國科學技術大學鏡像之後,一切安裝就變好了,所以本文只配置中科大鏡像。
  • TensorFlow vs PyTorch:哪個是深度學習網絡編程的最佳框架呢?
    import torchvisionb)加載和預處理數據使用TensorFlow加載和準備數據可以通過以下兩行代碼完成:在PyTorch中是這樣的:我們可以使用matplotlib.pyplot庫驗證這兩段代碼是否已經正確加載了相同數據:c)定義神經網絡模型在兩種框架都使用相當相似的語法來完成。
  • 如何用pyTorch改造基於Keras的MIT情感理解模型
    /t/self-attention-on-words-and-masking/5671/5        max_len = unnorm_ai.size(1)        idxes = torch.arange(0, max_len, out=torch.LongTensor(max_len)).unsqueeze(0)        if torch.cuda.is_available
  • 9個讓PyTorch模型訓練提速的技巧
    from pytorch_lightning import Trainermodel = LightningModule(…)trainer = Trainer()trainer.fit(model)1. DataLoaders這可能是最容易獲得速度增益的地方。