voc.py 12.0 KB
Newer Older
J
jiangjiajun 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import absolute_import
import copy
17
import os
J
jiangjiajun 已提交
18 19
import os.path as osp
import random
S
sunyanfang01 已提交
20
import re
J
jiangjiajun 已提交
21
import numpy as np
F
FlyingQianMM 已提交
22
from collections import OrderedDict
J
jiangjiajun 已提交
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
import xml.etree.ElementTree as ET
import paddlex.utils.logging as logging
from .dataset import Dataset
from .dataset import is_pic
from .dataset import get_encoding


class VOCDetection(Dataset):
    """读取PascalVOC格式的检测数据集,并对样本进行相应的处理。

    Args:
        data_dir (str): 数据集所在的目录路径。
        file_list (str): 描述数据集图片文件和对应标注文件的文件路径(文本内每行路径为相对data_dir的相对路)。
        label_list (str): 描述数据集包含的类别信息文件路径。
        transforms (paddlex.det.transforms): 数据集中每个样本的预处理/增强算子。
        num_workers (int|str): 数据集中样本在预处理过程中的线程或进程数。默认为'auto'。当设为'auto'时,根据
            系统的实际CPU核数设置`num_workers`: 如果CPU核数的一半大于8,则`num_workers`为8,否则为CPU核数的
            一半。
        buffer_size (int): 数据集中样本在预处理过程中队列的缓存长度,以样本数为单位。默认为100。
        parallel_method (str): 数据集中样本在预处理过程中并行处理的方式,支持'thread'
S
sunyanfang01 已提交
43
            线程和'process'进程两种方式。默认为'process'(Windows和Mac下会强制使用thread,该参数无效)。
J
jiangjiajun 已提交
44 45 46 47 48 49 50 51 52 53 54 55
        shuffle (bool): 是否需要对数据集中样本打乱顺序。默认为False。
    """

    def __init__(self,
                 data_dir,
                 file_list,
                 label_list,
                 transforms=None,
                 num_workers='auto',
                 buffer_size=100,
                 parallel_method='process',
                 shuffle=False):
J
jiangjiajun 已提交
56
        from pycocotools.coco import COCO
J
jiangjiajun 已提交
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
        super(VOCDetection, self).__init__(
            transforms=transforms,
            num_workers=num_workers,
            buffer_size=buffer_size,
            parallel_method=parallel_method,
            shuffle=shuffle)
        self.file_list = list()
        self.labels = list()
        self._epoch = 0

        annotations = {}
        annotations['images'] = []
        annotations['categories'] = []
        annotations['annotations'] = []

F
FlyingQianMM 已提交
72
        cname2cid = OrderedDict()
J
jiangjiajun 已提交
73 74 75
        label_id = 1
        with open(label_list, 'r', encoding=get_encoding(label_list)) as fr:
            for line in fr.readlines():
S
SunAhong1993 已提交
76
                cname2cid[line.strip()] = label_id
J
jiangjiajun 已提交
77
                label_id += 1
S
SunAhong1993 已提交
78
                self.labels.append(line.strip())
J
jiangjiajun 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
        logging.info("Starting to read file list from dataset...")
        for k, v in cname2cid.items():
            annotations['categories'].append({
                'supercategory': 'component',
                'id': v,
                'name': k
            })
        ct = 0
        ann_ct = 0
        with open(file_list, 'r', encoding=get_encoding(file_list)) as fr:
            while True:
                line = fr.readline()
                if not line:
                    break
                img_file, xml_file = [osp.join(data_dir, x) \
                        for x in line.strip().split()[:2]]
                if not is_pic(img_file):
                    continue
                if not osp.isfile(xml_file):
                    continue
                if not osp.exists(img_file):
S
sunyanfang01 已提交
100 101
                    raise IOError('The image file {} is not exist!'.format(
                        img_file))
J
jiangjiajun 已提交
102 103 104 105 106 107
                tree = ET.parse(xml_file)
                if tree.find('id') is None:
                    im_id = np.array([ct])
                else:
                    ct = int(tree.find('id').text)
                    im_id = np.array([int(tree.find('id').text)])
S
sunyanfang01 已提交
108
                pattern = re.compile('<object>', re.IGNORECASE)
F
FlyingQianMM 已提交
109 110
                obj_tag = pattern.findall(
                    str(ET.tostringlist(tree.getroot())))[0][1:-1]
S
sunyanfang01 已提交
111 112
                objs = tree.findall(obj_tag)
                pattern = re.compile('<size>', re.IGNORECASE)
F
FlyingQianMM 已提交
113 114
                size_tag = pattern.findall(
                    str(ET.tostringlist(tree.getroot())))[0][1:-1]
