微網(wǎng)站制作網(wǎng)站開發(fā)怎么制作網(wǎng)站?
mmdetection訓(xùn)練自己的數(shù)據(jù)集
這里寫目錄標(biāo)題
- mmdetection訓(xùn)練自己的數(shù)據(jù)集
- 一: 環(huán)境搭建
- 二:數(shù)據(jù)集格式轉(zhuǎn)換(yolo轉(zhuǎn)coco格式)
- yolo數(shù)據(jù)集格式
- coco數(shù)據(jù)集格式
- yolo轉(zhuǎn)coco數(shù)據(jù)集格式
- yolo轉(zhuǎn)coco數(shù)據(jù)集格式的代碼
- 三: 訓(xùn)練
- dataset數(shù)據(jù)文件配置
- configs
- 1.在configs/faster_rcnn/faster-rcnn_r101_fpn_1x_coco.py我們發(fā)現(xiàn),索引的是'./faster-rcnn_r50_fpn_1x_coco.py'
- 2.找到'./faster-rcnn_r50_fpn_1x_coco.py',發(fā)現(xiàn)索引是下面代碼
- 3.修改
- 4.訓(xùn)練
- 五: 還在繼續(xù)研究的內(nèi)容
一: 環(huán)境搭建
- 有很多的環(huán)境搭建過程,這里就不介紹,我自己也搭建環(huán)境了,一會(huì)就搭建好了。
二:數(shù)據(jù)集格式轉(zhuǎn)換(yolo轉(zhuǎn)coco格式)
yolo數(shù)據(jù)集格式
- 因?yàn)槲移綍r(shí)訓(xùn)練目標(biāo)檢測(cè)數(shù)據(jù)集用的YOLO系列,所以數(shù)據(jù)集格式標(biāo)簽也是txt,在最近接觸的mmdetection訓(xùn)練目標(biāo)檢測(cè)數(shù)據(jù)集是需要用到coco格式,所以在這里需要轉(zhuǎn)換數(shù)據(jù)集的格式。
- 先來看看yolo數(shù)據(jù)集標(biāo)簽的格式,圖片和標(biāo)簽一一對(duì)應(yīng)的。有多少?gòu)垐D片就有多少?gòu)坱xt文件標(biāo)簽。
├── linhuo(這個(gè)是數(shù)據(jù)集名稱)
│ ├── images
│ │ ├── train
│ │ │ ├── 1.jpg
│ │ │ ├── 2.jpg
│ │ │ ├── …
│ │ ├── val
│ │ │ ├── 2000.jpg
│ │ │ ├── 2001.jpg
│ │ │ ├── …
│ │ ├── test
│ │ │ ├── 3000.jpg
│ │ │ ├── 30001.jpg
│ │ │ ├── …
│ ├── labels
│ │ ├── train
│ │ │ ├── 1.xml
│ │ │ ├── 2.xml
│ │ │ ├── …
│ │ ├── val
│ │ │ ├── 2000.xml
│ │ │ ├── 2001.xml
│ │ │ ├── …
│ │ ├── test
│ │ │ ├── 3000.xml
│ │ │ ├── 3001.xml
│ │ │ ├── …
coco數(shù)據(jù)集格式
- coco數(shù)據(jù)集格式如下:
├── data
│ ├── coco
│ │ ├── annotations
│ │ │ ├── instances_train2017.json
│ │ │ ├── instances_val2017.json
│ │ ├── train2017
│ │ ├── val2017
│ │ ├── test2017
yolo轉(zhuǎn)coco數(shù)據(jù)集格式
- 我們需要對(duì)yolo的數(shù)據(jù)集的訓(xùn)練集(train)、驗(yàn)證集(val)、測(cè)試集(test)標(biāo)簽分別進(jìn)行轉(zhuǎn)換生成coco數(shù)據(jù)集的標(biāo)簽格式(圖片相對(duì)是不變的)instances_train2017.json、 instances_val2017.json(這里不需要對(duì)應(yīng)的test的標(biāo)簽)
- 在回顧說明一下需要轉(zhuǎn)換的,和保持相對(duì)不變的
- 保持相對(duì)不變的:
- linhuo/images/train的圖片直接復(fù)制到train2017
- linhuo/images/val的圖片直接復(fù)制到val2017
- linhuo/images/test的圖片直接復(fù)制到test2017
- 需要改變的是:
- linhuo/labels/train的所有標(biāo)簽需要轉(zhuǎn)換成 instances_train2017.json(coco格式)
- linhuo/labels/vla的所有標(biāo)簽需要轉(zhuǎn)換成instances_val2017.json(coco格式)
yolo轉(zhuǎn)coco數(shù)據(jù)集格式的代碼
"""
yolo標(biāo)簽:
yolo數(shù)據(jù)集的標(biāo)注文件是.txt文件,在label文件夾中每一個(gè).txt文件對(duì)應(yīng)數(shù)據(jù)集中的一張圖片
其中每個(gè).txt文件中的每一行代表圖片中的一個(gè)目標(biāo)。
coco標(biāo)簽:
而coco數(shù)據(jù)集的標(biāo)注文件是.json文件,全部的數(shù)據(jù)標(biāo)注文件由三個(gè).json文件組成:train.json val.json test.json,
其中每個(gè).json文件中包含全部的數(shù)據(jù)集圖片中的所有目標(biāo)(注意是所有目標(biāo)不是數(shù)據(jù)集中的所有張圖片)
準(zhǔn)備工作:
1. 在根目錄下創(chuàng)建coco文件格式對(duì)應(yīng)的文件夾
dataset_coco:annotationsimageslabelsclasses.txt(每一行是自定義數(shù)據(jù)集中的一個(gè)類別)YOLO 格式的數(shù)據(jù)集轉(zhuǎn)化為 COCO 格式的數(shù)據(jù)集
--root_dir 輸入根路徑
--save_path 保存文件的名字(沒有random_split時(shí)使用)
--random_split 有則會(huì)隨機(jī)劃分?jǐn)?shù)據(jù)集,然后再分別保存為3個(gè)文件。
--split_by_file 按照 ./train.txt ./val.txt ./test.txt 來對(duì)數(shù)據(jù)集進(jìn)行劃分運(yùn)行方式:python yolo2coco.py --root_dir ./dataset_coco --random_split
datasetcoco/images: 數(shù)據(jù)集所有圖片
datasetcoco/labels: 數(shù)據(jù)集yolo標(biāo)簽的txt文件
classes.txt(每一行是自定義數(shù)據(jù)集中的一個(gè)類別)
"""import os
import cv2
import json
from tqdm import tqdm
from sklearn.model_selection import train_test_split
import argparseparser = argparse.ArgumentParser()
parser.add_argument('--root_dir', default='./data', type=str,help="root path of images and labels, include ./images and ./labels and classes.txt")
parser.add_argument('--save_path', type=str, default='./train.json',help="if not split the dataset, give a path to a json file")
parser.add_argument('--random_split', action='store_true', help="random split the dataset, default ratio is 8:1:1")
parser.add_argument('--split_by_file', action='store_true',help="define how to split the dataset, include ./train.txt ./val.txt ./test.txt ")arg = parser.parse_args()def train_test_val_split_random(img_paths, ratio_train=0.8, ratio_test=0.1, ratio_val=0.1):# 這里可以修改數(shù)據(jù)集劃分的比例。assert int(ratio_train + ratio_test + ratio_val) == 1train_img, middle_img = train_test_split(img_paths, test_size=1 - ratio_train, random_state=233)ratio = ratio_val / (1 - ratio_train)val_img, test_img = train_test_split(middle_img, test_size=ratio, random_state=233)print("NUMS of train:val:test = {}:{}:{}".format(len(train_img), len(val_img), len(test_img)))return train_img, val_img, test_imgdef train_test_val_split_by_files(img_paths, root_dir):# 根據(jù)文件 train.txt, val.txt, test.txt(里面寫的都是對(duì)應(yīng)集合的圖片名字) 來定義訓(xùn)練集、驗(yàn)證集和測(cè)試集phases = ['train', 'val', 'test']img_split = []for p in phases:define_path = os.path.join(root_dir, f'{p}.txt')print(f'Read {p} dataset definition from {define_path}')assert os.path.exists(define_path)with open(define_path, 'r') as f:img_paths = f.readlines()# img_paths = [os.path.split(img_path.strip())[1] for img_path in img_paths] # NOTE 取消這句備注可以讀取絕對(duì)地址。img_split.append(img_paths)return img_split[0], img_split[1], img_split[2]def yolo2coco(arg):root_path = arg.root_dirprint("Loading data from ", root_path)assert os.path.exists(root_path)originLabelsDir = os.path.join(root_path, 'labels')originImagesDir = os.path.join(root_path, 'images')with open(os.path.join(root_path, 'classes.txt')) as f:classes = f.read().strip().split()# images dir nameindexes = os.listdir(originImagesDir)if arg.random_split or arg.split_by_file:# 用于保存所有數(shù)據(jù)的圖片信息和標(biāo)注信息train_dataset = {'categories': [], 'annotations': [], 'images': []}val_dataset = {'categories': [], 'annotations': [], 'images': []}test_dataset = {'categories': [], 'annotations': [], 'images': []}# 建立類別標(biāo)簽和數(shù)字id的對(duì)應(yīng)關(guān)系, 類別id從0開始。for i, cls in enumerate(classes, 0):train_dataset['categories'].append({'id': i, 'name': cls, 'supercategory': 'mark'})val_dataset['categories'].append({'id': i, 'name': cls, 'supercategory': 'mark'})test_dataset['categories'].append({'id': i, 'name': cls, 'supercategory': 'mark'})if arg.random_split:print("spliting mode: random split")train_img, val_img, test_img = train_test_val_split_random(indexes, 0.8, 0.1, 0.1)elif arg.split_by_file:print("spliting mode: split by files")train_img, val_img, test_img = train_test_val_split_by_files(indexes, root_path)else:dataset = {'categories': [], 'annotations': [], 'images': []}for i, cls in enumerate(classes, 0):dataset['categories'].append({'id': i, 'name': cls, 'supercategory': 'mark'})# 標(biāo)注的idann_id_cnt = 0for k, index in enumerate(tqdm(indexes)):# 支持 png jpg 格式的圖片。txtFile = index.replace('images', 'txt').replace('.jpg', '.txt').replace('.png', '.txt')# 讀取圖像的寬和高im = cv2.imread(os.path.join(root_path, 'images/') + index)height, width, _ = im.shapeif arg.random_split or arg.split_by_file:# 切換dataset的引用對(duì)象,從而劃分?jǐn)?shù)據(jù)集if index in train_img:dataset = train_datasetelif index in val_img:dataset = val_datasetelif index in test_img:dataset = test_dataset# 添加圖像的信息dataset['images'].append({'file_name': index,'id': k,'width': width,'height': height})if not os.path.exists(os.path.join(originLabelsDir, txtFile)):# 如沒標(biāo)簽,跳過,只保留圖片信息。continuewith open(os.path.join(originLabelsDir, txtFile), 'r') as fr:labelList = fr.readlines()for label in labelList:label = label.strip().split()x = float(label[1])y = float(label[2])w = float(label[3])h = float(label[4])# convert x,y,w,h to x1,y1,x2,y2H, W, _ = im.shapex1 = (x - w / 2) * Wy1 = (y - h / 2) * Hx2 = (x + w / 2) * Wy2 = (y + h / 2) * H# 標(biāo)簽序號(hào)從0開始計(jì)算, coco2017數(shù)據(jù)集標(biāo)號(hào)混亂,不管它了。cls_id = int(label[0])width = max(0, x2 - x1)height = max(0, y2 - y1)dataset['annotations'].append({'area': width * height,'bbox': [x1, y1, width, height],'category_id': cls_id,'id': ann_id_cnt,'image_id': k,'iscrowd': 0,# mask, 矩形是從左上角點(diǎn)按順時(shí)針的四個(gè)頂點(diǎn)'segmentation': [[x1, y1, x2, y1, x2, y2, x1, y2]]})ann_id_cnt += 1# 保存結(jié)果folder = os.path.join(root_path, 'annotations')if not os.path.exists(folder):os.makedirs(folder)if arg.random_split or arg.split_by_file:for phase in ['train', 'val', 'test']:json_name = os.path.join(root_path, 'annotations/{}.json'.format(phase))with open(json_name, 'w') as f:if phase == 'train':json.dump(train_dataset, f)elif phase == 'val':json.dump(val_dataset, f)elif phase == 'test':json.dump(test_dataset, f)print('Save annotation to {}'.format(json_name))else:json_name = os.path.join(root_path, 'annotations/{}'.format(arg.save_path))with open(json_name, 'w') as f:json.dump(dataset, f)print('Save annotation to {}'.format(json_name))if __name__ == "__main__":yolo2coco(arg)
三: 訓(xùn)練
以configs/faster_rcnn/faster-rcnn_r101_fpn_1x_coco.py為例
- mmdetection-mian創(chuàng)建文件夾data,在將上面轉(zhuǎn)換后的格式進(jìn)行簡(jiǎn)單整理如下,放到mmdetection-mian文件下
dataset數(shù)據(jù)文件配置
在路徑下面路徑中,修改數(shù)據(jù)集種類為自己數(shù)據(jù)集的種類。
mmdet/datasets/coco.py
configs
1.在configs/faster_rcnn/faster-rcnn_r101_fpn_1x_coco.py我們發(fā)現(xiàn),索引的是’./faster-rcnn_r50_fpn_1x_coco.py’
2.找到’./faster-rcnn_r50_fpn_1x_coco.py’,發(fā)現(xiàn)索引是下面代碼
3.修改
_base_ = ['../_base_/models/faster-rcnn_r50_fpn.py',#指向的是model dict,修改其中的num_classes類別為自己的類別。'../_base_/datasets/coco_detection.py',# 修改train_dataloader的ann_file為自己數(shù)據(jù)集json路徑,我這里ann_file='annotations/instances_val2017.json',val_dataloader,val_evaluator也要修改ann_file'../_base_/schedules/schedule_1x.py', # 優(yōu)化器,超參數(shù),自己實(shí)際情況來'../_base_/default_runtime.py'# 可以不修改
]
4.訓(xùn)練
- 若改動(dòng)框架源代碼后,一定要注意重新編譯后再使用。類似這里修改了幾個(gè)源代碼文件后再使用train命令之前,先要編譯,執(zhí)行下面命令。
pip install -v -e . # or "python setup.py develop"
- 訓(xùn)練語句
python tools/train.py configs/faster_rcnn/faster-rcnn_r101_fpn_1x_coco.py --work-dir work_dirs_2