SaulLu commited on
Commit
79fa3f3
1 Parent(s): 6aa1df0

add annotations

Browse files
Files changed (1) hide show
  1. Caltech-101.py +80 -30
Caltech-101.py CHANGED
@@ -14,10 +14,13 @@
14
  """Caltech 101 loading script"""
15
 
16
 
 
 
17
  from pathlib import Path
18
 
19
  import datasets
20
  import numpy as np
 
21
  from datasets.tasks import ImageClassification
22
 
23
  _CITATION = """\
@@ -147,6 +150,15 @@ _NAMES = [
147
  "wrench",
148
  "yin_yang",
149
  ]
 
 
 
 
 
 
 
 
 
150
 
151
  _TRAIN_POINTS_PER_CLASS = 30
152
 
@@ -173,36 +185,56 @@ class Caltech101(datasets.GeneratorBasedBuilder):
173
  ]
174
 
175
  def _info(self):
176
- return datasets.DatasetInfo(
177
- description=_DESCRIPTION,
178
- features=datasets.Features(
179
  {
180
  "image": datasets.Image(),
181
  "label": datasets.features.ClassLabel(names=_NAMES),
 
 
 
 
 
 
 
 
182
  }
183
- ),
184
- supervised_keys=("image", "label"),
 
 
 
 
 
 
 
 
 
185
  homepage=_HOMEPAGE,
186
  license=_LICENSE,
187
  citation=_CITATION,
188
- task_templates=ImageClassification(
189
- image_column="image", label_column="label"
190
- ),
191
  )
192
 
193
  def _split_generators(self, dl_manager):
194
  data_root_dir = dl_manager.download_and_extract(_DATA_URL)
195
- compress_folder_path = [
196
  file
197
  for file in dl_manager.iter_files(data_root_dir)
198
  if Path(file).name == "101_ObjectCategories.tar.gz"
199
  ][0]
200
- data_dir = dl_manager.extract(compress_folder_path)
 
 
 
 
 
 
201
  return [
202
  datasets.SplitGenerator(
203
  name=datasets.Split.TRAIN,
204
  gen_kwargs={
205
- "filepath": data_dir,
 
206
  "split": "train",
207
  "config_name": self.config.name,
208
  },
@@ -210,58 +242,76 @@ class Caltech101(datasets.GeneratorBasedBuilder):
210
  datasets.SplitGenerator(
211
  name=datasets.Split.TEST,
212
  gen_kwargs={
213
- "filepath": data_dir,
 
214
  "split": "test",
215
  "config_name": self.config.name,
216
  },
217
  ),
218
  ]
219
 
220
- def _generate_examples(self, filepath, split, config_name):
221
  # Same stratagy as the one proposed in TF datasets: 30 random examples from each class are added to the train
222
  # split, and the remainder are added to the test split.
223
  # Source: https://github.com/tensorflow/datasets/blob/1106d587f97c4fca68c5b593dc7dc48c790ffa8c/tensorflow_datasets/image_classification/caltech.py#L88-L140
224
 
225
  is_train_split = split == "train"
226
- data_dir = Path(filepath) / "101_ObjectCategories"
227
  # Sets random seed so the random partitioning of files is the same when
228
  # called for the train and test splits.
229
  numpy_original_state = np.random.get_state()
230
  np.random.seed(1234)
231
 
232
- for class_dir in data_dir.iterdir():
233
- # print(class_dir)
234
- fnames = [
235
- image_path
236
  for image_path in class_dir.iterdir()
237
  if image_path.name.endswith(".jpg")
238
  ]
239
  # _TRAIN_POINTS_PER_CLASS datapoints are sampled for the train split,
240
  # the others constitute the test split.
241
- if _TRAIN_POINTS_PER_CLASS > len(fnames):
242
  raise ValueError(
243
- "Fewer than {} ({}) points in class {}".format(
244
- _TRAIN_POINTS_PER_CLASS, len(fnames), class_dir.name
245
- )
246
  )
247
- train_fnames = np.random.choice(
248
- fnames, _TRAIN_POINTS_PER_CLASS, replace=False
 
249
  )
250
- test_fnames = set(fnames).difference(train_fnames)
251
- fnames_to_emit = train_fnames if is_train_split else test_fnames
 
252
 
253
  if (
254
- class_dir.name == "BACKGROUND_Google"
255
  and config_name == self._BUILDER_CONFIG_WITHOUT_BACKGROUND.name
256
  ):
257
  print("skip BACKGROUND_Google")
258
  continue
259
 
260
- for image_file in fnames_to_emit:
261
  record = {
262
- "image": str(image_file),
263
  "label": class_dir.name.lower(),
264
  }
265
- yield "%s/%s" % (class_dir.name.lower(), image_file), record
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
266
  # Resets the seeds to their previous states.
267
  np.random.set_state(numpy_original_state)
 
14
  """Caltech 101 loading script"""
15
 
16
 
17
+ from __future__ import annotations
18
+
19
  from pathlib import Path
20
 
21
  import datasets
22
  import numpy as np
23
+ import scipy.io
24
  from datasets.tasks import ImageClassification
25
 
26
  _CITATION = """\
 
150
  "wrench",
151
  "yin_yang",
152
  ]
153
+ # For some reason, the category names in "101_ObjectCategories" and
154
+ # "Annotations" do not always match. This is a manual map between the
155
+ # two. Defaults to using same name, since most names are fine.
156
+ _ANNOTATION_NAMES_MAP = {
157
+ "Faces": "Faces_2",
158
+ "Faces_easy": "Faces_3",
159
+ "Motorbikes": "Motorbikes_16",
160
+ "airplanes": "Airplanes_Side_2",
161
+ }
162
 
