rapadilla commited on
Commit
7d5136d
0 Parent(s):

init commit

Browse files
Files changed (9) hide show
  1. .gitattributes +55 -0
  2. .gitignore +2 -0
  3. README.md +146 -0
  4. coco2017.py +335 -0
  5. cocodataset/__init__.py +2 -0
  6. cocodataset/dataset.py +109 -0
  7. cocodataset/utils.py +190 -0
  8. requirements.txt +58 -0
  9. setup.py +45 -0
.gitattributes ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.lz4 filter=lfs diff=lfs merge=lfs -text
12
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
13
+ *.model filter=lfs diff=lfs merge=lfs -text
14
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
15
+ *.npy filter=lfs diff=lfs merge=lfs -text
16
+ *.npz filter=lfs diff=lfs merge=lfs -text
17
+ *.onnx filter=lfs diff=lfs merge=lfs -text
18
+ *.ot filter=lfs diff=lfs merge=lfs -text
19
+ *.parquet filter=lfs diff=lfs merge=lfs -text
20
+ *.pb filter=lfs diff=lfs merge=lfs -text
21
+ *.pickle filter=lfs diff=lfs merge=lfs -text
22
+ *.pkl filter=lfs diff=lfs merge=lfs -text
23
+ *.pt filter=lfs diff=lfs merge=lfs -text
24
+ *.pth filter=lfs diff=lfs merge=lfs -text
25
+ *.rar filter=lfs diff=lfs merge=lfs -text
26
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
27
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
29
+ *.tar filter=lfs diff=lfs merge=lfs -text
30
+ *.tflite filter=lfs diff=lfs merge=lfs -text
31
+ *.tgz filter=lfs diff=lfs merge=lfs -text
32
+ *.wasm filter=lfs diff=lfs merge=lfs -text
33
+ *.xz filter=lfs diff=lfs merge=lfs -text
34
+ *.zip filter=lfs diff=lfs merge=lfs -text
35
+ *.zst filter=lfs diff=lfs merge=lfs -text
36
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
37
+ # Audio files - uncompressed
38
+ *.pcm filter=lfs diff=lfs merge=lfs -text
39
+ *.sam filter=lfs diff=lfs merge=lfs -text
40
+ *.raw filter=lfs diff=lfs merge=lfs -text
41
+ # Audio files - compressed
42
+ *.aac filter=lfs diff=lfs merge=lfs -text
43
+ *.flac filter=lfs diff=lfs merge=lfs -text
44
+ *.mp3 filter=lfs diff=lfs merge=lfs -text
45
+ *.ogg filter=lfs diff=lfs merge=lfs -text
46
+ *.wav filter=lfs diff=lfs merge=lfs -text
47
+ # Image files - uncompressed
48
+ *.bmp filter=lfs diff=lfs merge=lfs -text
49
+ *.gif filter=lfs diff=lfs merge=lfs -text
50
+ *.png filter=lfs diff=lfs merge=lfs -text
51
+ *.tiff filter=lfs diff=lfs merge=lfs -text
52
+ # Image files - compressed
53
+ *.jpg filter=lfs diff=lfs merge=lfs -text
54
+ *.jpeg filter=lfs diff=lfs merge=lfs -text
55
+ *.webp filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ *.egg-info/
2
+ */__pycache__/
README.md ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: COCO2017
3
+ annotations_creators:
4
+ - expert-generated
5
+ size_categories:
6
+ - 100K<n<1M
7
+ language:
8
+ - en
9
+ task_categories:
10
+ - object-detection
11
+ ---
12
+
13
+ # Dataset Card for Dataset Name
14
+
15
+ This dataset includes **COCO 2017** only.
16
+
17
+ COCO 2014 and 2015 will be included soon.
18
+
19
+ ## Dataset Description
20
+
21
+ - **Homepage:** https://cocodataset.org/
22
+ - **Repository:** https://github.com/cocodataset/cocoapi
23
+ - **Paper:** [Microsoft COCO: Common Objects in Context](https://arxiv.org/abs/1405.0312)
24
+
25
+ ### Dataset Summary
26
+
27
+ COCO (Common Objects in Context) is a large-scale object detection, segmentation, and captioning dataset. It contains over 200,000 labeled images with over 80 category labels. It includes complex, everyday scenes with common objects in their natural context.
28
+
29
+ This dataset covers only the "object detection" part of the COCO dataset. But some features and specifications for the full COCO dataset:
30
+
31
+ - Object segmentation
32
+ - Recognition in context
33
+ - Superpixel stuff segmentation
34
+ - 330K images (>200K labeled)
35
+ - 1.5 million object instances
36
+ - 80 object categories
37
+ - 91 stuff categories
38
+ - 5 captions per image
39
+ - 250,000 people with keypoints
40
+
41
+ ### Data Splits
42
+
43
+ - **Training set ("train")**: 118287 images annotated with 860001 bounding boxes in total.
44
+ - **Validation set ("val")**: 5000 images annotated with 36781 bounding boxes in total.
45
+
46
+ - **92 classes**: "None", "person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "traffic light", "fire hydrant", "street sign", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "hat", "backpack", "umbrella", "shoe", "eye glasses", "handbag", "tie", "suitcase", "frisbee", "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard", "tennis racket", "bottle", "plate", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch", "potted plant", "bed", "mirror", "dining table", "window", "desk", "toilet", "door", "tv", "laptop", "mouse", "remote", "keyboard", "cell phone", "microwave", "oven", "toaster", "sink", "refrigerator", "blender", "book", "clock", "vase", "scissors", "teddy bear", "hair drier", "toothbrush", "hair brush"
47
+
48
+ - **But only 80 classes have with annotations**: "person", "bicycle", "car", "motorcycle", "airplane", "bus", "train", "truck", "boat", "traffic light", "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee", "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard", "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "couch", "potted plant", "bed", "dining table", "toilet", "tv", "laptop", "mouse", "remote", "keyboard", "cell phone", "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddy bear", "hair drier", "toothbrush"
49
+
50
+ ### Boxes format:
51
+
52
+ For the object detection set of COCO dataset, the ground-truth bounding boxes are provided in the following format: `x, y, width, height` in absolute coordinates.
53
+
54
+ ### Curation Rationale
55
+
56
+ COCO dataset was curated with the goal of advancing the state of the art in many tasks, such as object detection, dense pose, keypoints, segmentation and image classification.
57
+
58
+ ### Licensing Information
59
+
60
+ The annotations in this dataset belong to the COCO Consortium and are licensed under a Creative Commons Attribution 4.0 License.
61
+
62
+ Mode details at: https://cocodataset.org/#termsofuse
63
+
64
+ ### Loading dataset
65
+
66
+ You can load COCO 2017 dataset by calling:
67
+
68
+ ```
69
+ from datasets import load_dataset
70
+ # Full dataset
71
+ dataset = load_dataset("rafaelpadilla/coco2017")
72
+ print(dataset)
73
+ >> DatasetDict({
74
+ >> train: Dataset({
75
+ >> features: ['image', 'image_id', 'objects'],
76
+ >> num_rows: 118287
77
+ >> })
78
+ >> val: Dataset({
79
+ >> features: ['image', 'image_id', 'objects'],
80
+ >> num_rows: 5000
81
+ >> })
82
+ >> })
83
+
84
+ # Training set only
85
+ dataset = load_dataset("rafaelpadilla/coco2017", split="train")
86
+
87
+ # Validation set only
88
+ dataset = load_dataset("rafaelpadilla/coco2017", split="val")
89
+ ```
90
+
91
+ ### COCODataset Class
92
+
93
+ We offer the dataset class `COCODataset` that extends VisionDataset to represents images and annotations of COCO. To use it, you need to install coco2017 package. For that, follow the steps below:
94
+
95
+ 1. Create and activate an environment:
96
+ ```
97
+ conda create -n coco2017 python=3.11
98
+ conda activate coco2017
99
+ ```
100
+
101
+ 2. Install cocodataset package:
102
+
103
+ ```
104
+ pip install git+https://huggingface.co/datasets/rafaelpadilla/coco2017@main
105
+ ```
106
+
107
+ or alternatively:
108
+
109
+ ```
110
+ git clone https://huggingface.co/datasets/rafaelpadilla/coco2017
111
+ cd coco2017
112
+ pip install .
113
+ ```
114
+
115
+ 3. Now you can import `COCODataset` class into your Python code by:
116
+ ```
117
+ from cocodataset import COCODataset
118
+ ```
119
+
120
+
121
+ ### Citation Information
122
+
123
+ @inproceedings{lin2014microsoft,
124
+ title={Microsoft coco: Common objects in context},
125
+ author={Lin, Tsung-Yi and Maire, Michael and Belongie, Serge and Hays, James and Perona, Pietro and Ramanan, Deva and Doll{\'a}r, Piotr and Zitnick, C Lawrence},
126
+ booktitle={Computer Vision--ECCV 2014: 13th European Conference, Zurich, Switzerland, September 6-12, 2014, Proceedings, Part V 13},
127
+ pages={740--755},
128
+ year={2014},
129
+ organization={Springer}
130
+ }
131
+
132
+ ### Contributions
133
+
134
+ Tsung-Yi Lin Google Brain
135
+ Genevieve Patterson MSR, Trash TV
136
+ Matteo R. Ronchi Caltech
137
+ Yin Cui Google
138
+ Michael Maire TTI-Chicago
139
+ Serge Belongie Cornell Tech
140
+ Lubomir Bourdev WaveOne, Inc.
141
+ Ross Girshick FAIR
142
+ James Hays Georgia Tech
143
+ Pietro Perona Caltech
144
+ Deva Ramanan CMU
145
+ Larry Zitnick FAIR
146
+ Piotr Dollár FAIR
coco2017.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import json
16
+ from pathlib import Path
17
+ from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
18
+
19
+ import datasets
20
+ from datasets.data_files import DataFilesDict
21
+ from datasets.download.download_manager import ArchiveIterable, DownloadManager
22
+ from datasets.features import Features
23
+ from datasets.info import DatasetInfo
24
+
25
+ # Typing
26
+ _TYPING_BOX = Tuple[float, float, float, float]
27
+
28
+ _CITATION = """\
29
+ @article{DBLP:journals/corr/LinMBHPRDZ14,
30
+ author = {Tsung{-}Yi Lin and
31
+ Michael Maire and
32
+ Serge J. Belongie and
33
+ Lubomir D. Bourdev and
34
+ Ross B. Girshick and
35
+ James Hays and
36
+ Pietro Perona and
37
+ Deva Ramanan and
38
+ Piotr Doll{\'{a}}r and
39
+ C. Lawrence Zitnick},
40
+ title = {Microsoft {COCO:} Common Objects in Context},
41
+ journal = {CoRR},
42
+ volume = {abs/1405.0312},
43
+ year = {2014},
44
+ url = {http://arxiv.org/abs/1405.0312},
45
+ archivePrefix = {arXiv},
46
+ eprint = {1405.0312},
47
+ timestamp = {Mon, 13 Aug 2018 16:48:13 +0200},
48
+ biburl = {https://dblp.org/rec/bib/journals/corr/LinMBHPRDZ14},
49
+ bibsource = {dblp computer science bibliography, https://dblp.org}
50
+ }
51
+ """
52
+
53
+ _DESCRIPTION = """\
54
+ This dataset contains all COCO 2017 images and annotations split in training (118287 images) \
55
+ and validation (5000 images).
56
+ """
57
+
58
+ _HOMEPAGE = "https://cocodataset.org"
59
+
60
+ _URLS = {
61
+ "annotations": "http://images.cocodataset.org/annotations/annotations_trainval2017.zip",
62
+ "train": "http://images.cocodataset.org/zips/train2017.zip",
63
+ "val": "http://images.cocodataset.org/zips/val2017.zip",
64
+ }
65
+
66
+ _SPLITS = ["train", "val"]
67
+
68
+ _PATHS = {
69
+ "annotations": {
70
+ "train": Path("annotations/instances_train2017.json"),
71
+ "val": Path("annotations/instances_val2017.json"),
72
+ },
73
+ "images": {
74
+ "train": Path("train2017"),
75
+ "val": Path("val2017"),
76
+ },
77
+ }
78
+
79
+ _CLASSES = [
80
+ "None",
81
+ "person",
82
+ "bicycle",
83
+ "car",
84
+ "motorcycle",
85
+ "airplane",
86
+ "bus",
87
+ "train",
88
+ "truck",
89
+ "boat",
90
+ "traffic light",
91
+ "fire hydrant",
92
+ "street sign",
93
+ "stop sign",
94
+ "parking meter",
95
+ "bench",
96
+ "bird",
97
+ "cat",
98
+ "dog",
99
+ "horse",
100
+ "sheep",
101
+ "cow",
102
+ "elephant",
103
+ "bear",
104
+ "zebra",
105
+ "giraffe",
106
+ "hat",
107
+ "backpack",
108
+ "umbrella",
109
+ "shoe",
110
+ "eye glasses",
111
+ "handbag",
112
+ "tie",
113
+ "suitcase",
114
+ "frisbee",
115
+ "skis",
116
+ "snowboard",
117
+ "sports ball",
118
+ "kite",
119
+ "baseball bat",
120
+ "baseball glove",
121
+ "skateboard",
122
+ "surfboard",
123
+ "tennis racket",
124
+ "bottle",
125
+ "plate",
126
+ "wine glass",
127
+ "cup",
128
+ "fork",
129
+ "knife",
130
+ "spoon",
131
+ "bowl",
132
+ "banana",
133
+ "apple",
134
+ "sandwich",
135
+ "orange",
136
+ "broccoli",
137
+ "carrot",
138
+ "hot dog",
139
+ "pizza",
140
+ "donut",
141
+ "cake",
142
+ "chair",
143
+ "couch",
144
+ "potted plant",
145
+ "bed",
146
+ "mirror",
147
+ "dining table",
148
+ "window",
149
+ "desk",
150
+ "toilet",
151
+ "door",
152
+ "tv",
153
+ "laptop",
154
+ "mouse",
155
+ "remote",
156
+ "keyboard",
157
+ "cell phone",
158
+ "microwave",
159
+ "oven",
160
+ "toaster",
161
+ "sink",
162
+ "refrigerator",
163
+ "blender",
164
+ "book",
165
+ "clock",
166
+ "vase",
167
+ "scissors",
168
+ "teddy bear",
169
+ "hair drier",
170
+ "toothbrush",
171
+ "hair brush",
172
+ ]
173
+
174
+ def round_box_values(box, decimals=2):
175
+ return [round(val, decimals) for val in box]
176
+
177
+ class COCOHelper:
178
+ """Helper class to load COCO annotations"""
179
+
180
+ def __init__(self, annotation_path: Path, images_dir: Path) -> None:
181
+ with open(annotation_path, "r") as file:
182
+ data = json.load(file)
183
+ self.data = data
184
+
185
+ dict_id2annot: Dict[int, Any] = {}
186
+ for annot in self.annotations:
187
+ dict_id2annot.setdefault(annot["image_id"], []).append(annot)
188
+
189
+ # Sort by id
190
+ dict_id2annot = {
191
+ k: list(sorted(v, key=lambda a: a["id"])) for k, v in dict_id2annot.items()
192
+ }
193
+
194
+ self.dict_path2annot: Dict[str, Any] = {}
195
+ self.dict_path2id: Dict[str, Any] = {}
196
+ for img in self.images:
197
+ path_img = images_dir / str(img["file_name"])
198
+ path_img_str = str(path_img)
199
+ idx = int(img["id"])
200
+ annot = dict_id2annot.get(idx, [])
201
+ self.dict_path2annot[path_img_str] = annot
202
+ self.dict_path2id[path_img_str] = img["id"]
203
+
204
+
205
+ def __len__(self) -> int:
206
+ return len(self.data["images"])
207
+
208
+ @property
209
+ def info(self) -> Dict[str, Union[str, int]]:
210
+ return self.data["info"]
211
+
212
+ @property
213
+ def licenses(self) -> List[Dict[str, Union[str, int]]]:
214
+ return self.data["licenses"]
215
+
216
+ @property
217
+ def images(self) -> List[Dict[str, Union[str, int]]]:
218
+ return self.data["images"]
219
+
220
+ @property
221
+ def annotations(self) -> List[Any]:
222
+ return self.data["annotations"]
223
+
224
+ @property
225
+ def categories(self) -> List[Dict[str, Union[str, int]]]:
226
+ return self.data["categories"]
227
+
228
+ def get_annotations(self, image_path: str) -> List[Any]:
229
+ return self.dict_path2annot.get(image_path, [])
230
+
231
+ def get_image_id(self, image_path: str) -> int:
232
+ return self.dict_path2id.get(image_path, -1)
233
+
234
+
235
+ class COCO2017(datasets.GeneratorBasedBuilder):
236
+ """COCO 2017 dataset."""
237
+
238
+ VERSION = datasets.Version("1.0.1")
239
+
240
+ def _info(self) -> datasets.DatasetInfo:
241
+ """
242
+ Returns the dataset metadata and features.
243
+
244
+ Returns:
245
+ DatasetInfo: Metadata and features of the dataset.
246
+ """
247
+ return datasets.DatasetInfo(
248
+ description=_DESCRIPTION,
249
+ features=datasets.Features(
250
+ {
251
+ "image": datasets.Image(),
252
+ "image_id": datasets.Value("int64"),
253
+ "objects": datasets.Sequence(
254
+ {
255
+ "id": datasets.Value("int64"),
256
+ "area": datasets.Value("float64"),
257
+ "bbox": datasets.Sequence(
258
+ datasets.Value("float32"), length=4
259
+ ),
260
+ "label": datasets.ClassLabel(names=_CLASSES),
261
+ "iscrowd": datasets.Value("bool"),
262
+ }
263
+ ),
264
+ }
265
+ ),
266
+ homepage=_HOMEPAGE,
267
+ citation=_CITATION,
268
+ )
269
+
270
+ def _split_generators(
271
+ self, dl_manager: DownloadManager
272
+ ) -> List[datasets.SplitGenerator]:
273
+ """
274
+ Provides the split information and downloads the data.
275
+
276
+ Args:
277
+ dl_manager (DownloadManager): The DownloadManager to use for downloading and
278
+ extracting data.
279
+
280
+ Returns:
281
+ List[SplitGenerator]: List of SplitGenerator objects representing the data splits.
282
+ """
283
+ archive_annots = dl_manager.download_and_extract(_URLS["annotations"])
284
+
285
+ splits = []
286
+ for split in _SPLITS:
287
+ archive_split = dl_manager.download(_URLS[split])
288
+ annotation_path = Path(archive_annots) / _PATHS["annotations"][split]
289
+ images = dl_manager.iter_archive(archive_split)
290
+ splits.append(
291
+ datasets.SplitGenerator(
292
+ name=datasets.Split(split),
293
+ gen_kwargs={
294
+ "annotation_path": annotation_path,
295
+ "images_dir": _PATHS["images"][split],
296
+ "images": images,
297
+ },
298
+ )
299
+ )
300
+ return splits
301
+
302
+ def _generate_examples(
303
+ self, annotation_path: Path, images_dir: Path, images: ArchiveIterable
304
+ ) -> Iterator:
305
+ """
306
+ Generates examples for the dataset.
307
+
308
+ Args:
309
+ annotation_path (Path): The path to the annotation file.
310
+ images_dir (Path): The path to the directory containing the images.
311
+ images: (ArchiveIterable): An iterable containing the images.
312
+
313
+ Yields:
314
+ Dict[str, Union[str, Image]]: A dictionary containing the generated examples.
315
+ """
316
+ coco_annotation = COCOHelper(annotation_path, images_dir)
317
+
318
+ for image_path, f in images:
319
+ annotations = coco_annotation.get_annotations(image_path)
320
+ ret = {
321
+ "image": {"path": image_path, "bytes": f.read()},
322
+ "image_id": coco_annotation.get_image_id(image_path),
323
+ "objects": [
324
+ {
325
+ "id": annot["id"],
326
+ "area": annot["area"],
327
+ "bbox": round_box_values(annot["bbox"], 2), # [x, y, w, h]
328
+ "label": annot["category_id"],
329
+ "iscrowd": bool(annot["iscrowd"]),
330
+ }
331
+ for annot in annotations
332
+ ],
333
+ }
334
+
335
+ yield image_path, ret
cocodataset/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .dataset import COCODataset
2
+ from .utils import draw_rectangles, val_formatted_anns, create_json_COCO_format
cocodataset/dataset.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This code is an adaptation of https://huggingface.co/spaces/ybelkada/cocoevaluate
2
+
3
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
4
+
5
+ import torch
6
+ from datasets import Dataset
7
+ from PIL import Image
8
+ from torchvision.datasets.vision import VisionDataset
9
+
10
+ _TYPING_BOXES = Tuple[float, float, float, float]
11
+ _TYPING_ANNOTS = Dict[str, Union[int, str, _TYPING_BOXES]]
12
+ _TYPING_LABELS = Dict[str, torch.Tensor]
13
+
14
+ class COCODataset(VisionDataset):
15
+ """
16
+ A class that extends VisionDataset and represents a COCO detection dataset.
17
+ """
18
+
19
+ def __init__(
20
+ self,
21
+ loaded_json: _TYPING_ANNOTS,
22
+ ids_mapping: Dict[int, int],
23
+ dataset: Dataset,
24
+ transforms: Optional[Callable] = None,
25
+ transform: Optional[Callable] = None,
26
+ target_transform: Optional[Callable] = None,
27
+ ) -> None:
28
+ """
29
+ Arguments:
30
+ loaded_json: A dictionary that contains loaded json.
31
+ ids_mapping (Dict[int, int]): A dictionary that maps the index to the id.
32
+ dataset (Dataset): The data which is going to be used.
33
+ transforms (Optional): A function/transform that takes in an PIL image
34
+ and returns a transformed version.
35
+ transform (Optional): A function/transform that takes in an PIL image
36
+ and returns a transformed version. E.g, ``transforms.RandomCrop``.
37
+ target_transform (Optional): A function/transform that takes in the
38
+ target and transforms it.
39
+ """
40
+ root = ""
41
+ super().__init__(root, transforms, transform, target_transform)
42
+
43
+ self.ids_mapping = ids_mapping
44
+ self.dataset = dataset
45
+
46
+ self.images = {img["id"]: img for img in loaded_json["images"]}
47
+ self.ids = sorted(self.images)
48
+ self.annotations = {}
49
+ for annot in loaded_json["annotations"]:
50
+ img_id = annot["image_id"]
51
+ self.annotations.setdefault(img_id, []).append(annot)
52
+
53
+ def _load_image(self, idx: int) -> Image:
54
+ """
55
+ Load an image given its id.
56
+
57
+ Arguments:
58
+ idx: Index of the image to be loaded.
59
+
60
+ Returns:
61
+ PIL Image instance.
62
+ """
63
+ id = self.ids_mapping[idx]
64
+ img = self.dataset[id]["image"].convert("RGB")
65
+ return img
66
+
67
+ def _load_target(self, idx: int) -> List[Any]:
68
+ """
69
+ Load the annotations of an image given its id.
70
+
71
+ Arguments:
72
+ idx: Index of the image to load its annotations.
73
+
74
+ Returns:
75
+ List containing the annotations of the image.
76
+ """
77
+ if idx not in self.annotations:
78
+ return []
79
+ return self.annotations[idx]
80
+
81
+ def __len__(self) -> int:
82
+ """
83
+ Returns the number of elements in the dataset.
84
+
85
+ Returns:
86
+ int: Number of images in the dataset.
87
+ """
88
+ return len(self.ids)
89
+
90
+ def __getitem__(self, index: int) -> Dict[str, Union[torch.Tensor, _TYPING_LABELS]]:
91
+ """
92
+ Given an index, it preprocesses and returns the image and its associated annotations \
93
+ at a that index.
94
+
95
+ Arguments:
96
+ index: Index of the image.
97
+
98
+ Returns:
99
+ Dictionary containing preprocessed image as pixel values and its associated \
100
+ annotations as labels.
101
+ """
102
+ image_id = self.ids[index]
103
+ # PIL Image
104
+ image = self._load_image(image_id)
105
+ # List of annotation dicts 'id', 'category_id', 'iscrowd', 'imageid', 'area', 'bbox'
106
+ annot_dicts = self._load_target(image_id)
107
+
108
+ target = {"image_id": image_id, "annotations": annot_dicts}
109
+ return {"image": image, "target": target}
cocodataset/utils.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image, ImageDraw, ImageFont
2
+ import torch
3
+ from typing import Tuple, List, Dict, Union, Optional
4
+ import torch.utils.data as data
5
+ from tqdm import tqdm
6
+ import copy
7
+
8
+ # Typings
9
+ _TYPING_BOX = Tuple[float, float, float, float]
10
+ _TYPING_IMAGES = List[Dict[str, int]]
11
+ _TYPING_ANNOTATIONS = List[Dict[str, Union[int, _TYPING_BOX]]]
12
+ _TYPING_CATEGORIES = List[Dict[str, Union[int, str]]]
13
+ _TYPING_JSON_COCO = Dict[
14
+ str, Union[_TYPING_IMAGES, _TYPING_ANNOTATIONS, _TYPING_CATEGORIES]
15
+ ]
16
+ _TYPING_BOX = Tuple[float, float, float, float]
17
+ _TYPING_SCORES = List[float]
18
+ _TYPING_LABELS = List[int]
19
+ _TYPING_BOXES = List[_TYPING_BOX]
20
+ _TYPING_PRED_REF = Union[_TYPING_SCORES, _TYPING_LABELS, _TYPING_BOXES]
21
+ _TYPING_PREDICTION = Dict[str, _TYPING_PRED_REF]
22
+
23
+ _acc_box_format = ['xywh', 'xyx2y2']
24
+
25
+ def draw_rectangles(
26
+ image: Image,
27
+ boxes,
28
+ box_format='xyx2y2',
29
+ color_bbx=(255, 0, 0),
30
+ color_txt=(255, 255, 255),
31
+ thickness=1,
32
+ labels=None,
33
+ confidences=None,
34
+ draw_confidence=True,
35
+ ):
36
+ """
37
+ Draw rectangles around objects in an image.
38
+
39
+ Args:
40
+ image (Image): Image object to draw on.
41
+ boxes (List[torch.Tensor]): List of bounding boxes in (xywh or xyx2y2) format.
42
+ color_bbx (Tuple[int, int, int]): RGB color tuple for bounding box outlines. Default \
43
+ is (255, 0, 0) (red).
44
+ color_txt (Tuple[int, int, int]): RGB color tuple for text. Default is \
45
+ (255, 255, 255) (white).
46
+ thickness (int): Thickness of the bounding box outline. Default is 1.
47
+ labels (List[str]): List of labels for each object. Default is None.
48
+ confidences (List[float]): List of confidences for each object. Default is None.
49
+ draw_confidence (bool): Whether to draw confidence values. Default is True.
50
+
51
+ Returns:
52
+ Image: Image with rectangles drawn around objects.
53
+ """
54
+ # boxes: (x,y,x2,y2)
55
+ # color: (RGB)
56
+ # https://pillow.readthedocs.io/en/stable/handbook/text-anchors.html
57
+ # https://pillow.readthedocs.io/en/stable/reference/ImageFont.html
58
+
59
+ assert box_format in _acc_box_format, "box_format must be {}".format(_acc_box_format)
60
+ offset = 0.05
61
+ font = ImageFont.load_default()
62
+
63
+ # Make clones to avoid overwriting the original data
64
+ if boxes is not None:
65
+ if isinstance(boxes, torch.Tensor):
66
+ _boxes = copy.deepcopy(boxes).tolist()
67
+ elif isinstance(boxes, list):
68
+ _boxes = copy.deepcopy(boxes)
69
+ else:
70
+ _boxes = None
71
+
72
+ if confidences is not None:
73
+ if isinstance(confidences, torch.Tensor):
74
+ _confidences = copy.deepcopy(confidences).tolist()
75
+ elif isinstance(confidences, list):
76
+ _confidences = copy.deepcopy(confidences)
77
+ else:
78
+ _confidences = None
79
+ draw_confidence = False
80
+ _confidences = ["" for i in _boxes]
81
+
82
+ ret_image = image.copy()
83
+ img_draw = ImageDraw.Draw(ret_image)
84
+ for box, label, confidence in zip(_boxes, labels, _confidences):
85
+ if box_format == "xywh":
86
+ # convert to xyx2y2
87
+ box[2] = box[0]+box[2]
88
+ box[3] = box[1]+box[3]
89
+ text = f"{label}"
90
+ if draw_confidence:
91
+ text += f" ({100*confidence:.2f}%)"
92
+ text = " " + text + " "
93
+ _, _, txt_w, txt_h = font.getbbox(text)
94
+ offset_y = txt_h * offset
95
+ x, y, _, _ = box
96
+ box_txt = (x, y - txt_h - (2 * offset_y), x + txt_w, y)
97
+ pos_text = (x, y - txt_h - (offset_y))
98
+
99
+ # Draws rectangle around object
100
+ img_draw.rectangle(box, outline=color_bbx, width=thickness)
101
+ # Draws filled rectangle for text
102
+ img_draw.rectangle(box_txt, fill=color_bbx, width=thickness)
103
+ # Draws text
104
+ img_draw.text(pos_text, text, fill=color_txt, anchor="ma", font=font)
105
+
106
+ return ret_image
107
+
108
+ def val_formatted_anns(
109
+ image_id: int, objects: _TYPING_PREDICTION, feat_name: str = "category"
110
+ ) -> List[_TYPING_PREDICTION]:
111
+ """
112
+ This function formats annotations the same way they are for training, without the need \
113
+ for data augmentation.
114
+
115
+ Args:
116
+ image_id (int): The id of the image.
117
+ objects (_TYPING_PREDICTION): The dictionary containing object annotations.
118
+ feat_name (str): The name of the feature containing the category id.
119
+ Returns:
120
+ List[Dict[str, Union[int, _TYPING_BOX]]]: List of dictionaries with formatted annotations.
121
+ """
122
+ annotations = []
123
+ for i in range(0, len(objects["id"])):
124
+ new_ann = {
125
+ "id": objects["id"][i],
126
+ "category_id": objects[feat_name][i],
127
+ "iscrowd": objects["iscrowd"][i],
128
+ "image_id": image_id,
129
+ "area": objects["area"][i],
130
+ "bbox": objects["bbox"][i],
131
+ }
132
+ annotations.append(new_ann)
133
+
134
+ return annotations
135
+
136
+ def create_json_COCO_format(
137
+ dataset: data.Dataset, round_approx: Optional[int] = None
138
+ ) -> Tuple[Dict[int, int], _TYPING_JSON_COCO]:
139
+ """
140
+ Function to create a JSON in COCO format.
141
+
142
+ Args:
143
+ dataset (Dataset): The dataset to be converted to COCO format.
144
+ round_approx (Optional[int]): The number of decimal places to round the boxes.
145
+
146
+ Returns:
147
+ A tuple of a dictionary mapping image_id to index in dataset and a dictionary \
148
+ in COCO format.
149
+ """
150
+ feature = dataset.features["objects"].feature
151
+
152
+ # Look for the feature name
153
+ for feat_name in ["category", "label"]:
154
+ if feat_name in feature:
155
+ break
156
+ categories = feature[feat_name].names
157
+
158
+ id2label = {index: x for index, x in enumerate(categories, start=0)}
159
+ categories_json = [
160
+ {"supercategory": "none", "id": id, "name": id2label[id]} for id in id2label
161
+ ]
162
+
163
+ output_json = {}
164
+ output_json["images"] = []
165
+ output_json["annotations"] = []
166
+
167
+ # Collecting outputs from dataset
168
+ ids_mapping = {}
169
+ pbar = tqdm(dataset, desc="Collecting ground-truth annotations from dataset")
170
+ for idx, example in enumerate(pbar):
171
+
172
+ ids_mapping[example["image_id"]] = idx
173
+
174
+ ann = val_formatted_anns(example["image_id"], example["objects"], feat_name)
175
+ output_json["images"].append(
176
+ {
177
+ "id": example["image_id"],
178
+ "width": example["image"].width,
179
+ "height": example["image"].height,
180
+ }
181
+ )
182
+ if round_approx is not None:
183
+ for annotation in ann:
184
+ annotation["bbox"] = [round(val, round_approx) for val in annotation["bbox"]]
185
+
186
+ output_json["annotations"].extend(ann)
187
+
188
+ output_json["categories"] = categories_json
189
+
190
+ return ids_mapping, output_json
requirements.txt ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ aiohttp==3.8.4
2
+ aiosignal==1.3.1
3
+ async-timeout==4.0.2
4
+ attrs==23.1.0
5
+ certifi==2023.5.7
6
+ charset-normalizer==3.2.0
7
+ cmake==3.26.4
8
+ contourpy==1.1.0
9
+ Cython==3.0.0
10
+ datasets==2.13.1
11
+ dill==0.3.6
12
+ filelock==3.12.2
13
+ fonttools==4.40.0
14
+ frozenlist==1.4.0
15
+ fsspec==2023.6.0
16
+ huggingface-hub==0.16.4
17
+ idna==3.4
18
+ Jinja2==3.1.2
19
+ kiwisolver==1.4.4
20
+ lit==16.0.6
21
+ MarkupSafe==2.1.3
22
+ matplotlib==3.7.2
23
+ mpmath==1.3.0
24
+ multidict==6.0.4
25
+ multiprocess==0.70.14
26
+ networkx==3.1
27
+ numpy==1.25.1
28
+ nvidia-cublas-cu11==11.10.3.66
29
+ nvidia-cuda-cupti-cu11==11.7.101
30
+ nvidia-cuda-nvrtc-cu11==11.7.99
31
+ nvidia-cuda-runtime-cu11==11.7.99
32
+ nvidia-cudnn-cu11==8.5.0.96
33
+ nvidia-cufft-cu11==10.9.0.58
34
+ nvidia-curand-cu11==10.2.10.91
35
+ nvidia-cusolver-cu11==11.4.0.1
36
+ nvidia-cusparse-cu11==11.7.4.91
37
+ nvidia-nccl-cu11==2.14.3
38
+ nvidia-nvtx-cu11==11.7.91
39
+ packaging==23.1
40
+ pandas==2.0.3
41
+ Pillow==10.0.0
42
+ pyarrow==12.0.1
43
+ python-dateutil==2.8.2
44
+ pytz==2023.3
45
+ PyYAML==6.0.1
46
+ requests==2.31.0
47
+ responses==0.18.0
48
+ six==1.16.0
49
+ sympy==1.12
50
+ torch==2.0.1
51
+ torchvision==0.15.2
52
+ tqdm==4.65.0
53
+ triton==2.0.0
54
+ typing_extensions==4.7.1
55
+ tzdata==2023.3
56
+ urllib3==2.0.3
57
+ xxhash==3.2.0
58
+ yarl==1.9.2
setup.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __version__ = "0.0.2"
2
+
3
+ import subprocess
4
+
5
+ from setuptools import find_packages, setup
6
+ from setuptools.command.develop import develop
7
+ from setuptools.command.egg_info import egg_info
8
+ from setuptools.command.install import install
9
+
10
+ def custom_command():
11
+ subprocess.call(["pip", "install", "numpy", "cython"])
12
+ subprocess.call(["pip", "install", "-r", "requirements.txt", "--user"])
13
+
14
+
15
+ class CustomInstallCommand(install):
16
+ def run(self):
17
+ install.run(self)
18
+ custom_command()
19
+
20
+
21
+ class CustomDevelopCommand(develop):
22
+ def run(self):
23
+ develop.run(self)
24
+ custom_command()
25
+
26
+
27
+ class CustomEggInfoCommand(egg_info):
28
+ def run(self):
29
+ egg_info.run(self)
30
+ custom_command()
31
+
32
+
33
+ setup(
34
+ name="cocodataset",
35
+ description="COCO 2017 Dataset",
36
+ version=__version__,
37
+ zip_safe=True,
38
+ packages=find_packages(),
39
+ include_package_data=True,
40
+ cmdclass={
41
+ "install": CustomInstallCommand,
42
+ "develop": CustomDevelopCommand,
43
+ "egg_info": CustomEggInfoCommand,
44
+ },
45
+ )