【從零開始學CenterNet】1. pytorch版CenterNet訓練自己的數據集


CenterNet(Objects as points)已經有一段時間了,之前這篇文章-【目標檢測Anchor-Free】CVPR 2019 Object as Points(CenterNet)中講解了CenterNet的原理,可以回顧一下。

這篇文章是基於非官方的CenterNet實現,https://github.com/zzzxxxttt/pytorch_simple_CenterNet_45,這個版本的實現更加簡單,基於官方版本(https://github.com/xingyizhou/CenterNet)進行修改,要比官方代碼更適合閱讀和理解,dataloader、hourglass、訓練流程等原版中比較復雜的部分都進行了重寫,最終要比官方的速度更快。

這篇博文主要講解如何用這個版本的CenterNet訓練自己的VOC數據集,環境的配置。

1. 環境配置

環境要求:

  • python>=3.5
  • pytorch==0.4.1or 1.1.0 or 1.0.0(筆者用的1.0.0也可以)
  • tensorboardX(可選)

配置:

  1. 將cudnn的batch norm關閉。打開torch/nn/functional.py文件,找到torch.batch_norm這一行,將torch.backends.cudnn.enabled選項更改為False。
  2. 克隆項目
CenterNet_ROOT=/path/to/clone/CenterNet
git clone https://github.com/zzzxxxttt/pytorch_simple_CenterNet_45 $CenterNet_ROOT
  1. 安裝cocoAPI
cd $CenterNet_ROOT/lib/cocoapi/PythonAPI
make
python setup.py install --user
  1. 編譯可變形卷積DCN
  • 如果使用的是pytorch0.4.1, 將$CenterNet_ROOT/lib/DCNv2_old 復制為 $CenterNet_ROOT/lib/DCNv2
  • 如果使用的是pytorch1.1.0 or 1.0.0, 將$CenterNet_ROOT/lib/DCNv2_new 復制為 $CenterNet_ROOT/lib/DCNv2.
  • 然后開始編譯
cd $CenterNet_ROOT/lib/DCNv2
./make.sh
  1. 編譯NMS
cd $CenterNet_ROOT/lib/nms
make
  1. 對於COCO格式的數據集,下載鏈接在:http://cocodataset.org/#download。將annotations, train2017, val2017, test2017放在$CenterNet_ROOT/data/coco

  2. 對於Pascal VOC格式的數據集,下載VOC轉為COCO以后的數據集:

百度網盤鏈接:https://pan.baidu.com/share/init?surl=z6BtsKPHh2MnbfT25Y4wYw 密碼:4iu2

下載以后將annotations, images, VOCdevkit放在$CenterNet_ROOT/data/voc

PS:以上兩者是官方數據集,如果制作自己的數據集的話可以往下看。

  1. 如果選擇Hourglass-104作為骨干網絡,下載CornerNet預訓練模型:

百度網盤鏈接:https://pan.baidu.com/s/1tp9-5CAGwsX3VUSdV276Fg 密碼: y1z4

將下載的權重checkpoint.t7放到$CenterNet_ROOT/ckpt/pretrain中。

2. 配置自己的數據集

這個版本提供的代碼是針對官方COCO或者官方VOC數據集進行配置的,所以有一些細節需要修改。

由於筆者習慣VOC格式數據集,所以以Pascal VOC格式為例,修改自己的數據集。

筆者只有一個類,‘dim target’,所以按照一個類來修改,其他的類別也很容易修改。

2.1 VOC類別修改

  • 將datasets/pascal.py中16行內容:
VOC_NAMES = ['__background__', "aeroplane", "bicycle", "bird", "boat",
             "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog",
             "horse", "motorbike", "person", "pottedplant", "sheep", "sofa",
             "train", "tvmonitor"]

修改為自己類別的名稱:

VOC_NAMES = ['__background__', 'dim target']
  • 將datasets/pascal.py中第33行內容:

num_classes=20修改為自己對應的類別個數num_classes=1

  • 將datasets/pascal.py中的第35行內容:

self.valid_ids = np.arange(1, 21, dtype=np.int32)中的21修改為類別數目+1

2.2 annotations

VOC格式數據集中沒有annotations中所需要的json文件,這部分需要重新構建。

下面是一個VOC轉COCO格式的腳本,需要改xml path和json file的名稱。

import xml.etree.ElementTree as ET
import os
import json

coco = dict()
coco['images'] = []
coco['type'] = 'instances'
coco['annotations'] = []
coco['categories'] = []

category_set = dict()
image_set = set()

category_item_id = 0
image_id = 20200000000
annotation_id = 0

