File size: 5,696 Bytes
a3b3c95
 
 
 
 
 
 
 
 
 
 
 
 
8e9394a
a3b3c95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b628395
a3b3c95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29d686d
a3b3c95
 
 
 
e7d9d57
 
 
 
 
 
a3b3c95
e7d9d57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a3b3c95
 
 
 
 
 
 
 
 
 
 
 
c917614
b628395
a3b3c95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e9394a
a3b3c95
 
 
 
 
 
 
 
 
 
 
 
 
05c77b2
 
 
 
 
a3b3c95
 
 
 
05c77b2
 
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
# Copyright 2022 Daniel van Strien.
#
# 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.
"""Card Display Detection"""

import collections
import json
import os
from typing import Any, Dict, List
import pandas as pd
import datasets

_CITATION = """Connor Hoehn"""

_DESCRIPTION = "This dataset comprises of card display images from the public domain"

_HOMEPAGE = "https://www.connorhoehn.com"

_LICENSE = "Public Domain Mark 1.0"

_DATASET_URL = "https://www.connorhoehn.com/object_detection_dataset_v2.zip"

_CATEGORIES = ["boxed","grid","spread","stack"]

class CardDisplayDetectorConfig(datasets.BuilderConfig):
    """BuilderConfig for card display dataset."""

    def __init__(self, name, **kwargs):
        
        super(CardDisplayDetectorConfig, self).__init__(
            version=datasets.Version("1.0.0"),
            name=name,
            description="Card Display Detector",
            **kwargs,
        )


class CardDisplayDetector(datasets.GeneratorBasedBuilder):
    """Card Display dataset."""

    BUILDER_CONFIGS = [
        CardDisplayDetectorConfig("display-detection"),
    ]

    def _info(self):
    
        features = datasets.Features(
            {
                "image_id": datasets.Value("int64"),
                "image": datasets.Image(),
                "width": datasets.Value("int32"),
                "height": datasets.Value("int32"),
            }
        )
        object_dict = {
            "category_id": datasets.ClassLabel(names=_CATEGORIES),
            "image_id": datasets.Value("string"),
            "id": datasets.Value("int64"),
            "area": datasets.Value("int64"),
            "bbox": datasets.Sequence(datasets.Value("float32"), length=4),
            "iscrowd": datasets.Value("bool"),
        }
        features["objects"] = [object_dict]

        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=features,
            homepage=_HOMEPAGE,
            license=_LICENSE,
            citation=_CITATION,
        )



    def _split_generators(self, dl_manager):
        
        dataset_zip = dl_manager.download_and_extract(_DATASET_URL)
        
        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                # COCO -> x.json, images/
                gen_kwargs={
                    "annotations_file": os.path.join(dataset_zip, "result.json"),
                    # Annotator indicated there was a folder named 1 that doesn't exist
                    "image_dir": os.path.join(dataset_zip),
                },
            )
        ]

    # Return dictionary of unique image_ids that have multiple nested annotations
    def _get_image_id_to_annotations_mapping(self, annotations: List[Dict]) -> Dict[int, List[Dict[Any, Any]]]:
        """
        A helper function to build a mapping from image ids to annotations.
        """
        image_id_to_annotations = collections.defaultdict(list)
        
        for annotation in annotations:
            
            image_id_to_annotations[annotation["image_id"]].append(annotation)
            
        return image_id_to_annotations
    

    def _generate_examples(self, annotations_file, image_dir):
        
        def _image_info_to_example(image_info, image_dir):
            
            # from the annotation file
            image = image_info["file_name"]
            
            return {
                "image_id": image_info["id"],
                "image": os.path.join(image_dir, image),
                "width": image_info["width"],
                "height": image_info["height"],
            }
        
        with open(annotations_file, encoding="utf8") as annotation_json:
            
            annotation_data = json.load(annotation_json)
            
            images = annotation_data["images"]
            
            annotations = annotation_data["annotations"]
            
            # dictionary of image_ids with all related annotations (bbox)
            image_id_to_annotations = self._get_image_id_to_annotations_mapping(
                annotations
            )

            if self.config.name == "display-detection":
                
                # yield image_id, features
                for image_id, image_info in enumerate(images):
                    #image_info -> (w,h,id,filename)
                    
                    image_details = _image_info_to_example(image_info, image_dir)
                    
                    # Get images unit id
                    annotations = image_id_to_annotations[image_info["id"]]
                    
                    objects = []
                    
                    # Add the annotation information to the image details
                    for annotation in annotations:
                        
                        del annotation['segmentation']
                        del annotation['ignore']
                        
                        objects.append(annotation)
                    
                    # nested dictionary
                    image_details["objects"] = objects
                                        
                    yield (image_id, image_details)