File size: 15,450 Bytes
95d0568
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3710f75
 
 
 
 
4c0ceea
 
 
 
 
95d0568
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3710f75
 
 
 
 
 
 
 
 
 
 
 
95d0568
 
 
 
974c47b
95d0568
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3710f75
 
 
 
 
 
 
 
cdd9e5f
 
 
 
 
95d0568
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3710f75
95d0568
3710f75
 
 
 
 
 
 
 
4c0ceea
 
cdd9e5f
4c0ceea
 
 
 
95d0568
 
 
 
 
 
 
 
974c47b
 
 
95d0568
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3710f75
870f86a
 
 
 
 
 
 
 
 
3710f75
 
 
 
cdd9e5f
3710f75
 
 
 
 
 
 
 
 
95d0568
 
 
 
 
 
 
 
 
3710f75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95d0568
 
 
 
 
 
 
3710f75
95d0568
 
 
 
3710f75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
__doc__ = """\
GLENDA (Gynecologic Laparoscopy ENdometriosis DAtaset) comprises over 350 annotated endometriosis lesion images taken from 100+ gynecologic laparoscopy surgeries as well as over 13K unannotated non pathological images of 20+ surgeries. The dataset is purposefully created to be utilized for a variety of automatic content analysis problems in the context of Endometriosis recognition.

Description
Endometriosis is a benign but potentially painful condition among women in child bearing age involving the growth of uterine-like tissue in locations outside of the uterus. Corresponding lesions can be found in various positions and severities, often in multiple instances per patient requiring a physician to determine its extent. This most frequently is accomplished by calculating its magnitude via utilizing the combination of two popular classification systems, the revised American Society for Reproductive Medicine (rASRM) and the European Enzian scores. Endometriosis can not reliably identified by laymen, therefore, the dataset has been created with the help of medical experts in the field of endometriosis treatment.

Purposes
* (endometriosis) classification (binary or using 4 pathological endometriosis categories)
* detection/localization

Overview
The dataset includes region-based annotations of 4 pathological endometriosis categories as well as non pathological counter example images. Annotations are created for single video frames that may be part of larger sequences comprising several consecutive frames (all showing the annotated condition). Frames can contain multiple annotations, potentially of different categories. Each single annotation is exported as a binary image (similar to below examples, albeit one image per annotation).

Disclaimer
The dataset is exclusively provided for scientific research purposes and as such cannot be used commercially or for any other purpose. If any other purpose is intended, you may directly contact the originator of the videos, Prof. Dr. Jörg Keckstein.

In addition, reference must be made to the following publication when this dataset is used in any academic and research reports:
A. Leibetseder, S. Kletz, K. Schoeffmann, S. Keckstein and J. Keckstein. 2020. GLENDA: Gynecologic Laparoscopy Endometriosis Dataset. In Proceedings of the 26th International Conference on Multimedia Modeling, MMM 2020. Springer, Cham.
"""
import json
from pathlib import Path
import re

import datasets

DESCRIPTION = str(__doc__)

LICENSE = "cc-by-nc-4.0"


CITATION = "Leibetseder, A., Kletz, S., Schoeffmann, K., Keckstein, S., Keckstein, J. (2020). GLENDA: Gynecologic Laparoscopy Endometriosis Dataset. In: , et al. MultiMedia Modeling. MMM 2020. Lecture Notes in Computer Science(), vol 11962. Springer, Cham. https://doi.org/10.1007/978-3-030-37734-2_36"

HOMEPAGE = "http://ftp.itec.aau.at/datasets/GLENDA/index.html"

VERSION = "1.5"

URLS = {
    "endometriosis_classes": "http://ftp.itec.aau.at/datasets/GLENDA/downloads//Glenda_v1.5_classes.zip",
    "no_pathology": "http://ftp.itec.aau.at/datasets/GLENDA/downloads/GLENDA_v1.5_no_pathology.zip",
}

CLASS_NAMES = {
    "binary_classification": ("no_pathology", "endometriosis"),
    "multiclass_classification": (
        "No-Pathology",
        "6.1.1.1_Endo-Peritoneum",
        "6.1.1.2_Endo-Ovar",
        "6.1.1.3_Endo-TIE",
        "6.1.1.4_Endo-Uterus",
    ),
}

ENDOMETRIOSIS_IMAGE_METADATA_REGEX = re.compile(
    r"c_(?P<case_id>[0-9]+)_v_\(video_(?P<video_id>[0-9]+).mp4\)_f_(?P<frame_id>[0-9]+).jpg"
)

NO_PATHOLOGY_IMAGE_METADATA_REGEX = re.compile(
    r"v_(?P<video_id>[0-9]+)_s_(?P<from_seconds>[0-9]+)-(?P<to_seconds>[0-9]+)/f_(?P<frame_id>[0-9]+).jpg"
)


class GLENDA(datasets.GeneratorBasedBuilder):
    BUILDER_CONFIGS = [
        datasets.BuilderConfig(
            name="binary_classification",
            description="Contains images without visible pathology in relation to endometriosis (label = 'no_pathology') and different endometriosis classes (label = 'endometriosis').",
            version=datasets.Version(f"{VERSION}.0"),
        ),
        datasets.BuilderConfig(
            name="multiclass_classification",
            description="Contains images without visible pathology in relation to endometriosis (label = 'No-Pathology') and different endometriosis classes (label is exactly one of: 6.1.1.1_Endo-Peritoneum, 6.1.1.2_Endo-Ovar, 6.1.1.3_Endo-TIE, 6.1.1.4_Endo-Uterus).",
            version=datasets.Version(f"{VERSION}.0"),
        ),
        datasets.BuilderConfig(
            name="object_detection",
            description="Contains images without visible pathology in relation to endometriosis and different endometriosis classes with corresponding COCO bounding box annotations.",
            version=datasets.Version(f"{VERSION}.0"),
        ),
        # datasets.BuilderConfig(
        #     name="instance_segmentation",
        #     description="Contains images without visible pathology in relation to endometriosis and different endometriosis classes with COCO instance segmentation annotations.",
        #     version=datasets.Version(f"{VERSION}.0"),
        # ),
    ]

    def _info(self):
        features = {
            "image": datasets.Image(),
            "metadata": {
                "id": datasets.Value(dtype="int32"),
                "width": datasets.Value(dtype="int32"),
                "height": datasets.Value(dtype="int32"),
                "file_name": datasets.Value(dtype="string"),
                "path": datasets.Value(dtype="string"),
                "fickr_url": datasets.Value(dtype="string"),
                "coco_url": datasets.Value(dtype="string"),
                "date_captured": datasets.Value(dtype="string"),
                "case_id": datasets.Value("int32"),
                "video_id": datasets.Value("int32"),
                "frame_id": datasets.Value("int32"),
                "from_seconds": datasets.Value("int32"),
                "to_seconds": datasets.Value("int32"),
            },
        }

        task_templates = None

        if self.config.name in ("binary_classification", "multiclass_classification"):
            class_names = CLASS_NAMES[self.config.name]
            features["labels"] = datasets.ClassLabel(
                num_classes=len(class_names),
                names=class_names,
            )
            supervised_keys = (("image", "labels"),)
            task_templates = [
                datasets.ImageClassification(
                    image_column="image", label_column="labels"
                )
            ]
        elif self.config.name == "object_detection":
            features["objects"] = {
                "area": datasets.Value("int32"),
                "bbox": datasets.Sequence(feature=datasets.Value("int32")),
                "category": datasets.Value("string"),
                "id": datasets.Value("int32"),
            }
            supervised_keys = (("image", "objects"),)
        elif self.config.name == "instance_segmentation":
            # features["segmentation"] = {
            # }
            supervised_keys = (("image", "objects"),)
        else:
            raise NotImplementedError()

        return datasets.DatasetInfo(
            description=__doc__,
            features=datasets.Features(features),
            homepage=HOMEPAGE,
            license=LICENSE,
            citation=CITATION,
            task_templates=task_templates,
            supervised_keys=supervised_keys,
        )

    def _split_generators(self, dl_manager):
        endometriosis_data_path = Path(
            dl_manager.download_and_extract(URLS["endometriosis_classes"])
        ).joinpath(f"Glenda_v{VERSION}_classes")

        no_pathology_data_path = Path(
            dl_manager.download_and_extract(URLS["no_pathology"])
        ).joinpath("no_pathology", "frames")

        coco_annotation_filepath = Path(endometriosis_data_path).joinpath("coco.json")

        with open(coco_annotation_filepath, "r") as coco_annotation_file:
            coco_annotations = json.load(coco_annotation_file)

        category_id2_name = {
            category["id"]: category["name"]
            for category in coco_annotations["categories"]
        }

        image_filepaths, image_metadata = [], []

        if self.config.name in ("binary_classification", "multiclass_classification"):
            label_name = "labels"
            annotation_list = []
        elif self.config.name == "object_detection":
            label_name = "objects"
            annotation_list = []
        elif self.config.name == "instance_segmentation":
            label_name = "segmentation"
            annotation_list = []
        else:
            raise NotImplementedError(f"Unsupported task: '{self.config.name}'")

        for annotation, metadata in zip(
            coco_annotations["annotations"],
            coco_annotations["images"],
        ):
            image_filepaths.append(
                endometriosis_data_path.joinpath(
                    metadata["coco_url"],
                )
            )
            regex_match = re.search(
                string=metadata["file_name"],
                pattern=ENDOMETRIOSIS_IMAGE_METADATA_REGEX,
            )
            metadata.update(
                {
                    field_name: int(field_value)
                    for field_name, field_value in regex_match.groupdict().items()
                }
            )
            # NOTE: Only defined for `no_pathology` images
            metadata["from_seconds"] = None
            metadata["to_seconds"] = None

            _ = metadata.pop("metadata")
            # This field does not accurately reflect the dataset license,
            # so let's not include it to avoid confusion.
            _ = metadata.pop("license")
            image_metadata.append(metadata)

            if self.config.name == "binary_classification":
                _, positive_label_name = CLASS_NAMES[self.config.name]
                annotation_list.append(positive_label_name)
            elif self.config.name == "multiclass_classification":
                annotation_list.append(category_id2_name[annotation["category_id"]])
            elif self.config.name == "object_detection":
                annotation_list.append({
                    "area": annotation["area"],
                    "bbox": annotation["bbox"],
                    "category": category_id2_name[annotation["category_id"]],
                    "id": annotation["category_id"],
                })
            # elif self.config.name == "instance_segmentation":
            #     annotation_list.append({

            #         })
            #     raise ValueError(annotation["category_id"], annotation["segmentation"])
            #     raise ValueError(annotation)
            #     raise NotImplementedError()
            else:
                raise NotImplementedError()

        max_id = max(metadata["id"] for metadata in image_metadata)
        for image_id, image_filepath in enumerate(
            no_pathology_data_path.glob("*/*.jpg"), start=max_id + 1
        ):
            image_filepaths.append(image_filepath)
            *_, parent_folder, image_filename = image_filepath.parts

            image_filename_with_parent_folder = f"{parent_folder}/{image_filename}"

            metadata = {
                "id": image_id,
                "width": image_metadata[-1]["width"],
                "height": image_metadata[-1]["height"],
                "file_name": image_filepath.name,
                "path": f"frames/{image_filename_with_parent_folder}",
                "fickr_url": None,
                "coco_url": f"frames/{image_filename_with_parent_folder}",
                "date_captured": None,
            }
            match = re.search(
                string=str(image_filename_with_parent_folder),
                pattern=NO_PATHOLOGY_IMAGE_METADATA_REGEX,
            )

            try:
                metadata.update(
                    {
                        field_name: int(field_value)
                        for field_name, field_value in match.groupdict().items()
                    }
                )
            except AttributeError:
                if match is None:
                    print(
                        "Could not get metadata for: ",
                        image_filename_with_parent_folder,
                    )
                    continue

                metadata.update(
                    {
                        "video_id": None,
                        "frame_id": None,
                        "from_seconds": None,
                        "to_seconds": None,
                    }
                )
            # NOTE: Only defined for `endometriosis` images
            metadata["case_id"] = None
            image_metadata.append(metadata)

            if self.config.name in (
                "binary_classification",
                "multiclass_classification",
            ):
                negative_class_label_name, *_ = CLASS_NAMES[self.config.name]
                annotation_list.append(negative_class_label_name)
            elif self.config.name == "object_detection":
                negative_category_id = 0
                negative_class_label_name, *_ = CLASS_NAMES["multiclass_classification"]
                annotation_list.append({
                    "area": None,
                    "bbox": [],
                    "category": negative_class_label_name,
                    "id": negative_category_id,
                })
            elif self.config.name == "instance_segmentation":
                raise NotImplementedError()
            else:
                raise NotImplementedError()


        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={
                    "image_filepaths": image_filepaths,
                    "metadata": image_metadata,
                    label_name: annotation_list,
                },
            )
        ]

    def _generate_examples(self, **kwargs):
        if self.config.name in ("binary_classification", "multiclass_classification"):
            for example_id, (image_filepath, label, image_metadata) in enumerate(
                zip(
                    kwargs["image_filepaths"],
                    kwargs["labels"],
                    kwargs["metadata"]
                )
            ):
                with open(image_filepath, "rb") as image_file:
                    yield example_id, {
                        "image": {"path": str(image_filepath), "bytes": image_file.read()},
                        "labels": label,
                        "metadata": image_metadata,
                    }
        elif self.config.name == "object_detection":
            for example_id, (image_filepath, objects, image_metadata) in enumerate(
                zip(
                    kwargs["image_filepaths"],
                    kwargs["objects"],
                    kwargs["metadata"]
                )
            ):
                with open(image_filepath, "rb") as image_file:
                    yield example_id, {
                        "image": {"path": str(image_filepath), "bytes": image_file.read()},
                        "objects": objects,
                        "metadata": image_metadata,
                    }
        else:
            raise NotImplementedError()