centerNet训练自己的数据python3.6 pytorch 1.*

获得源码

git clone https://github.com/xingyizhou/CenterNet.git
依据readme进行操作

跑通原工程

  1.google云获得权重文件
  2.下载源码DCNv2 https://github.com/CharlesShang/DCNv2.git
       依据readme编译
  3. 需要把 ./torch/nn/functional.py bn=False (具体哪个不太清楚,但有)

制作自己数据

目录
centerNet训练自己的数据python3.6 pytorch 1.*_第1张图片

我训练的是车尾/喷漆车牌/正常车牌检测
在data下建立文件夹路径如图
carHail/image_and_xml:保存所有图片的xml文件;
carHail/annotations:保存有文件xml_json.py生成的json文件;
carHail/images:保存所有图片的原图;

xml_json.py 文件为:

# -*- coding: utf-8 -*-
# @Time    : 2020/1/19 下午1:59
# @Author  : shenyingying
# @Email   : [email protected]
# @File    : xml_json.py
# @Software: PyCharm

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 = -1
image_id = 20180000000
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

        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 , , , 
        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 = elem.text
                if file_name in category_set:
                    raise Exception('file_name duplicated')

            # add img item only after parse  tag
            elif current_image_id is None and file_name is not None and size['width'] is not None:
                if file_name not in image_set:
                    current_image_id = addImgItem(file_name, size)
                    print('add image with {} and {}'.format(file_name, size))
                else:
                    raise Exception('duplicated image: {}'.format(file_name))
                    # subelem is , , , , 
            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 , , , , when subelem is 
                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  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 = '/data_1/project/Detection/CenterNet/data/carHail/val/Annotations'  # 这是xml文件所在的地址
    json_file = '/data_1/project/Detection/CenterNet/data/carHail/val.json'  # 这是你要生成的json文件
    parseXmlFiles(xml_path)  # 只需要改动这两个参数就行了
    json.dump(coco, open(json_file, 'w'))

代码中需要的修改

  1. 在src/lib/datasets/dataset/下copy coco.py 新建一个carHail.py 文件,其具体修改如下图10个地方:
    centerNet训练自己的数据python3.6 pytorch 1.*_第2张图片
  2. 其中生成均值和方差 代码为:
# -*- coding: utf-8 -*-
# @Time    : 2020/1/19 下午2:38
# @Author  : shenyingying
# @Email   : [email protected]
# @File    : compute_mean_std.py
# @Software: PyCharm

import cv2, os, argparse
import numpy as np
from tqdm import tqdm


def main():
    dirs = r'/data_1/project/Detection/CenterNet/data/carHail/images'  # 修改你自己的图片路径
    img_file_names = os.listdir(dirs)
    m_list, s_list = [], []
    for img_filename in tqdm(img_file_names):
        img = cv2.imread(dirs + '/' + img_filename)
        img = img / 255.0
        m, s = cv2.meanStdDev(img)
        m_list.append(m.reshape((3,)))
        s_list.append(s.reshape((3,)))
    m_array = np.array(m_list)
    s_array = np.array(s_list)
    m = m_array.mean(axis=0, keepdims=True)
    s = s_array.mean(axis=0, keepdims=True)
    print("mean = ", m[0][::-1])
    print("std = ", s[0][::-1])


if __name__ == '__main__':
    main()


  1. 在src/lib/datasets/dataset_factory.py 加入
    centerNet训练自己的数据python3.6 pytorch 1.*_第3张图片
  2. 修改 src/lib/opts.py 中默认 参数
    centerNet训练自己的数据python3.6 pytorch 1.*_第4张图片
    centerNet训练自己的数据python3.6 pytorch 1.*_第5张图片
    5. 修改src/lib/utils/debugger.py 文件为:
    centerNet训练自己的数据python3.6 pytorch 1.*_第6张图片
    centerNet训练自己的数据python3.6 pytorch 1.*_第7张图片

进行训练

  1. 不加载权重的训练

    python main.py ctdet --exp_id carHail --batch_size 4 --lr 1.25e-4
    
  2. 加载权重的训练

     python main.py ctdet --exp_id carHail --batch_size 4 --lr 1.25e-4 --load_model ../models/ctdet_dla_2x.pth
    
  3. 多卡训练

    python main.py ctdet --exp_id carHail --batch_size 4 --lr 1.25e-4 --gpus 0,1,2 --load_model ../models/ctdet_dla_2x.pth
    
  4. 断点恢复

     python main.py ctdet --exp_id carHail --batch_size 4 --lr 1.25e-4 --gpus 0,1,2 --load_model ../models/ctdet_dla_2x.pth --resume
    

    训练完成后,在./exp/ctdet/food/文件夹下会出现一堆文件;
    其中,model_last是最后一次epoch的模型;model_best是val最好的模型

验证模型

运行demo文件检查下训练的模型,–demo设置你要预测的图片/图片文件夹/视频所在的路径;

原始预测:

python demo.py ctdet --demo  ../data/carHail/images   --loda_model exp/ctdet/carHail/model_best.pt

带数据增强的预测:

python demo.py ctdet --demo  ../data/carHail/images   --loda_model exp/ctdet/carHail/model_best.pth --flip_test

多尺度预测

python demo.py ctdet --demo  ../data/carHail/images   --loda_model exp/ctdet/carHail/model_best.pth --test_scales 0.5,0.75,1.0,1.25,1.5

注意,如果多尺度预测报错,一般就是你自己没有编译nms。
编译方法:到 path/to/CenterNet/src/lib/externels 目录下,运行:

 python setup.py build_ext --inplace

测试数据

python test.py ctdet --exp_id carHail   --not_prefetch_test   ctdet  --loda_model exp/ctdet/carHail/model_best.pth 

集群bug

centerNet训练自己的数据python3.6 pytorch 1.*_第8张图片

你可能感兴趣的:(detection)