def addCatItem(name):
    global category_item_id
    category_item = dict()
    category_item['supercategory'] = 'none'
    category_item_id += 1
    category_item['id'] = category_item_id
    category_item['name'] = name
    coco['categories'].append(category_item)
    category_set[name] = category_item_id
    return category_item_id

def addImgItem(file_name, size):
    global image_id
    if file_name is None:
        raise Exception('Could not find filename tag in xml file.')
    if size['width'] is None:
        raise Exception('Could not find width tag in xml file.')
    if size['height'] is None:
        raise Exception('Could not find height tag in xml file.')
    image_id += 1
    image_item = dict()
    image_item['id'] = image_id
    image_item['file_name'] = file_name
    image_item['width'] = size['width']
    image_item['height'] = size['height']
    coco['images'].append(image_item)
    image_set.add(file_name)
    return image_id


def addAnnoItem(object_name, image_id, category_id, bbox):
    global annotation_id
    annotation_item = dict()
    annotation_item['segmentation'] = []
    seg = []
    #bbox[] is x,y,w,h
    #left_top
    seg.append(bbox[0])
    seg.append(bbox[1])
    #left_bottom
    seg.append(bbox[0])
    seg.append(bbox[1] + bbox[3])
    #right_bottom
    seg.append(bbox[0] + bbox[2])
    seg.append(bbox[1] + bbox[3])
    #right_top
    seg.append(bbox[0] + bbox[2])
    seg.append(bbox[1])

    annotation_item['segmentation'].append(seg)

    annotation_item['area'] = bbox[2] * bbox[3]
    annotation_item['iscrowd'] = 0
    annotation_item['ignore'] = 0
    annotation_item['image_id'] = image_id
    annotation_item['bbox'] = bbox
    annotation_item['category_id'] = category_id
    annotation_id += 1
    annotation_item['id'] = annotation_id
    coco['annotations'].append(annotation_item)

def parseXmlFiles(xml_path):
    for f in os.listdir(xml_path):
        if not f.endswith('.xml'):
            continue

        real_file_name = f.split(".")[0] + ".jpg"

        bndbox = dict()
        size = dict()
        current_image_id = None
        current_category_id = None
        file_name = None
        size['width'] = None
        size['height'] = None
        size['depth'] = None

        xml_file = os.path.join(xml_path, f)
        print(xml_file)

        tree = ET.parse(xml_file)
        root = tree.getroot()
        if root.tag != 'annotation':
            raise Exception(
                'pascal voc xml root element should be annotation, rather than {}'
                .format(root.tag))

        #elem is <folder>, <filename>, <size>, <object>
        for elem in root:
            current_parent = elem.tag
            current_sub = None
            object_name = None

            if elem.tag == 'folder':
                continue

            if elem.tag == 'filename':
                file_name = real_file_name  #elem.text
                if file_name in category_set:
                    raise Exception('file_name duplicated')

            #add img item only after parse <size> tag
            elif current_image_id is None and file_name is not None and size[
                    'width'] is not None:
                # print(file_name, "===", image_set)
                if file_name not in image_set:
                    current_image_id = addImgItem(file_name, size)
                    print('add image with {} and {}'.format(file_name, size))
                else:
                    pass
                    # raise Exception('duplicated image: {}'.format(file_name))
            #subelem is <width>, <height>, <depth>, <name>, <bndbox>
            for subelem in elem:
                bndbox['xmin'] = None
                bndbox['xmax'] = None
                bndbox['ymin'] = None
                bndbox['ymax'] = None

                current_sub = subelem.tag
                if current_parent == 'object' and subelem.tag == 'name':
                    object_name = subelem.text
                    if object_name not in category_set:
                        current_category_id = addCatItem(object_name)
                    else:
                        current_category_id = category_set[object_name]

                elif current_parent == 'size':
                    if size[subelem.tag] is not None:
                        raise Exception('xml structure broken at size tag.')
                    size[subelem.tag] = int(subelem.text)

                #option is <xmin>, <ymin>, <xmax>, <ymax>, when subelem is <bndbox>
                for option in subelem:
                    if current_sub == 'bndbox':
                        if bndbox[option.tag] is not None:
                            raise Exception(
                                'xml structure corrupted at bndbox tag.')
                        bndbox[option.tag] = int(option.text)

                #only after parse the <object> tag
                if bndbox['xmin'] is not None:
                    if object_name is None:
                        raise Exception('xml structure broken at bndbox tag')
                    if current_image_id is None:
                        raise Exception('xml structure broken at bndbox tag')
                    if current_category_id is None:
                        raise Exception('xml structure broken at bndbox tag')
                    bbox = []
                    #x
                    bbox.append(bndbox['xmin'])
                    #y
                    bbox.append(bndbox['ymin'])
                    #w
                    bbox.append(bndbox['xmax'] - bndbox['xmin'])
                    #h
                    bbox.append(bndbox['ymax'] - bndbox['ymin'])
                    print('add annotation with {},{},{},{}'.format(
                        object_name, current_image_id, current_category_id,
                        bbox))
                    addAnnoItem(object_name, current_image_id,
                                current_category_id, bbox)