S
sunyanfang01 已提交
115 116
                size_element = tree.find(size_tag)
                pattern = re.compile('<width>', re.IGNORECASE)
F
FlyingQianMM 已提交
117 118
                width_tag = pattern.findall(
                    str(ET.tostringlist(size_element)))[0][1:-1]
S
sunyanfang01 已提交
119 120
                im_w = float(size_element.find(width_tag).text)
                pattern = re.compile('<height>', re.IGNORECASE)
F
FlyingQianMM 已提交
121 122
                height_tag = pattern.findall(
                    str(ET.tostringlist(size_element)))[0][1:-1]
S
sunyanfang01 已提交
123
                im_h = float(size_element.find(height_tag).text)
J
jiangjiajun 已提交
124 125 126 127 128 129
                gt_bbox = np.zeros((len(objs), 4), dtype=np.float32)
                gt_class = np.zeros((len(objs), 1), dtype=np.int32)
                gt_score = np.ones((len(objs), 1), dtype=np.float32)
                is_crowd = np.zeros((len(objs), 1), dtype=np.int32)
                difficult = np.zeros((len(objs), 1), dtype=np.int32)
                for i, obj in enumerate(objs):
S
sunyanfang01 已提交
130
                    pattern = re.compile('<name>', re.IGNORECASE)
F
FlyingQianMM 已提交
131 132
                    name_tag = pattern.findall(str(ET.tostringlist(obj)))[0][
                        1:-1]
S
SunAhong1993 已提交
133
                    cname = obj.find(name_tag).text.strip()
J
jiangjiajun 已提交
134
                    gt_class[i][0] = cname2cid[cname]
S
sunyanfang01 已提交
135
                    pattern = re.compile('<difficult>', re.IGNORECASE)
F
FlyingQianMM 已提交
136 137
                    diff_tag = pattern.findall(str(ET.tostringlist(obj)))[0][
                        1:-1]
S
sunyanfang01 已提交
138 139 140 141
                    try:
                        _difficult = int(obj.find(diff_tag).text)
                    except Exception:
                        _difficult = 0
S
sunyanfang01 已提交
142
                    pattern = re.compile('<bndbox>', re.IGNORECASE)
F
FlyingQianMM 已提交
143 144
                    box_tag = pattern.findall(str(ET.tostringlist(obj)))[0][1:
                                                                            -1]
S
sunyanfang01 已提交
145 146
                    box_element = obj.find(box_tag)
                    pattern = re.compile('<xmin>', re.IGNORECASE)
F
FlyingQianMM 已提交
147 148
                    xmin_tag = pattern.findall(
                        str(ET.tostringlist(box_element)))[0][1:-1]
S
sunyanfang01 已提交
149
                    x1 = float(box_element.find(xmin_tag).text)
S
sunyanfang01 已提交
150
                    pattern = re.compile('<ymin>', re.IGNORECASE)
F
FlyingQianMM 已提交
151 152
                    ymin_tag = pattern.findall(
                        str(ET.tostringlist(box_element)))[0][1:-1]
S
sunyanfang01 已提交
153
                    y1 = float(box_element.find(ymin_tag).text)
S
sunyanfang01 已提交
154
                    pattern = re.compile('<xmax>', re.IGNORECASE)
F
FlyingQianMM 已提交
155 156
                    xmax_tag = pattern.findall(
                        str(ET.tostringlist(box_element)))[0][1:-1]
S
sunyanfang01 已提交
157
                    x2 = float(box_element.find(xmax_tag).text)
S
sunyanfang01 已提交
158
                    pattern = re.compile('<ymax>', re.IGNORECASE)
F
FlyingQianMM 已提交
159 160
                    ymax_tag = pattern.findall(
                        str(ET.tostringlist(box_element)))[0][1:-1]
S
sunyanfang01 已提交
161
                    y2 = float(box_element.find(ymax_tag).text)
J
jiangjiajun 已提交
162 163
                    x1 = max(0, x1)
                    y1 = max(0, y1)
S
sunyanfang01 已提交
164 165 166
                    if im_w > 0.5 and im_h > 0.5:
                        x2 = min(im_w - 1, x2)
                        y2 = min(im_h - 1, y2)
