【YOLOv3 dataset】YOLOv3數據集準備

1 為什么要整這一出

神經網絡需要數據傳入才能進行訓練等操作,那怎樣才能把圖片以及標注信息整合成神經網絡正規輸入的格式呢?

回答:pytorch 的數據加載到模型的操作順序是這樣的:
① 創建一個 Dataset 對象
② 創建一個 DataLoader 對象
③ 循環這個 DataLoader 對象,將img, label加載到模型中進行訓練

整之前,先了解一些基礎知識。

2 基礎知識

代碼中經常看到這兩行,那Dataset和DataLoader是什么玩意?

from torch.utils.data.dataset import Dataset
from torch.utils.data import DataLoader

2.1 Dataset

Dataset是一個包裝類,用來將數據包裝為Dataset類,然后傳入DataLoader中。

當用戶想要加載自定義的數據時,只需要繼承這個類,并且覆寫其中的兩個方法即可:

  1. __len__:實現len(dataset),返回整個數據集的大小。
  2. __getitem__:用來獲取一些索引的數據,使dataset[i]返回數據集中第i個樣本。
  3. 不覆寫這兩個方法會直接返回錯誤。

簡單看一眼,有點感覺就行,繼續往下。

class YoloDataset(Dataset):
    def __init__(self, annotation_lines, input_shape, num_classes, train):
        super(YoloDataset, self).__init__()
        ...

    def __len__(self):
        ...

    def __getitem__(self, index):
        ...

2.2 DataLoader

DataLoader將自定義的Dataset根據batch size大小、是否shuffle等封裝成一個Batch Size大小的Tensor,用于后面的訓練。

  • dataloader本質上是一個可迭代對象,使用iter()訪問,不能使用next()訪問;
  • 使用iter(dataloader)返回的是一個迭代器,然后可以使用next訪問;
  • 一般使用for inputs, labels in dataloaders進行可迭代對象的訪問;

DataLoader參數介紹:

class torch.utils.data.DataLoader(
 dataset,
 batch_size=1,
 shuffle=False,
 sampler=None,
 batch_sampler=None,
 num_workers=0,
 collate_fn=None,    # <function default_collate>
 pin_memory=False,
 drop_last=False,
 timeout=0,
 worker_init_fn=None)

部分關鍵參數含義:

  • batch_size:每個batch的大小
  • shuffle:在每個epoch開始的時候,是否對數據進行重新排序
  • num_workers:加載數據的時候使用幾個子進程,0意味著所有的數據都會被load進主進程。(默認為0)
  • collate_fn:如何取樣本,可以自己定義函數來準確地實現想要的功能
  • drop_last:告訴如何處理數據集長度除以batch_size 余下的數據。True就拋棄,否則保留

3 Dataset與DataLoader綜合使用

最樸實的情況:

dataset = MyDataset()
dataloader = DataLoader(dataset)
num_epoches = 100
for epoch in range(num_epoches):
    for img, label in dataloader:
        ....

在YOLOv3中的操作示例:

        train_dataset  = YoloDataset(train_lines, input_shape, num_classes, train=True)
        val_dataset    = YoloDataset(val_lines, input_shape, num_classes, train=False)
        # gen常寫為train_loader
        gen            = DataLoader(train_dataset, shuffle=True, batch_size=batch_size, num_workers=num_workers, pin_memory=True,
                                    drop_last=True, collate_fn=yolo_dataset_collate)
        # gen_val常寫為val_loader
        gen_val        = DataLoader(val_dataset  , shuffle=True, batch_size=batch_size, num_workers=num_workers, pin_memory=True, 
                                    drop_last=True, collate_fn=yolo_dataset_collate)

        for iteration, batch in enumerate(gen):
            images, targets = batch[0], batch[1]
            ...

那重寫的Dataset內部是怎么操作的呢?它的輸入又是什么意思呢?

4 YoloDataset的實際使用

訓練時會使用一些數據增強手段,包括:

1. 裁剪(需改變bbox)
2. 平移(需改變bbox)
3. 改變亮度
4. 加噪聲
5. 旋轉角度(需要改變bbox)
6. 鏡像(需要改變bbox)
7. cutout

整個學習過程中,存在兩個問題

  • 輸出GT box的[中心點x,中心點y,寬w,高h,cls_num],其中坐標點位置以及box寬和高是歸一化的嗎?(0~1)
    回答:看網絡,YOLO需要歸一化,SSD不需要歸一化,原因是:網絡中使用的定位損失函數有區別。

  • 在網絡訓練過程中,所謂的圖像縮放、扭曲、翻轉,色域變換等數據增強技術,都是在輸入圖像上變換嗎?有沒有增加訓練數據量?
    回答:數據增強不是數據擴充。每一個epoch取出原數據后,樣本有一定概率使用數據增強技術,這樣導致每一次訓練的圖片其實有一些區別,并不完全相同。總結,確實是在輸入圖像上變換的,沒有增加訓練數據量。

直接看代碼:

import cv2
import numpy as np
from PIL import Image
from torch.utils.data.dataset import Dataset
from torch.utils.data import DataLoader

#---------------------------------------------------------#
#   將圖像轉換成RGB圖像,防止灰度圖在預測時報錯。
#   代碼僅僅支持RGB圖像的預測,所有其它類型的圖像都會轉化成RGB
#   .convert('RGB')的使用與理解,可見http://www.lxweimin.com/p/5b53af742ad5
#---------------------------------------------------------#
def cvtColor(image):
    if len(np.shape(image)) == 3 and np.shape(image)[2] == 3:
        return image
    else:
        image = image.convert('RGB')
        return image

def preprocess_input(image):
    image /= 255.0
    return image


class YoloDataset(Dataset):
    def __init__(self, annotation_lines, input_shape, num_classes, train):
        super(YoloDataset, self).__init__()
        # annotation_lines[index]:圖片路徑 目標1的xmin,ymin,xmax,ymax,class_num 目標2的xmin,ymin,xmax,ymax,class_num ...
        self.annotation_lines = annotation_lines
        self.input_shape = input_shape      # [416, 416]    【高,寬】
        self.num_classes = num_classes      # 20
        self.length = len(self.annotation_lines)        # self.annotation_lines是個list
        self.train = train      # self.train是bool型,用來確定是否進行數據增強,train時增強,val時不增強

    def __len__(self):
        return self.length

    def __getitem__(self, index):
        index = index % self.length     # 這一步保證index不超過length,不然self.annotation_lines[index]取不到值
        # ---------------------------------------------------#
        #   訓練時進行數據的隨機增強
        #   驗證時不進行數據的隨機增強
        # ---------------------------------------------------#
        image, box = self.get_random_data(self.annotation_lines[index], self.input_shape[0:2], random=self.train)
        # ---------------------------------------------#
        #   把圖片數據image轉成CHW格式,float32類型數據,并歸一化
        # ---------------------------------------------#
        image = np.transpose(preprocess_input(np.array(image, dtype=np.float32)), (2, 0, 1))
        box = np.array(box, dtype=np.float32)
        if len(box) != 0:
            # 左上點和右下點坐標x   歸一化?
            box[:, [0, 2]] = box[:, [0, 2]] / self.input_shape[1]
            # 左上點和右下點坐標y   歸一化?
            box[:, [1, 3]] = box[:, [1, 3]] / self.input_shape[0]

            # box位置信息從[xmin,ymin,xmax,ymax,cls_num]到[xmin,ymin,寬w,高h,cls_num]
            box[:, 2:4] = box[:, 2:4] - box[:, 0:2]
            # box位置信息從[xmin,ymin,寬w,高h,cls_num]到[中心點x,中心點y,寬w,高h,cls_num]
            box[:, 0:2] = box[:, 0:2] + box[:, 2:4] / 2
        return image, box

    # 下面get_random_data函數中要用到這個函數
    def rand(self, a=0, b=1):
        # np.random.rand()返回一個或一組服從“0~1”均勻分布的隨機樣本值。
        # 隨機樣本取值范圍是[0,1),不包括1
        return np.random.rand() * (b - a) + a

    def get_random_data(self, annotation_line, input_shape, jitter=.3, hue=.1, sat=1.5, val=1.5, random=True):
        # ------------------------------#
        #   annotation_line是字符串,路徑、各標簽信息之間 空格 隔開
        #   進過split(),line是list,每個元素是str
        # ------------------------------#
        line = annotation_line.split()
        # ------------------------------#
        #   讀取圖像并轉換成RGB圖像
        #   line[0]是路徑
        # ------------------------------#
        image = Image.open(line[0])
        image = cvtColor(image)
        # ------------------------------#
        #   獲得圖像的高寬與目標高寬
        # ------------------------------#
        iw, ih = image.size     # 原圖的寬和高,Image讀取圖片,img.size返回圖片寬和高,詳見http://www.lxweimin.com/p/5b53af742ad5
        h, w = input_shape      # input_shape:[416, 416]
        # ------------------------------#
        #   獲得預測框
        #   二維數組,里面每一維,一個bbox的標簽
        #   內部操作:str->int  一個bbox的標簽成list,再np轉,再套個列表,再轉
        # ------------------------------#
        box = np.array([np.array(list(map(int, box.split(',')))) for box in line[1:]])

        # ----------------------------------#
        #   不進行數據增強,也就是測試的時候
        #   random為False
        # ----------------------------------#
        if not random:
            # -------------------------------------------#
            #   獲取縮放參數
            #   可參考http://www.lxweimin.com/p/2ae3a497f5f4
            # -------------------------------------------#
            scale = min(w / iw, h / ih)
            nw = int(iw * scale)
            nh = int(ih * scale)
            dx = (w - nw) // 2
            dy = (h - nh) // 2

            # ---------------------------------#
            #   原image等比例縮放后,新建一個期待大小的灰度圖,如416x416,
            #   把縮放后的image,貼在灰圖上,從(dx,dy)那兒貼,也就是左上頂點對齊(dx,dy)
            #   就像給圖像加灰條的感覺
            # ---------------------------------#
            image = image.resize((nw, nh), Image.BICUBIC)
            new_image = Image.new('RGB', (w, h), (128, 128, 128))
            new_image.paste(image, (dx, dy))
            image_data = np.array(new_image, np.float32)

            # ---------------------------------#
            #   對真實框進行調整
            # ---------------------------------#
            if len(box) > 0:
                np.random.shuffle(box)      # 用來打亂真實框的順序
                # -----------------------------------------------#
                #   box是二維數組,里面一個元素:[xmin,ymin,xmax,ymax,class_num]
                #   若 b = array([[1, 2, 3], [4, 5, 6]])
                #   則 b[:,[0,2]]: array([[1, 3], [4, 6]])
                #      b[:,0:2]: array([[1, 2], [4, 5]])
                #      b[:,0:2]<0: array([[False, False], [False, False]])
                #      b[:,0:2][b[:,0:2]<2]=0,則b=array([[0, 2, 3], [4, 5, 6]])
                #      b[:,1]-b[:,0]:array([2, 1]),array對應位置相減,得到一個array
                #      b[np.array([True, False])]:array([[0, 2, 3]])
                # -----------------------------------------------#
                # 對標簽的xmin和xmax進行變換,到resize后圖片里的位置
                box[:, [0, 2]] = box[:, [0, 2]] * nw / iw + dx
                # 對標簽的ymin和ymax進行變換,到resize后圖片里的位置
                box[:, [1, 3]] = box[:, [1, 3]] * nh / ih + dy
                # 出界了就整到邊界上去
                #   xmin和ymin小于0,就置為0
                box[:, 0:2][box[:, 0:2] < 0] = 0
                #   xmax和ymax大于w和h,就置為w和h
                box[:, 2][box[:, 2] > w] = w
                box[:, 3][box[:, 3] > h] = h
                box_w = box[:, 2] - box[:, 0]       # 得到框的寬
                box_h = box[:, 3] - box[:, 1]       # 得到框的高
                # -------------------------------------------------#
                #   np.logical_and邏輯與,都是True,才為True。寬個高不大于1像素,就舍棄
                #   np.logical_and(box_w > 1, box_h > 1)得到一個array,
                #   類似于array([False, False], dtype=bool)
                #   初始:box[[GT框1信息], [GT框2信息], [GT框3信息]]
                #   經過:box[np.array([True, False, True])]
                #   結果:box[[GT框1信息], [GT框3信息]]
                # -------------------------------------------------#
                box = box[np.logical_and(box_w > 1, box_h > 1)]  # discard invalid box

            return image_data, box  # np.array的圖片數據、有效的np.array的標簽數據

        # ------------------------------------------#
        #   下面都是    數據增強技術
        #   所謂的圖像縮放、扭曲、翻轉,色域變換等,都是在輸入圖像上變換嗎?有沒有增加訓練數據量?
        # ------------------------------------------#
        #   對圖像進行縮放并且進行長和寬的扭曲
        # ------------------------------------------#
        new_ar = w / h * self.rand(1 - jitter, 1 + jitter) / self.rand(1 - jitter, 1 + jitter)
        scale = self.rand(.25, 2)
        if new_ar < 1:
            nh = int(scale * h)
            nw = int(nh * new_ar)
        else:
            nw = int(scale * w)
            nh = int(nw / new_ar)
        image = image.resize((nw, nh), Image.BICUBIC)

        # ------------------------------------------#
        #   將圖像多余的部分加上灰條
        # ------------------------------------------#
        dx = int(self.rand(0, w - nw))
        dy = int(self.rand(0, h - nh))
        new_image = Image.new('RGB', (w, h), (128, 128, 128))
        new_image.paste(image, (dx, dy))
        image = new_image

        # ------------------------------------------#
        #   翻轉圖像
        # ------------------------------------------#
        flip = self.rand() < .5
        if flip: image = image.transpose(Image.FLIP_LEFT_RIGHT)

        image_data      = np.array(image, np.uint8)
        #---------------------------------#
        #   對圖像進行色域變換
        #   計算色域變換的參數
        #---------------------------------#
        r               = np.random.uniform(-1, 1, 3) * [hue, sat, val] + 1
        #---------------------------------#
        #   將圖像轉到HSV上
        #---------------------------------#
        hue, sat, val   = cv2.split(cv2.cvtColor(image_data, cv2.COLOR_RGB2HSV))
        dtype           = image_data.dtype
        #---------------------------------#
        #   應用變換
        #---------------------------------#
        x       = np.arange(0, 256, dtype=r.dtype)
        lut_hue = ((x * r[0]) % 180).astype(dtype)
        lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)
        lut_val = np.clip(x * r[2], 0, 255).astype(dtype)

        image_data = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val)))
        image_data = cv2.cvtColor(image_data, cv2.COLOR_HSV2RGB)

        #---------------------------------#
        #   對真實框進行調整
        #---------------------------------#
        if len(box)>0:
            np.random.shuffle(box)
            box[:, [0,2]] = box[:, [0,2]]*nw/iw + dx
            box[:, [1,3]] = box[:, [1,3]]*nh/ih + dy
            if flip: box[:, [0,2]] = w - box[:, [2,0]]
            box[:, 0:2][box[:, 0:2]<0] = 0
            box[:, 2][box[:, 2]>w] = w
            box[:, 3][box[:, 3]>h] = h
            box_w = box[:, 2] - box[:, 0]
            box_h = box[:, 3] - box[:, 1]
            box = box[np.logical_and(box_w>1, box_h>1)] 
        
        return image_data, box


# DataLoader中collate_fn使用
def yolo_dataset_collate(batch):
    images = []
    bboxes = []
    for img, box in batch:
        images.append(img)
        bboxes.append(box)
    images = np.array(images)
    return images, bboxes


if __name__ == '__main__':
    # ------------------------------------------------------#
    #   數據集中類別個數,以voc為例,20類
    # ------------------------------------------------------#
    num_classes = 20
    # ------------------------------------------------------#
    #   輸入的shape大小,一定要是32的倍數
    # ------------------------------------------------------#
    input_shape     = [416, 416]

    num_workers = 0
    batch_size = 64
    # ----------------------------------------------------#
    #   獲得圖片路徑和標簽
    #   圖片路徑 目標1的xmin,ymin,xmax,ymax,class_num 目標2的xmin,ymin,xmax,ymax,class_num ...
    #   D:\VOCdevkit/VOC2007/JPEGImages/000005.jpg 263,211,324,339,8 165,264,253,372,8 241,194,295,299,8
    #   D:\VOCdevkit/VOC2007/JPEGImages/000007.jpg 141,50,500,330,6
    #   2007_train.txt和2007_val.txt怎么得到的,之后再聊
    # ----------------------------------------------------#
    train_annotation_path   = '2007_train.txt'
    val_annotation_path     = '2007_val.txt'
    # ------------------------------------------------------------------#
    #   讀取數據集對應的txt
    #   train_lines是一個list,里面每個元素是一個str,每個str內有圖片路徑和標簽信息,以 空格 分開
    #               每個元素的最后是 換行符\n
    # ------------------------------------------------------------------#
    with open(train_annotation_path) as f:
        train_lines = f.readlines()
    with open(val_annotation_path) as f:
        val_lines   = f.readlines()

    train_dataset = YoloDataset(train_lines, input_shape, num_classes, train=True)
    val_dataset = YoloDataset(val_lines, input_shape, num_classes, train=False)

    # gen就是常規的train_loader
    gen = DataLoader(train_dataset, shuffle=True, batch_size=batch_size, num_workers=num_workers, pin_memory=True,
                     drop_last=True, collate_fn=yolo_dataset_collate)
    # gen_val就是常規的val_loader
    gen_val = DataLoader(val_dataset, shuffle=True, batch_size=batch_size, num_workers=num_workers, pin_memory=True,
                         drop_last=True, collate_fn=yolo_dataset_collate)

        for iteration, batch in enumerate(gen):
            images, targets = batch[0], batch[1]

調試時train_dataset和gen的結果:

train_dataset
gen
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容