if __name__ == '__main__':
    xml_path = './annotations/test'
    json_file = './pascal_test2020.json'
    #'./pascal_trainval0712.json'
    parseXmlFiles(xml_path)
    json.dump(coco, open(json_file, 'w'))

注意這里json文件的命名要通過datasets/pascal.py中第44到48行的內容確定的。

self.data_dir = os.path.join(data_dir, 'voc')
self.img_dir = os.path.join(self.data_dir, 'images')
_ann_name = {'train': 'trainval0712', 'val': 'test2007'}
self.annot_path = os.path.join(self.data_dir, 'annotations', 'pascal_%s.json' % _ann_name[split])

這里筆者為了方便命名對這些字段進行了修改:

self.data_dir = os.path.join(data_dir, 'voc') # ./data/voc
self.img_dir = os.path.join(self.data_dir, 'images') # ./data/voc/images
_ann_name = {'train': 'train2020', 'val': 'test2020'}
# 意思是需要json格式數據集
self.annot_path = os.path.join(
self.data_dir, 'annotations', 'pascal_%s.json' % _ann_name[split])

所以要求json的命名可以按照以下格式准備:

# ./data/voc/annotations
#   - pascal_train2020
#   - pascal_test2020

數據集總體格式為:

- data
  - voc
  	- annotations
  		- pascal_train2020.json
  		- pascal_test2020.json
  	- images
  		- *.jpg
  	- VOCdevkit(這個文件夾主要是用於測評)
  		- VOC2007
            - Annotations
                - *.xml
            - JPEGImages
                - *.jpg
            - ImageSets
            	- Main
            		- train.txt
            		- val.txt
            		- trainval.txt
            		- test.txt  		

2.3 其他

在datasets/pascal.py中21-22行,標准差和方差最好替換為自己的數據集的標准差和方差。

VOC_MEAN = [0.485, 0.456, 0.406]
VOC_STD = [0.229, 0.224, 0.225]

3. 訓練和測試

3.1 訓練命令

訓練命令比較多,可以寫一個shell腳本來完成。

python train.py --log_name pascal_resdcn18_384_dp \
                --dataset pascal \
                --arch resdcn_18 \
                --img_size 384 \
                --lr 1.25e-4 \
                --lr_step 45,60 \
                --batch_size 32 \
                --num_epochs 70 \
                --num_workers 10

log name代表記錄的日志的名稱。

dataset設置pascal代表使用的是pascal voc格式。

arch代表選擇的backbone的類型,有以下幾種:

  • large_hourglass
  • small_hourglass
  • resdcn_18
  • resdcn_34
  • resdcn_50
  • resdcn_101
  • resdcn_152

img size控制圖片長和寬。

lr和lr_step控制學習率大小及變化。

batch size是一個批次處理的圖片個數。

num epochs代表學習數據集的總次數。

num workers代表開啟多少個線程加載數據集。

3.2 測試命令

測試命令很簡單,需要注意的是img size要和訓練的時候設置的一致。

python test.py --log_name pascal_resdcn18_384_dp \
               --dataset pascal \
               --arch resdcn_18 \
               --img_size 384

flip test屬於TTA(Test Time Augmentation),可以一定程度上提高mAP。

# flip test
python test.py --log_name pascal_resdcn18_384_dp \
               --dataset pascal \
               --arch resdcn_18 \
               --img_size 384 \
               --test_flip

4. 結果

以下是作者在COCO和VOC數據集上以不同的圖片分辨率和TTA方法得到的結果。

COCO:

Model Training image size mAP
Hourglass-104 (DP) 512 39.9/42.3/45.0
Hourglass-104 (DDP) 512 40.5/42.6/45.3

PascalVOC:

Model Training image size mAP
ResDCN-18 (DDP) 384 71.19/72.99
ResDCN-18 (DDP) 512 72.76/75.69

筆者在自己的數據集上進行了訓練,訓練log如下:

每隔5個epoch將進行一次eval,在自己的數據集上最終可以得到90%左右的mAP。

筆者將已經改好的單類的CenterNet放在Github上:https://github.com/pprp/SimpleCVReproduction/tree/master/Simple_CenterNet

5. 參考

https://github.com/pprp/SimpleCVReproduction/tree/master/Simple_CenterNet

https://github.com/zzzxxxttt/pytorch_simple_CenterNet_45


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM