Yorai commited on
Commit
2b83a94
1 Parent(s): 724281f

added loading script

Browse files
Files changed (2) hide show
  1. README.md +42 -0
  2. detect-waste_loading_script.py +329 -0
README.md ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ dataset_info:
3
+ config_name: taco-multi
4
+ features:
5
+ - name: image_id
6
+ dtype: int64
7
+ - name: image
8
+ dtype: image
9
+ - name: width
10
+ dtype: int32
11
+ - name: height
12
+ dtype: int32
13
+ - name: objects
14
+ sequence:
15
+ - name: id
16
+ dtype: int64
17
+ - name: area
18
+ dtype: int64
19
+ - name: bbox
20
+ sequence: float32
21
+ length: 4
22
+ - name: category
23
+ dtype:
24
+ class_label:
25
+ names:
26
+ '0': metals_and_plastic
27
+ '1': other
28
+ '2': non_recyclable
29
+ '3': glass
30
+ '4': paper
31
+ '5': bio
32
+ '6': unknown
33
+ splits:
34
+ - name: train
35
+ num_bytes: 1006510
36
+ num_examples: 3647
37
+ - name: test
38
+ num_bytes: 248312
39
+ num_examples: 915
40
+ download_size: 10265127938
41
+ dataset_size: 1254822
42
+ ---
detect-waste_loading_script.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ AI4Good project for detecting waste in environment. www.detectwaste.ml.
3
+
4
+ Our latest results were published in Waste Management journal in article titled Deep learning-based waste detection in natural and urban environments.
5
+
6
+ You can find more technical details in our technical report Waste detection in Pomerania: non-profit project for detecting waste in environment.
7
+
8
+ Did you know that we produce 300 million tons of plastic every year? And only the part of it is properly recycled.
9
+
10
+ The idea of detect waste project is to use Artificial Intelligence to detect plastic waste in the environment. Our solution is applicable for video and photography. Our goal is to use AI for Good.
11
+
12
+ In Detect Waste in Pomerania project we used 9 publicity available datasets, and additional data collected using Google Images Download.
13
+
14
+ For more details, about the data we used, check our jupyter notebooks with data exploratory analysis.
15
+ """
16
+
17
+ from pathlib import Path
18
+ import csv
19
+ import datasets
20
+ import itertools
21
+ import json
22
+ import os
23
+ import PIL.Image
24
+
25
+ # BibTeX citation
26
+ _CITATION = """\
27
+ @article{MAJCHROWSKA2022274,
28
+ title = {Deep learning-based waste detection in natural and urban environments},
29
+ journal = {Waste Management},
30
+ volume = {138},
31
+ pages = {274-284},
32
+ year = {2022},
33
+ issn = {0956-053X},
34
+ doi = {https://doi.org/10.1016/j.wasman.2021.12.001},
35
+ url = {https://www.sciencedirect.com/science/article/pii/S0956053X21006474},
36
+ author = {Sylwia Majchrowska and Agnieszka Mikołajczyk and Maria Ferlin and Zuzanna Klawikowska and Marta A. Plantykow and Arkadiusz Kwasigroch and Karol Majek},
37
+ keywords = {Object detection, Semi-supervised learning, Waste classification benchmarks, Waste detection benchmarks, Waste localization, Waste recognition},
38
+ abstract = {Waste pollution is one of the most significant environmental issues in the modern world. The importance of recycling is well known, both for economic and ecological reasons, and the industry demands high efficiency. Current studies towards automatic waste detection are hardly comparable due to the lack of benchmarks and widely accepted standards regarding the used metrics and data. Those problems are addressed in this article by providing a critical analysis of over ten existing waste datasets and a brief but constructive review of the existing Deep Learning-based waste detection approaches. This article collects and summarizes previous studies and provides the results of authors’ experiments on the presented datasets, all intended to create a first replicable baseline for litter detection. Moreover, new benchmark datasets detect-waste and classify-waste are proposed that are merged collections from the above-mentioned open-source datasets with unified annotations covering all possible waste categories: bio, glass, metal and plastic, non-recyclable, other, paper, and unknown. Finally, a two-stage detector for litter localization and classification is presented. EfficientDet-D2 is used to localize litter, and EfficientNet-B2 to classify the detected waste into seven categories. The classifier is trained in a semi-supervised fashion making the use of unlabeled images. The proposed approach achieves up to 70% of average precision in waste detection and around 75% of classification accuracy on the test dataset. The code and annotations used in the studies are publicly available online11https://github.com/wimlds-trojmiasto/detect-waste..}
39
+ }
40
+ """
41
+
42
+ _DESCRIPTION = """\
43
+ AI4Good project for detecting waste in environment. www.detectwaste.ml.
44
+
45
+ Our latest results were published in Waste Management journal in article titled Deep learning-based waste detection in natural and urban environments.
46
+
47
+ You can find more technical details in our technical report Waste detection in Pomerania: non-profit project for detecting waste in environment.
48
+
49
+ Did you know that we produce 300 million tons of plastic every year? And only the part of it is properly recycled.
50
+
51
+ The idea of detect waste project is to use Artificial Intelligence to detect plastic waste in the environment. Our solution is applicable for video and photography. Our goal is to use AI for Good.
52
+ """
53
+
54
+ _HOMEPAGE = "https://github.com/wimlds-trojmiasto/detect-waste"
55
+
56
+ _LICENSE = (
57
+ "https://raw.githubusercontent.com/wimlds-trojmiasto/detect-waste/main/LICENSE"
58
+ )
59
+
60
+ _URLS = {
61
+ "annotations_train": "https://raw.githubusercontent.com/wimlds-trojmiasto/detect-waste/main/annotations/annotations_train.json",
62
+ "annotations_test": "https://raw.githubusercontent.com/wimlds-trojmiasto/detect-waste/main/annotations/annotations_test.json",
63
+ "taco_all_image_urls_csv": "https://raw.githubusercontent.com/pedropro/TACO/master/data/all_image_urls.csv",
64
+ }
65
+
66
+ _CATEGORIES = [
67
+ "metals_and_plastic",
68
+ "other",
69
+ "non_recyclable",
70
+ "glass",
71
+ "paper",
72
+ "bio",
73
+ "unknown",
74
+ ]
75
+
76
+
77
+ def exif_transpose(image, *, in_place=False, remove_exif_metadata_only=False):
78
+ from PIL import ExifTags, Image
79
+
80
+ """
81
+ https://pillow.readthedocs.io/en/stable/_modules/PIL/ImageOps.html#exif_transpose
82
+ If an image has an EXIF Orientation tag, other than 1, transpose the image
83
+ accordingly, and remove the orientation data.
84
+
85
+ :param image: The image to transpose.
86
+ :param in_place: Boolean. Keyword-only argument.
87
+ If ``True``, the original image is modified in-place, and ``None`` is returned.
88
+ If ``False`` (default), a new :py:class:`~PIL.Image.Image` object is returned
89
+ with the transposition applied. If there is no transposition, a copy of the
90
+ image will be returned.
91
+ """
92
+ image_exif = image.getexif()
93
+ orientation = image_exif.get(ExifTags.Base.Orientation)
94
+
95
+ method = {
96
+ 2: Image.Transpose.FLIP_LEFT_RIGHT,
97
+ 3: Image.Transpose.ROTATE_180,
98
+ 4: Image.Transpose.FLIP_TOP_BOTTOM,
99
+ 5: Image.Transpose.TRANSPOSE,
100
+ 6: Image.Transpose.ROTATE_270,
101
+ 7: Image.Transpose.TRANSVERSE,
102
+ 8: Image.Transpose.ROTATE_90,
103
+ }.get(orientation)
104
+ if method is not None:
105
+ transposed_image = image
106
+ if not remove_exif_metadata_only:
107
+ transposed_image = image.transpose(method)
108
+ if in_place:
109
+ image.im = transposed_image.im
110
+ image.pyaccess = None
111
+ image._size = transposed_image._size
112
+ exif_image = image if in_place else transposed_image
113
+
114
+ exif = exif_image.getexif()
115
+ if ExifTags.Base.Orientation in exif:
116
+ del exif[ExifTags.Base.Orientation]
117
+ if "exif" in exif_image.info:
118
+ exif_image.info["exif"] = exif.tobytes()
119
+ elif "Raw profile type exif" in exif_image.info:
120
+ exif_image.info["Raw profile type exif"] = exif.tobytes().hex()
121
+ elif "XML:com.adobe.xmp" in exif_image.info:
122
+ for pattern in (
123
+ r'tiff:Orientation="([0-9])"',
124
+ r"<tiff:Orientation>([0-9])</tiff:Orientation>",
125
+ ):
126
+ exif_image.info["XML:com.adobe.xmp"] = re.sub(
127
+ pattern, "", exif_image.info["XML:com.adobe.xmp"]
128
+ )
129
+ if not in_place:
130
+ return transposed_image
131
+ elif not in_place:
132
+ return image.copy()
133
+
134
+
135
+ class DetectWasteDataset(datasets.GeneratorBasedBuilder):
136
+ """AI4Good project for detecting waste in environment. www.detectwaste.ml."""
137
+
138
+ VERSION = datasets.Version("1.0.0")
139
+
140
+ BUILDER_CONFIGS = [
141
+ datasets.BuilderConfig(
142
+ name="taco-multi",
143
+ version=VERSION,
144
+ description="TACO dataset with 7 detect-waste categories object detection training",
145
+ ),
146
+ ]
147
+ DEFAULT_CONFIG_NAME = "taco-multi"
148
+
149
+ def _info(self):
150
+ features = datasets.Features(
151
+ {
152
+ "image_id": datasets.Value("int64"),
153
+ "image": datasets.Image(),
154
+ "width": datasets.Value("int32"),
155
+ "height": datasets.Value("int32"),
156
+ "objects": datasets.Sequence(
157
+ {
158
+ "id": datasets.Value("int64"),
159
+ "area": datasets.Value("int64"),
160
+ "bbox": datasets.Sequence(datasets.Value("float32"), length=4),
161
+ "category": datasets.ClassLabel(names=_CATEGORIES),
162
+ }
163
+ ),
164
+ }
165
+ )
166
+ return datasets.DatasetInfo(
167
+ description=_DESCRIPTION,
168
+ features=features,
169
+ homepage=_HOMEPAGE,
170
+ license=_LICENSE,
171
+ citation=_CITATION,
172
+ )
173
+
174
+ # fmt: off
175
+ # manually verified.
176
+ # these images need to be rotated so fit the annotations
177
+ _image_ids_for_exif_transpose = [228,229,230,231,232,233,234,235,237,240,241,242,243,295,296,297,298,299,300,301,302,303,304,307,308,309,310,311,312,313,315,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,345,353,354,355,359,360,362,372,460,522,527,528,529,530,531,532,534,535,536,537,538,539,540,541,542,543,545,546,548,550,551,553,556,557,559,560,561,562,563,564,565,566,567,568,569,570,571,572,573,574,575,576,577,578,579,580,581,582,583,584,585,586,587,588,589,590,591,592,593,594,595,596,597,598,599,600,601,602,603,604,605,606,607,608,609,610,611,612,613,614,615,617,618,672,679,680]
178
+ # these images do not need to be rotated, but have exif metadata that needs to be removed to cleanliness
179
+ _image_ids_for_exif_metadata_removal = [1501,1509,1511,1516,1518,1520,1530,1535,1538,1539,1541,1542,1545,1549,1550,1552,1559,1562,1563,1564,1568,1574,1576,1579,1581,1582,1584,1585,1590,1591,1592,1600,3274,3275,3294,3297,3298,3303,3304,3312,3313,3316,3317,3323,3326,3327,3331,3339,3340,3347,3350,3352,3354,3356,3364,3365,3372,3373,3376,3377,3378,3380,3382,3386,3390,3395,3397,3398,3399,3400,3401,3403,3406,3411,3412,3413,3415,3418,3421,3422,3427,3431,3432,3435,3437,3440,3442,3444,3447,3450,3452,3453,3461,3463,3464,3465,3466,3467,3474,3476,3478,3479,3480,3481,3492,3497,3499,3500,3501,3505,3508,3515,3516,3518,3522,3528,3529,3530,3533,3534,3536,3540,3541,3543,3548,3556,3558,3559,3565,3569,3570,3576,3579,3583,3584,3591,3592,3595,3599,3601,3606,3607,3609,3610,3613,3617,3623,3624,3625,3626,3629,3630,3633,3644,3645,3650,3655,3660,3663,3664,3665,3666,3668,3673,3678,3679,3680,3683,3686,3688,3690,3691,3693,3694,3695,3697,3701,3702,3704,3710,3711,3712,3717,3720,3723,3726,3730,3731,3732,3741,3742,3743,3745,3747,3750,3757,3758,3759,3763,3764,3767,3769,3773,3776,3780,3783,3786,3789,3790,3795,3796,3798,3800,3804,3805,3813,3815,3818,3820,3822,3823,3824,3825,3831,3833,3836,3837,3840,3841,3843,3852,3854,3855,3859,3863,3866,3869,3875,3878,3880,3884,3885,3886,3890,3891,3892,3896,3898,3900,3906,3908,3914,3916,3920,3923,3927,3929,3931,3932,3936,3937,3938,3939,3944,3947,3948,3952,3953,3958,3959,3960,3966,3967,3969,3971,3973,3979,3980,3981,3982,3987,3992,3994,3996,3997,4000,4001,4002,4004,4009,4010,4013,4014,4016,4017,4020,4021,4022,4028,4031,4034,4035,4037,4039,4043,4044,4047,4049,4050,4058,4061,4063,4066,4069,4072,4076,4079,4080,4085,4090,4094,4096,4098,4100,4101,4103,4104,4105,4107,4109,4111,4114,4116,4117,4118,4119,4122,4123,4124,4130,4134,4137,4139,4141,4143,4152,4155,4156,4158,4162,4164,4171,4173,4174,4175,4180,4181,4186,4188,4189,4191,4193,4200,4203,4204,4206,4207,4213,4214,4221,4224,4227,4229,4230,4233,4236,4245,4246,4248,4249,4250,4254,4255,4258,4259,4262,4263,4265,4272,4274,4282,4286,4289,4290,4296,4297,4299,4304,4306,4310,4313,4316,4321,4322,4323,4326,4331,4335,4336,4339,4348,4350,4360,4365,4367,4368,4369,4373,4378,4380,4390,4392,4396,4397,4399,4409,4411,4412,4413,4414,4416,4420,4423,4426,4427,4434,4439,4441,4446,4453,4454,4460,4462,4471,4472,4473,4475,4476,4479,4481,4483,4494,4497,4499,4504,4506,4508,4510,4513,4516,4518,4519,4520,4521,4522,4524,4527,4528,4533,4534,4537,4541,4545,4547,4550,4558,4563,4566,4569,4572,4577,4580,4581,4583,4586,4588,4591,4592,4593,4597,4599,4602,4603,4606,4609,4613,1507,1523,1536,1537,1555,1595,3279,3283,3284,3328,3358,3371,3388,3394,3408,3423,3425,3428,3433,3434,3449,3490,3504,3519,3523,3564,3567,3578,3589,3622,3640,3654,3658,3659,3667,3681,3687,3689,3698,3715,3718,3725,3727,3737,3749,3753,3756,3761,3768,3799,3835,3838,3844,3873,3881,3883,3907,3912,3935,3946,3957,3964,3974,3983,4033,4038,4051,4064,4075,4084,4091,4093,4120,4138,4159,4160,4166,4183,4192,4219,4220,4231,4240,4269,4291,4308,4311,4314,4317,4341,4342,4345,4358,4364,4372,4375,4393,4400,4431,4442,4445,4448,4449,4464,4480,4525,4540,4551,4555,4560,4561,4568,4585,4590,4605,4607]
180
+ # fmt: on
181
+ def _split_generators(self, dl_manager):
182
+ data_dir = dl_manager.download(_URLS)
183
+ csv_path = data_dir["taco_all_image_urls_csv"]
184
+ train_json_path = data_dir["annotations_train"]
185
+ test_json_path = data_dir["annotations_test"]
186
+
187
+ annotations_train = json.load(open(train_json_path))
188
+ annotations_test = json.load(open(test_json_path))
189
+
190
+ images = {}
191
+ with open(csv_path) as f:
192
+ reader = csv.DictReader(f, fieldnames=["flickr_640_url", "flickr_url"])
193
+ for row in reader:
194
+ for url in row.values():
195
+ if url:
196
+ images[Path(url).name] = row
197
+
198
+ images_train = annotations_train["images"]
199
+ images_test = annotations_test["images"]
200
+ # sanity check - train,test don't have overlapping images
201
+ assert not set(map(lambda image: image["id"], images_train)) & set(
202
+ map(lambda image: image["id"], images_test)
203
+ )
204
+
205
+ all_images = itertools.chain(images_train, images_test)
206
+ all_image_annotations = itertools.chain(
207
+ annotations_train["annotations"], annotations_test["annotations"]
208
+ )
209
+
210
+ image_id2image = {image["id"]: image for image in all_images}
211
+ image_ids_for_download = list(
212
+ map(
213
+ lambda ann: ann["image_id"],
214
+ all_image_annotations,
215
+ )
216
+ )
217
+
218
+ def standardize_image_dict(image):
219
+ name = Path(image["file_name"]).name
220
+ image["flickr_640_url"] = image.get("flickr_640_url") or ""
221
+ image["flickr_url"] = image.get("flickr_url") or ""
222
+ if name in images:
223
+ image.update(images[name])
224
+
225
+ def get_download_url(image):
226
+ file_path = Path(image["file_name"])
227
+ url = (
228
+ image["flickr_640_url"]
229
+ if Path(image["flickr_640_url"]).name == file_path.name
230
+ else image["flickr_url"]
231
+ )
232
+ return url
233
+
234
+ files = {}
235
+ for image_id in image_ids_for_download:
236
+ image = image_id2image[image_id]
237
+ standardize_image_dict(image)
238
+ url = get_download_url(image)
239
+ files[image_id] = url
240
+
241
+ image_id2storage_path = dl_manager.download(files)
242
+
243
+ def standardize_image_data(image, remove_exif_metadata_only=False):
244
+ image_id = image["id"]
245
+ image_name = Path(image["file_name"])
246
+ image_storage_path = Path(image_id2storage_path[image_id])
247
+ format = image_name.suffix[1:].lower().replace("jpg", "jpeg")
248
+
249
+ new_image_storage_path = image_storage_path.with_stem(
250
+ image_name.stem + "_exif"
251
+ )
252
+ with PIL.Image.open(str(image_storage_path)) as I:
253
+ exif_transpose(
254
+ I,
255
+ # in_place=True, # Does nothing. Pillow bug?
256
+ remove_exif_metadata_only=remove_exif_metadata_only,
257
+ ).save(
258
+ str(new_image_storage_path),
259
+ format=format,
260
+ subsampling=0,
261
+ quality=100,
262
+ )
263
+ image_id2storage_path[image_id] = str(new_image_storage_path.absolute())
264
+
265
+ for image_id in self._image_ids_for_exif_transpose:
266
+ image = image_id2image[image_id]
267
+ standardize_image_data(image)
268
+ for image_id in self._image_ids_for_exif_metadata_removal:
269
+ image = image_id2image[image_id]
270
+ standardize_image_data(image, remove_exif_metadata_only=True)
271
+
272
+ return [
273
+ datasets.SplitGenerator(
274
+ name=datasets.Split.TRAIN,
275
+ gen_kwargs={
276
+ "image_id2storage_path": image_id2storage_path,
277
+ "annotations": annotations_train,
278
+ "split": "train",
279
+ },
280
+ ),
281
+ datasets.SplitGenerator(
282
+ name=datasets.Split.TEST,
283
+ gen_kwargs={
284
+ "image_id2storage_path": image_id2storage_path,
285
+ "annotations": annotations_test,
286
+ "split": "test",
287
+ },
288
+ ),
289
+ ]
290
+
291
+ def _generate_examples(self, image_id2storage_path, annotations, split):
292
+ all_image_annotations = annotations["annotations"]
293
+ all_image_annotations = sorted(
294
+ all_image_annotations, key=lambda ann: ann["image_id"]
295
+ )
296
+ image_id2grouped_annotations = {
297
+ image_id: list(group)
298
+ for image_id, group in itertools.groupby(
299
+ all_image_annotations, lambda x: x["image_id"]
300
+ )
301
+ }
302
+
303
+ all_images = annotations["images"]
304
+ image_id2image = {image["id"]: image for image in all_images}
305
+
306
+ for image_id in image_id2image:
307
+ file_path = image_id2storage_path[image_id]
308
+ width, height = (
309
+ image_id2image[image_id]["width"],
310
+ image_id2image[image_id]["height"],
311
+ )
312
+ objects = image_id2grouped_annotations[image_id]
313
+ objects = [
314
+ {
315
+ "id": object["id"],
316
+ "area": object["area"],
317
+ "bbox": object["bbox"],
318
+ "category": object["category_id"] - 1,
319
+ }
320
+ for object in objects
321
+ ]
322
+ dat = image_id, {
323
+ "image_id": image_id,
324
+ "image": file_path,
325
+ "width": width,
326
+ "height": height,
327
+ "objects": objects,
328
+ }
329
+ yield dat