163
  _TRAIN_POINTS_PER_CLASS = 30
164
 
 
185
  ]
186
 
187
  def _info(self):
188
+ if self.config.name == self._BUILDER_CONFIG_WITHOUT_BACKGROUND.name:
189
+ features = datasets.Features(
 
190
  {
191
  "image": datasets.Image(),
192
  "label": datasets.features.ClassLabel(names=_NAMES),
193
+ "annotation": {
194
+ "obj_contour": datasets.features.Array2D(
195
+ shape=(2, None), dtype="float64"
196
+ ),
197
+ "box_coord": datasets.features.Array2D(
198
+ shape=(1, 4), dtype="int64"
199
+ ),
200
+ },
201
  }
202
+ )
203
+ else:
204
+ features = datasets.Features(
205
+ {
206
+ "image": datasets.Image(),
207
+ "label": datasets.features.ClassLabel(names=_NAMES),
208
+ }
209
+ )
210
+ return datasets.DatasetInfo(
211
+ description=_DESCRIPTION,
212
+ features=features,
213
  homepage=_HOMEPAGE,
214
  license=_LICENSE,
215
  citation=_CITATION,
 
 
 
216
  )
217
 
218
  def _split_generators(self, dl_manager):
219
  data_root_dir = dl_manager.download_and_extract(_DATA_URL)
220
+ img_folder_compress_path = [
221
  file
222
  for file in dl_manager.iter_files(data_root_dir)
223
  if Path(file).name == "101_ObjectCategories.tar.gz"
224
  ][0]
225
+ annotations_folder_compress_path = [
226
+ file
227
+ for file in dl_manager.iter_files(data_root_dir)
228
+ if Path(file).name == "Annotations.tar"
229
+ ][0]
230
+ img_dir = dl_manager.extract(img_folder_compress_path)
231
+ annotation_dir = dl_manager.extract(annotations_folder_compress_path)
232
  return [
233
  datasets.SplitGenerator(
234
  name=datasets.Split.TRAIN,
235
  gen_kwargs={
236
+ "img_dir": Path(img_dir) / "101_ObjectCategories",
237
+ "annotation_dir": Path(annotation_dir) / "Annotations",
238
  "split": "train",
239
  "config_name": self.config.name,
240
  },
 
242
  datasets.SplitGenerator(
243
  name=datasets.Split.TEST,
244
  gen_kwargs={
245
+ "img_dir": Path(img_dir) / "101_ObjectCategories",
246
+ "annotation_dir": Path(annotation_dir) / "Annotations",
247
  "split": "test",
248
  "config_name": self.config.name,
249
  },
250
  ),
251
  ]
252
 
253
+ def _generate_examples(self, img_dir, annotation_dir, split, config_name):
254
  # Same stratagy as the one proposed in TF datasets: 30 random examples from each class are added to the train
255
  # split, and the remainder are added to the test split.
256
  # Source: https://github.com/tensorflow/datasets/blob/1106d587f97c4fca68c5b593dc7dc48c790ffa8c/tensorflow_datasets/image_classification/caltech.py#L88-L140
257
 
258
  is_train_split = split == "train"
259
+
260
  # Sets random seed so the random partitioning of files is the same when
261
  # called for the train and test splits.
262
  numpy_original_state = np.random.get_state()
263
  np.random.seed(1234)
264
 
265
+ for class_dir in img_dir.iterdir():
266
+ class_name = class_dir.name
267
+ index_codes = [
268
+ image_path.name.split("_")[1][: -len(".jpg")]
269
  for image_path in class_dir.iterdir()
270
  if image_path.name.endswith(".jpg")
271
  ]
272
  # _TRAIN_POINTS_PER_CLASS datapoints are sampled for the train split,
273
  # the others constitute the test split.
274
+ if _TRAIN_POINTS_PER_CLASS > len(index_codes):
275
  raise ValueError(
276
+ f"Fewer than {_TRAIN_POINTS_PER_CLASS} ({len(index_codes)}) points in class {class_dir.name}"
 
 
277
  )
278
+
279
+ train_indices = np.random.choice(
280
+ index_codes, _TRAIN_POINTS_PER_CLASS, replace=False
281
  )
282
+ test_indices = set(index_codes).difference(train_indices)
283
+
284
+ indices_to_emit = train_indices if is_train_split else test_indices
285
 
286
  if (
287
+ class_name == "BACKGROUND_Google"
288
  and config_name == self._BUILDER_CONFIG_WITHOUT_BACKGROUND.name
289
  ):
290
  print("skip BACKGROUND_Google")
291
  continue
292
 
293
+ for indice in indices_to_emit:
294
  record = {
295
+ "image": str(class_dir / f"image_{indice}.jpg"),
296
  "label": class_dir.name.lower(),
297
  }
298
+ if config_name == self._BUILDER_CONFIG_WITHOUT_BACKGROUND.name:
299
+ if class_name in _ANNOTATION_NAMES_MAP:
300
+ annotations_class_name = _ANNOTATION_NAMES_MAP[class_name]
301
+ else:
302
+ annotations_class_name = class_name
303
+ data = scipy.io.loadmat(
304
+ str(
305
+ annotation_dir
306
+ / annotations_class_name
307
+ / f"annotation_{indice}.mat"
308
+ )
309
+ )
310
+ # raise ValueError(data["obj_contour"].dtype, data["box_coord"])
311
+ record["annotation"] = {
312
+ "obj_contour": data["obj_contour"],
313
+ "box_coord": data["box_coord"],
314
+ }
315
+ yield f"{class_dir.name.lower()}/{f'image_{indice}.jpg'}", record
316
  # Resets the seeds to their previous states.
317
  np.random.set_state(numpy_original_state)