viarias commited on
Commit
be46cd1
1 Parent(s): 3ac54d7

Upload remote_sensing_2018_weedmap.py

Browse files
Files changed (1) hide show
  1. remote_sensing_2018_weedmap.py +253 -0
remote_sensing_2018_weedmap.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from collections import OrderedDict, defaultdict
4
+ from math import ceil
5
+ from sklearn.model_selection import train_test_split
6
+ import numpy as np
7
+ import pandas as pd
8
+
9
+ import datasets
10
+
11
+ logger = datasets.logging.get_logger(__name__)
12
+
13
+ _LICENSE = "GPL-3.0 license"
14
+
15
+ _CITATION = """\
16
+ @article{weedMap-2018,
17
+ author={I. Sa, M. Popovic, R. Khanna, Z. Chen, P. Lottes, F. Liebisch, J. Nieto, C. Stachniss, A. Walter, and R. Siegwart},
18
+ journal={MDPI Remote Sensing},
19
+ title={WeedMap: A large-scale semantic weed mapping framework using aerial multispectral imaging and deep neural network for precision farming},
20
+ year={2018},
21
+ volume={10},
22
+ number={9},
23
+ doi={doi: 10.3390/rs10091423},
24
+ month={Aug}}
25
+ }
26
+ """
27
+
28
+ _HOMEPAGE = "https://projects.asl.ethz.ch/datasets/doku.php?id=weedmap:remotesensing2018weedmap"
29
+
30
+ _DESCRIPTION = """\
31
+ The WeedMap dataset is a comprehensive collection of multispectral images captured from sugar beet fields in Eschikon, Switzerland, and Rheinbach, Germany, using quadrotor UAVs equipped with RedEdge-M and Sequoia multispectral cameras.
32
+ Spanning over five months, it comprises 129 directories with 18,746 image files. The dataset is divided into Orthomosaic and Tiles folders, featuring orthomosaic maps and their segmented tiles, respectively.
33
+ Ground truth annotations are provided, detailing classifications such as background, crop, and weed in both color and indexed formats. This dataset, the largest publicly available for sugar beet fields with pixel-level ground truth, spans a total area of 16,554 square meters.
34
+ It offers a detailed representation of the agricultural landscape, including a ground sample distance of about 1cm, facilitating high precision in weed detection research. This rich dataset supports the development of advanced deep learning models for semantic segmentation in precision agriculture, enhancing weed management practices​​​​.
35
+ """
36
+
37
+ _URLS = {
38
+ "RED_EDGE": "http://robotics.ethz.ch/~asl-datasets/2018-weedMap-dataset-release/Tiles/RedEdge.zip",
39
+ "SEQUOIA": "http://robotics.ethz.ch/~asl-datasets/2018-weedMap-dataset-release/Tiles/Sequoia.zip",
40
+ }
41
+
42
+ WEEDMAP_CLASSES = OrderedDict(
43
+ {
44
+ 0: "BACKGROUND",
45
+ 1: "CROP",
46
+ 2: "WEED",
47
+ }
48
+ )
49
+
50
+ SEQUOIA_CHANNELS = ['CIR', 'G', 'NDVI', 'NIR', 'R', 'RE']
51
+ SEQUOIA_SPLIT = {
52
+ "train": ["006", "007"],
53
+ "test": ["005"],
54
+ }
55
+
56
+ REDEDGE_CHANNELS = ['B', 'CIR', 'G', 'NDVI', 'NIR', 'R', 'RE', "RGB"]
57
+ REDEDGE_SPLIT = {
58
+ "train": ["000", "001", "002", "004"],
59
+ "test": ["003"],
60
+ }
61
+
62
+
63
+ class WeedMapConfig(datasets.BuilderConfig):
64
+ """BuilderConfig for WeedMap."""
65
+
66
+ def __init__(self, data_url, **kwargs):
67
+ """BuilderConfig for WeedMap.
68
+
69
+ Args:
70
+ data_url: `string`, url to download the zip file from.
71
+ **kwargs: keyword arguments forwarded to super.
72
+ """
73
+ super(WeedMapConfig, self).__init__(version=datasets.Version("1.0.0"), **kwargs)
74
+ self.data_url = data_url
75
+
76
+ class WeedMap(datasets.GeneratorBasedBuilder):
77
+ """Remote Sensing 2018 Weed Map Dataset."""
78
+
79
+ BUILDER_CONFIGS = [
80
+ WeedMapConfig(
81
+ name="red_edge",
82
+ description="weedmap dataset with the subset generated by the Red Edge sensor",
83
+ data_url=_URLS["RED_EDGE"],)
84
+ ,
85
+ WeedMapConfig(
86
+ name="sequoia",
87
+ description="weedmap dataset with the subset generated by the Sequoia sensor",
88
+ data_url=_URLS["SEQUOIA"],)
89
+ ]
90
+
91
+ DEFAULT_CONFIG_NAME = "red_edge"
92
+
93
+ def _info(self):
94
+ if self.config.name == "red_edge":
95
+ features = datasets.Features(
96
+ {
97
+ "B": datasets.Image(),
98
+ "CIR": datasets.Image(),
99
+ "G": datasets.Image(),
100
+ "NDVI": datasets.Image(),
101
+ "NIR": datasets.Image(),
102
+ "R": datasets.Image(),
103
+ "RE": datasets.Image(),
104
+ "RGB": datasets.Image(),
105
+ "annotation": datasets.Image(),
106
+ }
107
+ )
108
+ elif self.config.name == "sequoia":
109
+ features = datasets.Features(
110
+ {
111
+ "CIR": datasets.Image(),
112
+ "G": datasets.Image(),
113
+ "NDVI": datasets.Image(),
114
+ "NIR": datasets.Image(),
115
+ "R": datasets.Image(),
116
+ "RE": datasets.Image(),
117
+ "annotation": datasets.Image(),
118
+ }
119
+ )
120
+
121
+ return datasets.DatasetInfo(
122
+ description=_DESCRIPTION,
123
+ features=features,
124
+ homepage=_HOMEPAGE,
125
+ license=_LICENSE,
126
+ citation=_CITATION,
127
+ )
128
+
129
+ def _split_generators(self, dl_manager):
130
+ """Returns SplitGenerators."""
131
+ # use the datasets.DownloadManager().download_and_extract() method to download the data
132
+ # in testing time, the data will be downloaded in the default cache directory, which is
133
+ # ~/.cache/huggingface/datasets
134
+
135
+ def images_and_masks(images_dict, masks):
136
+ for image_dict, mask in zip(images_dict, masks):
137
+ yield image_dict, mask
138
+
139
+ if self.config.name == "red_edge":
140
+ data_dir = dl_manager.download_and_extract(_URLS["RED_EDGE"])
141
+ files_path = dl_manager.iter_files(data_dir)
142
+ train_image_files, train_mask_files = create_list_paths(files_path, subset="red_edge", split_section="train")
143
+ test_image_files, test_mask_files = create_list_paths(files_path, subset="red_edge", split_section="test")
144
+
145
+
146
+ elif self.config.name == "sequoia":
147
+ data_dir = dl_manager.download_and_extract(_URLS["SEQUOIA"])
148
+ files_path = dl_manager.iter_files(data_dir)
149
+ train_image_files, train_mask_files = create_list_paths(files_path, subset="sequoia", split_section="train")
150
+ test_image_files, test_mask_files = create_list_paths(files_path, subset="sequoia", split_section="test")
151
+
152
+ return [
153
+ datasets.SplitGenerator(
154
+ name=datasets.Split.TRAIN,
155
+ gen_kwargs={
156
+ "data": images_and_masks(train_image_files, train_mask_files),
157
+ },
158
+ ),
159
+ datasets.SplitGenerator(
160
+ name=datasets.Split.TEST,
161
+ gen_kwargs={
162
+ "data": images_and_masks(test_image_files, test_mask_files),
163
+ },
164
+ ),
165
+ ]
166
+
167
+ def _generate_examples(self, data):
168
+
169
+ """Yields examples."""
170
+ if self.config.name == "red_edge":
171
+ for idx, (img_path, msk_path) in enumerate(data):
172
+ print("")
173
+ print("")
174
+ print("")
175
+ print(img_path["B"])
176
+ print("")
177
+ print("")
178
+ print("")
179
+ yield idx, {
180
+ "B": img_path["B"],
181
+ "CIR": img_path["CIR"],
182
+ "G": img_path["G"],
183
+ "NDVI": img_path["NDVI"],
184
+ "NIR": img_path["NIR"],
185
+ "R": img_path["R"],
186
+ "RE": img_path["RE"],
187
+ "RGB": img_path["RGB"],
188
+ "annotation": msk_path,
189
+ }
190
+
191
+ elif self.config.name == "sequoia":
192
+ for idx, (img_path, msk_path) in enumerate(data):
193
+ yield idx, {
194
+ "CIR": img_path["CIR"],
195
+ "G": img_path["G"],
196
+ "NDVI": img_path["NDVI"],
197
+ "NIR": img_path["NIR"],
198
+ "R": img_path["R"],
199
+ "RE": img_path["RE"],
200
+ "annotation": msk_path,
201
+ }
202
+
203
+ def create_list_paths(total_files_path, subset="red_edge", split_section="train"):
204
+ """
205
+ Create a list of paths for the images and masks.
206
+
207
+ Args:
208
+ total_files_path (list): A list of file paths.
209
+ subset (str, optional): The subset to filter the files. Defaults to "red_edge".
210
+ split_section (str, optional): The split section to filter the files. Defaults to "train".
211
+
212
+ Returns:
213
+ tuple or list: If split_section is "train", returns a tuple containing train_image_files, train_mask_files,
214
+ val_image_files, val_mask_files. Otherwise, returns a list containing split_image_files and
215
+ split_mask_files.
216
+ """
217
+ if subset == "red_edge":
218
+ subset_dict = REDEDGE_SPLIT
219
+
220
+ elif subset == "sequoia":
221
+ subset_dict = SEQUOIA_SPLIT
222
+
223
+ # multi filter
224
+ split_files_path = [
225
+ file_path for file_path in total_files_path
226
+ if (
227
+ (not ".DS_Store" in file_path) and # don't take account trash files
228
+ ("GroundTruth_color.png" in file_path or # if the image is a color mask, save the path
229
+ file_path.split("/")[-4] in subset_dict[split_section] # if the image is in the correct split folder, save the path
230
+ )
231
+ )
232
+ ]
233
+
234
+ split_mask_files = []
235
+ split_image_files = dict()
236
+
237
+ # separate every tile by channel name
238
+ for file in split_files_path:
239
+ if "tile" in file:
240
+ image_channel_name = file.split("/")[-2]
241
+ split_image_files.setdefault(image_channel_name, [])
242
+ split_image_files[image_channel_name].append(file)
243
+ else:
244
+ split_mask_files.append(file)
245
+
246
+ # sorted the image and mask files by name
247
+ for key, image_paths_channel in split_image_files.items():
248
+ split_image_files[key] = sorted(image_paths_channel, key=lambda path_file: (str(path_file).split("/")[-4], str(path_file).split("/")[-1]))
249
+ split_mask_files = sorted(split_mask_files, key=lambda path_file: (str(path_file).split("/")[-4], str(path_file).split("/")[-1]))
250
+
251
+ split_image_files_ld = [dict(zip(split_image_files, t)) for t in zip(*split_image_files.values())]
252
+
253
+ return split_image_files_ld, split_mask_files