You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

customize_dataset.md 19 kB

2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. # Tutorial 2: Customize Datasets
  2. ## Support new data format
  3. To support a new data format, you can either convert them to existing formats (COCO format or PASCAL format) or directly convert them to the middle format. You could also choose to convert them offline (before training by a script) or online (implement a new dataset and do the conversion at training). In MMDetection, we recommend to convert the data into COCO formats and do the conversion offline, thus you only need to modify the config's data annotation paths and classes after the conversion of your data.
  4. ### Reorganize new data formats to existing format
  5. The simplest way is to convert your dataset to existing dataset formats (COCO or PASCAL VOC).
  6. The annotation json files in COCO format has the following necessary keys:
  7. ```python
  8. 'images': [
  9. {
  10. 'file_name': 'COCO_val2014_000000001268.jpg',
  11. 'height': 427,
  12. 'width': 640,
  13. 'id': 1268
  14. },
  15. ...
  16. ],
  17. 'annotations': [
  18. {
  19. 'segmentation': [[192.81,
  20. 247.09,
  21. ...
  22. 219.03,
  23. 249.06]], # if you have mask labels
  24. 'area': 1035.749,
  25. 'iscrowd': 0,
  26. 'image_id': 1268,
  27. 'bbox': [192.81, 224.8, 74.73, 33.43],
  28. 'category_id': 16,
  29. 'id': 42986
  30. },
  31. ...
  32. ],
  33. 'categories': [
  34. {'id': 0, 'name': 'car'},
  35. ]
  36. ```
  37. There are three necessary keys in the json file:
  38. - `images`: contains a list of images with their information like `file_name`, `height`, `width`, and `id`.
  39. - `annotations`: contains the list of instance annotations.
  40. - `categories`: contains the list of categories names and their ID.
  41. After the data pre-processing, there are two steps for users to train the customized new dataset with existing format (e.g. COCO format):
  42. 1. Modify the config file for using the customized dataset.
  43. 2. Check the annotations of the customized dataset.
  44. Here we give an example to show the above two steps, which uses a customized dataset of 5 classes with COCO format to train an existing Cascade Mask R-CNN R50-FPN detector.
  45. #### 1. Modify the config file for using the customized dataset
  46. There are two aspects involved in the modification of config file:
  47. 1. The `data` field. Specifically, you need to explicitly add the `classes` fields in `data.train`, `data.val` and `data.test`.
  48. 2. The `num_classes` field in the `model` part. Explicitly over-write all the `num_classes` from default value (e.g. 80 in COCO) to your classes number.
  49. In `configs/my_custom_config.py`:
  50. ```python
  51. # the new config inherits the base configs to highlight the necessary modification
  52. _base_ = './cascade_mask_rcnn_r50_fpn_1x_coco.py'
  53. # 1. dataset settings
  54. dataset_type = 'CocoDataset'
  55. classes = ('a', 'b', 'c', 'd', 'e')
  56. data = dict(
  57. samples_per_gpu=2,
  58. workers_per_gpu=2,
  59. train=dict(
  60. type=dataset_type,
  61. # explicitly add your class names to the field `classes`
  62. classes=classes,
  63. ann_file='path/to/your/train/annotation_data',
  64. img_prefix='path/to/your/train/image_data'),
  65. val=dict(
  66. type=dataset_type,
  67. # explicitly add your class names to the field `classes`
  68. classes=classes,
  69. ann_file='path/to/your/val/annotation_data',
  70. img_prefix='path/to/your/val/image_data'),
  71. test=dict(
  72. type=dataset_type,
  73. # explicitly add your class names to the field `classes`
  74. classes=classes,
  75. ann_file='path/to/your/test/annotation_data',
  76. img_prefix='path/to/your/test/image_data'))
  77. # 2. model settings
  78. # explicitly over-write all the `num_classes` field from default 80 to 5.
  79. model = dict(
  80. roi_head=dict(
  81. bbox_head=[
  82. dict(
  83. type='Shared2FCBBoxHead',
  84. # explicitly over-write all the `num_classes` field from default 80 to 5.
  85. num_classes=5),
  86. dict(
  87. type='Shared2FCBBoxHead',
  88. # explicitly over-write all the `num_classes` field from default 80 to 5.
  89. num_classes=5),
  90. dict(
  91. type='Shared2FCBBoxHead',
  92. # explicitly over-write all the `num_classes` field from default 80 to 5.
  93. num_classes=5)],
  94. # explicitly over-write all the `num_classes` field from default 80 to 5.
  95. mask_head=dict(num_classes=5)))
  96. ```
  97. #### 2. Check the annotations of the customized dataset
  98. Assuming your customized dataset is COCO format, make sure you have the correct annotations in the customized dataset:
  99. 1. The length for `categories` field in annotations should exactly equal the tuple length of `classes` fields in your config, meaning the number of classes (e.g. 5 in this example).
  100. 2. The `classes` fields in your config file should have exactly the same elements and the same order with the `name` in `categories` of annotations. MMDetection automatically maps the uncontinuous `id` in `categories` to the continuous label indices, so the string order of `name` in `categories` field affects the order of label indices. Meanwhile, the string order of `classes` in config affects the label text during visualization of predicted bounding boxes.
  101. 3. The `category_id` in `annotations` field should be valid, i.e., all values in `category_id` should belong to `id` in `categories`.
  102. Here is a valid example of annotations:
  103. ```python
  104. 'annotations': [
  105. {
  106. 'segmentation': [[192.81,
  107. 247.09,
  108. ...
  109. 219.03,
  110. 249.06]], # if you have mask labels
  111. 'area': 1035.749,
  112. 'iscrowd': 0,
  113. 'image_id': 1268,
  114. 'bbox': [192.81, 224.8, 74.73, 33.43],
  115. 'category_id': 16,
  116. 'id': 42986
  117. },
  118. ...
  119. ],
  120. # MMDetection automatically maps the uncontinuous `id` to the continuous label indices.
  121. 'categories': [
  122. {'id': 1, 'name': 'a'}, {'id': 3, 'name': 'b'}, {'id': 4, 'name': 'c'}, {'id': 16, 'name': 'd'}, {'id': 17, 'name': 'e'},
  123. ]
  124. ```
  125. We use this way to support CityScapes dataset. The script is in [cityscapes.py](https://github.com/open-mmlab/mmdetection/blob/master/tools/dataset_converters/cityscapes.py) and we also provide the finetuning [configs](https://github.com/open-mmlab/mmdetection/blob/master/configs/cityscapes).
  126. **Note**
  127. 1. For instance segmentation datasets, **MMDetection only supports evaluating mask AP of dataset in COCO format for now**.
  128. 2. It is recommended to convert the data offline before training, thus you can still use `CocoDataset` and only need to modify the path of annotations and the training classes.
  129. ### Reorganize new data format to middle format
  130. It is also fine if you do not want to convert the annotation format to COCO or PASCAL format.
  131. Actually, we define a simple annotation format and all existing datasets are
  132. processed to be compatible with it, either online or offline.
  133. The annotation of a dataset is a list of dict, each dict corresponds to an image.
  134. There are 3 field `filename` (relative path), `width`, `height` for testing,
  135. and an additional field `ann` for training. `ann` is also a dict containing at least 2 fields:
  136. `bboxes` and `labels`, both of which are numpy arrays. Some datasets may provide
  137. annotations like crowd/difficult/ignored bboxes, we use `bboxes_ignore` and `labels_ignore`
  138. to cover them.
  139. Here is an example.
  140. ```python
  141. [
  142. {
  143. 'filename': 'a.jpg',
  144. 'width': 1280,
  145. 'height': 720,
  146. 'ann': {
  147. 'bboxes': <np.ndarray, float32> (n, 4),
  148. 'labels': <np.ndarray, int64> (n, ),
  149. 'bboxes_ignore': <np.ndarray, float32> (k, 4),
  150. 'labels_ignore': <np.ndarray, int64> (k, ) (optional field)
  151. }
  152. },
  153. ...
  154. ]
  155. ```
  156. There are two ways to work with custom datasets.
  157. - online conversion
  158. You can write a new Dataset class inherited from `CustomDataset`, and overwrite two methods
  159. `load_annotations(self, ann_file)` and `get_ann_info(self, idx)`,
  160. like [CocoDataset](https://github.com/open-mmlab/mmdetection/blob/master/mmdet/datasets/coco.py) and [VOCDataset](https://github.com/open-mmlab/mmdetection/blob/master/mmdet/datasets/voc.py).
  161. - offline conversion
  162. You can convert the annotation format to the expected format above and save it to
  163. a pickle or json file, like [pascal_voc.py](https://github.com/open-mmlab/mmdetection/blob/master/tools/dataset_converters/pascal_voc.py).
  164. Then you can simply use `CustomDataset`.
  165. ### An example of customized dataset
  166. Assume the annotation is in a new format in text files.
  167. The bounding boxes annotations are stored in text file `annotation.txt` as the following
  168. ```
  169. #
  170. 000001.jpg
  171. 1280 720
  172. 2
  173. 10 20 40 60 1
  174. 20 40 50 60 2
  175. #
  176. 000002.jpg
  177. 1280 720
  178. 3
  179. 50 20 40 60 2
  180. 20 40 30 45 2
  181. 30 40 50 60 3
  182. ```
  183. We can create a new dataset in `mmdet/datasets/my_dataset.py` to load the data.
  184. ```python
  185. import mmcv
  186. import numpy as np
  187. from .builder import DATASETS
  188. from .custom import CustomDataset
  189. @DATASETS.register_module()
  190. class MyDataset(CustomDataset):
  191. CLASSES = ('person', 'bicycle', 'car', 'motorcycle')
  192. def load_annotations(self, ann_file):
  193. ann_list = mmcv.list_from_file(ann_file)
  194. data_infos = []
  195. for i, ann_line in enumerate(ann_list):
  196. if ann_line != '#':
  197. continue
  198. img_shape = ann_list[i + 2].split(' ')
  199. width = int(img_shape[0])
  200. height = int(img_shape[1])
  201. bbox_number = int(ann_list[i + 3])
  202. anns = ann_line.split(' ')
  203. bboxes = []
  204. labels = []
  205. for anns in ann_list[i + 4:i + 4 + bbox_number]:
  206. bboxes.append([float(ann) for ann in anns[:4]])
  207. labels.append(int(anns[4]))
  208. data_infos.append(
  209. dict(
  210. filename=ann_list[i + 1],
  211. width=width,
  212. height=height,
  213. ann=dict(
  214. bboxes=np.array(bboxes).astype(np.float32),
  215. labels=np.array(labels).astype(np.int64))
  216. ))
  217. return data_infos
  218. def get_ann_info(self, idx):
  219. return self.data_infos[idx]['ann']
  220. ```
  221. Then in the config, to use `MyDataset` you can modify the config as the following
  222. ```python
  223. dataset_A_train = dict(
  224. type='MyDataset',
  225. ann_file = 'image_list.txt',
  226. pipeline=train_pipeline
  227. )
  228. ```
  229. ## Customize datasets by dataset wrappers
  230. MMDetection also supports many dataset wrappers to mix the dataset or modify the dataset distribution for training.
  231. Currently it supports to three dataset wrappers as below:
  232. - `RepeatDataset`: simply repeat the whole dataset.
  233. - `ClassBalancedDataset`: repeat dataset in a class balanced manner.
  234. - `ConcatDataset`: concat datasets.
  235. ### Repeat dataset
  236. We use `RepeatDataset` as wrapper to repeat the dataset. For example, suppose the original dataset is `Dataset_A`, to repeat it, the config looks like the following
  237. ```python
  238. dataset_A_train = dict(
  239. type='RepeatDataset',
  240. times=N,
  241. dataset=dict( # This is the original config of Dataset_A
  242. type='Dataset_A',
  243. ...
  244. pipeline=train_pipeline
  245. )
  246. )
  247. ```
  248. ### Class balanced dataset
  249. We use `ClassBalancedDataset` as wrapper to repeat the dataset based on category
  250. frequency. The dataset to repeat needs to instantiate function `self.get_cat_ids(idx)`
  251. to support `ClassBalancedDataset`.
  252. For example, to repeat `Dataset_A` with `oversample_thr=1e-3`, the config looks like the following
  253. ```python
  254. dataset_A_train = dict(
  255. type='ClassBalancedDataset',
  256. oversample_thr=1e-3,
  257. dataset=dict( # This is the original config of Dataset_A
  258. type='Dataset_A',
  259. ...
  260. pipeline=train_pipeline
  261. )
  262. )
  263. ```
  264. You may refer to [source code](../../mmdet/datasets/dataset_wrappers.py) for details.
  265. ### Concatenate dataset
  266. There are three ways to concatenate the dataset.
  267. 1. If the datasets you want to concatenate are in the same type with different annotation files, you can concatenate the dataset configs like the following.
  268. ```python
  269. dataset_A_train = dict(
  270. type='Dataset_A',
  271. ann_file = ['anno_file_1', 'anno_file_2'],
  272. pipeline=train_pipeline
  273. )
  274. ```
  275. If the concatenated dataset is used for test or evaluation, this manner supports to evaluate each dataset separately. To test the concatenated datasets as a whole, you can set `separate_eval=False` as below.
  276. ```python
  277. dataset_A_train = dict(
  278. type='Dataset_A',
  279. ann_file = ['anno_file_1', 'anno_file_2'],
  280. separate_eval=False,
  281. pipeline=train_pipeline
  282. )
  283. ```
  284. 2. In case the dataset you want to concatenate is different, you can concatenate the dataset configs like the following.
  285. ```python
  286. dataset_A_train = dict()
  287. dataset_B_train = dict()
  288. data = dict(
  289. imgs_per_gpu=2,
  290. workers_per_gpu=2,
  291. train = [
  292. dataset_A_train,
  293. dataset_B_train
  294. ],
  295. val = dataset_A_val,
  296. test = dataset_A_test
  297. )
  298. ```
  299. If the concatenated dataset is used for test or evaluation, this manner also supports to evaluate each dataset separately.
  300. 3. We also support to define `ConcatDataset` explicitly as the following.
  301. ```python
  302. dataset_A_val = dict()
  303. dataset_B_val = dict()
  304. data = dict(
  305. imgs_per_gpu=2,
  306. workers_per_gpu=2,
  307. train=dataset_A_train,
  308. val=dict(
  309. type='ConcatDataset',
  310. datasets=[dataset_A_val, dataset_B_val],
  311. separate_eval=False))
  312. ```
  313. This manner allows users to evaluate all the datasets as a single one by setting `separate_eval=False`.
  314. **Note:**
  315. 1. The option `separate_eval=False` assumes the datasets use `self.data_infos` during evaluation. Therefore, COCO datasets do not support this behavior since COCO datasets do not fully rely on `self.data_infos` for evaluation. Combining different types of datasets and evaluating them as a whole is not tested thus is not suggested.
  316. 2. Evaluating `ClassBalancedDataset` and `RepeatDataset` is not supported thus evaluating concatenated datasets of these types is also not supported.
  317. A more complex example that repeats `Dataset_A` and `Dataset_B` by N and M times, respectively, and then concatenates the repeated datasets is as the following.
  318. ```python
  319. dataset_A_train = dict(
  320. type='RepeatDataset',
  321. times=N,
  322. dataset=dict(
  323. type='Dataset_A',
  324. ...
  325. pipeline=train_pipeline
  326. )
  327. )
  328. dataset_A_val = dict(
  329. ...
  330. pipeline=test_pipeline
  331. )
  332. dataset_A_test = dict(
  333. ...
  334. pipeline=test_pipeline
  335. )
  336. dataset_B_train = dict(
  337. type='RepeatDataset',
  338. times=M,
  339. dataset=dict(
  340. type='Dataset_B',
  341. ...
  342. pipeline=train_pipeline
  343. )
  344. )
  345. data = dict(
  346. imgs_per_gpu=2,
  347. workers_per_gpu=2,
  348. train = [
  349. dataset_A_train,
  350. dataset_B_train
  351. ],
  352. val = dataset_A_val,
  353. test = dataset_A_test
  354. )
  355. ```
  356. ## Modify Dataset Classes
  357. With existing dataset types, we can modify the class names of them to train subset of the annotations.
  358. For example, if you want to train only three classes of the current dataset,
  359. you can modify the classes of dataset.
  360. The dataset will filter out the ground truth boxes of other classes automatically.
  361. ```python
  362. classes = ('person', 'bicycle', 'car')
  363. data = dict(
  364. train=dict(classes=classes),
  365. val=dict(classes=classes),
  366. test=dict(classes=classes))
  367. ```
  368. MMDetection V2.0 also supports to read the classes from a file, which is common in real applications.
  369. For example, assume the `classes.txt` contains the name of classes as the following.
  370. ```
  371. person
  372. bicycle
  373. car
  374. ```
  375. Users can set the classes as a file path, the dataset will load it and convert it to a list automatically.
  376. ```python
  377. classes = 'path/to/classes.txt'
  378. data = dict(
  379. train=dict(classes=classes),
  380. val=dict(classes=classes),
  381. test=dict(classes=classes))
  382. ```
  383. **Note**:
  384. - Before MMDetection v2.5.0, the dataset will filter out the empty GT images automatically if the classes are set and there is no way to disable that through config. This is an undesirable behavior and introduces confusion because if the classes are not set, the dataset only filter the empty GT images when `filter_empty_gt=True` and `test_mode=False`. After MMDetection v2.5.0, we decouple the image filtering process and the classes modification, i.e., the dataset will only filter empty GT images when `filter_empty_gt=True` and `test_mode=False`, no matter whether the classes are set. Thus, setting the classes only influences the annotations of classes used for training and users could decide whether to filter empty GT images by themselves.
  385. - Since the middle format only has box labels and does not contain the class names, when using `CustomDataset`, users cannot filter out the empty GT images through configs but only do this offline.
  386. - Please remember to modify the `num_classes` in the head when specifying `classes` in dataset. We implemented [NumClassCheckHook](https://github.com/open-mmlab/mmdetection/blob/master/mmdet/datasets/utils.py) to check whether the numbers are consistent since v2.9.0(after PR#4508).
  387. - The features for setting dataset classes and dataset filtering will be refactored to be more user-friendly in the future (depends on the progress).
  388. ## COCO Panoptic Dataset
  389. Now we support COCO Panoptic Dataset, the format of panoptic annotations is different from COCO format.
  390. Both the foreground and the background will exist in the annotation file.
  391. The annotation json files in COCO Panoptic format has the following necessary keys:
  392. ```python
  393. 'images': [
  394. {
  395. 'file_name': '000000001268.jpg',
  396. 'height': 427,
  397. 'width': 640,
  398. 'id': 1268
  399. },
  400. ...
  401. ]
  402. 'annotations': [
  403. {
  404. 'filename': '000000001268.jpg',
  405. 'image_id': 1268,
  406. 'segments_info': [
  407. {
  408. 'id':8345037, # One-to-one correspondence with the id in the annotation map.
  409. 'category_id': 51,
  410. 'iscrowd': 0,
  411. 'bbox': (x1, y1, w, h), # The bbox of the background is the outer rectangle of its mask.
  412. 'area': 24315
  413. },
  414. ...
  415. ]
  416. },
  417. ...
  418. ]
  419. 'categories': [ # including both foreground categories and background categories
  420. {'id': 0, 'name': 'person'},
  421. ...
  422. ]
  423. ```
  424. Moreover, the `seg_prefix` must be set to the path of the panoptic annotation images.
  425. ```python
  426. data = dict(
  427. type='CocoPanopticDataset',
  428. train=dict(
  429. seg_prefix = 'path/to/your/train/panoptic/image_annotation_data'
  430. ),
  431. val=dict(
  432. seg_prefix = 'path/to/your/train/panoptic/image_annotation_data'
  433. )
  434. )
  435. ```

No Description

Contributors (2)