coco.py 3.69 KB
Newer Older
Kai Chen's avatar
Kai Chen committed
1
2
3
import numpy as np
from pycocotools.coco import COCO

Kai Chen's avatar
Kai Chen committed
4
from .custom import CustomDataset
Kai Chen's avatar
Kai Chen committed
5
6


Kai Chen's avatar
Kai Chen committed
7
class CocoDataset(CustomDataset):
Kai Chen's avatar
Kai Chen committed
8

Kai Chen's avatar
Kai Chen committed
9
    def load_annotations(self, ann_file):
Kai Chen's avatar
Kai Chen committed
10
        self.coco = COCO(ann_file)
Kai Chen's avatar
Kai Chen committed
11
12
13
14
15
        self.cat_ids = self.coco.getCatIds()
        self.cat2label = {
            cat_id: i + 1
            for i, cat_id in enumerate(self.cat_ids)
        }
Kai Chen's avatar
Kai Chen committed
16
        self.img_ids = self.coco.getImgIds()
Kai Chen's avatar
Kai Chen committed
17
        img_infos = []
Kai Chen's avatar
Kai Chen committed
18
        for i in self.img_ids:
Kai Chen's avatar
Kai Chen committed
19
            info = self.coco.loadImgs(i)[0]
Kai Chen's avatar
Kai Chen committed
20
21
22
            info['filename'] = info['file_name']
            img_infos.append(info)
        return img_infos
Kai Chen's avatar
Kai Chen committed
23

Kai Chen's avatar
Kai Chen committed
24
25
    def get_ann_info(self, idx):
        img_id = self.img_infos[idx]['id']
Kai Chen's avatar
Kai Chen committed
26
27
        ann_ids = self.coco.getAnnIds(imgIds=img_id)
        ann_info = self.coco.loadAnns(ann_ids)
Kai Chen's avatar
Kai Chen committed
28
29
30
31
32
33
34
35
36
37
38
39
        return self._parse_ann_info(ann_info)

    def _filter_imgs(self, min_size=32):
        """Filter images too small or without ground truths."""
        valid_inds = []
        ids_with_ann = set(_['image_id'] for _ in self.coco.anns.values())
        for i, img_info in enumerate(self.img_infos):
            if self.img_ids[i] not in ids_with_ann:
                continue
            if min(img_info['width'], img_info['height']) >= min_size:
                valid_inds.append(i)
        return valid_inds
Kai Chen's avatar
Kai Chen committed
40

Kai Chen's avatar
Kai Chen committed
41
42
43
44
45
46
47
48
49
50
51
52
53
54
    def _parse_ann_info(self, ann_info, with_mask=True):
        """Parse bbox and mask annotation.

        Args:
            ann_info (list[dict]): Annotation info of an image.
            with_mask (bool): Whether to parse mask annotations.

        Returns:
            dict: A dict containing the following keys: bboxes, bboxes_ignore,
                labels, masks, mask_polys, poly_lens.
        """
        gt_bboxes = []
        gt_labels = []
        gt_bboxes_ignore = []
Kai Chen's avatar
Kai Chen committed
55
56
57
58
        # Two formats are provided.
        # 1. mask: a binary map of the same size of the image.
        # 2. polys: each mask consists of one or several polys, each poly is a
        # list of float.
Kai Chen's avatar
Kai Chen committed
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
        if with_mask:
            gt_masks = []
            gt_mask_polys = []
            gt_poly_lens = []
        for i, ann in enumerate(ann_info):
            if ann.get('ignore', False):
                continue
            x1, y1, w, h = ann['bbox']
            if ann['area'] <= 0 or w < 1 or h < 1:
                continue
            bbox = [x1, y1, x1 + w - 1, y1 + h - 1]
            if ann['iscrowd']:
                gt_bboxes_ignore.append(bbox)
            else:
                gt_bboxes.append(bbox)
                gt_labels.append(self.cat2label[ann['category_id']])
            if with_mask:
                gt_masks.append(self.coco.annToMask(ann))
                mask_polys = [
                    p for p in ann['segmentation'] if len(p) >= 6
                ]  # valid polygons have >= 3 points (6 coordinates)
                poly_lens = [len(p) for p in mask_polys]
                gt_mask_polys.append(mask_polys)
                gt_poly_lens.extend(poly_lens)
        if gt_bboxes:
            gt_bboxes = np.array(gt_bboxes, dtype=np.float32)
            gt_labels = np.array(gt_labels, dtype=np.int64)
        else:
            gt_bboxes = np.zeros((0, 4), dtype=np.float32)
            gt_labels = np.array([], dtype=np.int64)

        if gt_bboxes_ignore:
            gt_bboxes_ignore = np.array(gt_bboxes_ignore, dtype=np.float32)
        else:
            gt_bboxes_ignore = np.zeros((0, 4), dtype=np.float32)

        ann = dict(
            bboxes=gt_bboxes, labels=gt_labels, bboxes_ignore=gt_bboxes_ignore)

        if with_mask:
            ann['masks'] = gt_masks
            # poly format is not used in the current implementation
            ann['mask_polys'] = gt_mask_polys
            ann['poly_lens'] = gt_poly_lens
        return ann