J
jiangjiajun 已提交
167 168 169 170
                    gt_bbox[i] = [x1, y1, x2, y2]
                    is_crowd[i][0] = 0
                    difficult[i][0] = _difficult
                    annotations['annotations'].append({
S
sunyanfang01 已提交
171 172
                        'iscrowd': 0,
                        'image_id': int(im_id[0]),
J
jiangjiajun 已提交
173
                        'bbox': [x1, y1, x2 - x1 + 1, y2 - y1 + 1],
S
sunyanfang01 已提交
174 175 176 177
                        'area': float((x2 - x1 + 1) * (y2 - y1 + 1)),
                        'category_id': cname2cid[cname],
                        'id': ann_ct,
                        'difficult': _difficult
J
jiangjiajun 已提交
178 179 180 181 182
                    })
                    ann_ct += 1

                im_info = {
                    'im_id': im_id,
S
sunyanfang01 已提交
183
                    'image_shape': np.array([im_h, im_w]).astype('int32'),
J
jiangjiajun 已提交
184 185 186 187 188 189
                }
                label_info = {
                    'is_crowd': is_crowd,
                    'gt_class': gt_class,
                    'gt_bbox': gt_bbox,
                    'gt_score': gt_score,
F
FlyingQianMM 已提交
190
                    'gt_poly': [],
J
jiangjiajun 已提交
191 192 193 194 195 196 197
                    'difficult': difficult
                }
                voc_rec = (im_info, label_info)
                if len(objs) != 0:
                    self.file_list.append([img_file, voc_rec])
                    ct += 1
                    annotations['images'].append({
S
sunyanfang01 已提交
198 199 200 201
                        'height': im_h,
                        'width': im_w,
                        'id': int(im_id[0]),
                        'file_name': osp.split(img_file)[1]
J
jiangjiajun 已提交
202 203 204 205 206 207 208 209 210 211 212
                    })

        if not len(self.file_list) > 0:
            raise Exception('not found any voc record in %s' % (file_list))
        logging.info("{} samples in file {}".format(
            len(self.file_list), file_list))
        self.num_samples = len(self.file_list)
        self.coco_gt = COCO()
        self.coco_gt.dataset = annotations
        self.coco_gt.createIndex()

F
FlyingQianMM 已提交
213
    def add_negative_samples(self, image_dir):
214 215
        import cv2
        if not osp.exists(image_dir):
F
FlyingQianMM 已提交
216 217
            raise Exception("{} background images directory does not exist.".
                            format(image_dir))
218 219 220 221 222 223 224 225 226 227 228 229
        image_list = os.listdir(image_dir)
        max_img_id = max(self.coco_gt.getImgIds())
        for image in image_list:
            if not is_pic(image):
                continue
            # False ground truth
            gt_bbox = np.array([[0, 0, 1e-05, 1e-05]], dtype=np.float32)
            gt_class = np.array([[0]], dtype=np.int32)
            gt_score = np.ones((1, 1), dtype=np.float32)
            is_crowd = np.array([[0]], dtype=np.int32)
            difficult = np.zeros((1, 1), dtype=np.int32)
            gt_poly = [[[0, 0, 0, 1e-05, 1e-05, 1e-05, 1e-05, 0]]]
F
FlyingQianMM 已提交
230

231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
            max_img_id += 1
            im_fname = osp.join(image_dir, image)
            img_data = cv2.imread(im_fname)
            im_h, im_w, im_c = img_data.shape
            im_info = {
                'im_id': np.array([max_img_id]).astype('int32'),
                'image_shape': np.array([im_h, im_w]).astype('int32'),
            }
            label_info = {
                'is_crowd': is_crowd,
                'gt_class': gt_class,
                'gt_bbox': gt_bbox,
                'gt_score': gt_score,
                'difficult': difficult,
                'gt_poly': gt_poly
            }
            coco_rec = (im_info, label_info)
            self.file_list.append([im_fname, coco_rec])
        self.num_samples = len(self.file_list)

J
jiangjiajun 已提交
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
    def iterator(self):
        self._epoch += 1
        self._pos = 0
        files = copy.deepcopy(self.file_list)
        if self.shuffle:
            random.shuffle(files)
        files = files[:self.num_samples]
        self.num_samples = len(files)
        for f in files:
            records = f[1]
            im_info = copy.deepcopy(records[0])
            label_info = copy.deepcopy(records[1])
            im_info['epoch'] = self._epoch
            if self.num_samples > 1:
                mix_idx = random.randint(1, self.num_samples - 1)
                mix_pos = (mix_idx + self._pos) % self.num_samples
            else:
                mix_pos = 0
            im_info['mixup'] = [
S
sunyanfang01 已提交
270
                files[mix_pos][0], copy.deepcopy(files[mix_pos][1][0]),
J
jiangjiajun 已提交
271 272 273 274 275
                copy.deepcopy(files[mix_pos][1][1])
            ]
            self._pos += 1
            sample = [f[0], im_info, label_info]
            yield sample