XintongHe commited on
Commit
0d03b37
1 Parent(s): 8da209d

Update new_dataset_script.py

Browse files
Files changed (1) hide show
  1. new_dataset_script.py +113 -106
new_dataset_script.py CHANGED
@@ -115,115 +115,122 @@ class NewDataset(datasets.GeneratorBasedBuilder):
115
  )
116
 
117
  def _split_generators(self, dl_manager):
118
- # TODO: This method is tasked with downloading/extracting the data and defining the splits depending on the configuration
119
- # If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
 
121
- # dl_manager is a datasets.download.DownloadManager that can be used to download and extract URLS
122
- # It can accept any type or nested list/dict and will give back the same structure with the url replaced with path to local files.
123
- # By default the archives will be extracted and a path to a cached folder where they are extracted is returned instead of the archive
124
-
125
- # Download and extract the dataset using Hugging Face's datasets library
126
- data_files = dl_manager.download_and_extract({
127
- "csv": "https://huggingface.co/datasets/XintongHe/Populus_Stomatal_Images_Datasets/resolve/main/Labeled Stomatal Images.csv",
128
- "zip": "https://huggingface.co/datasets/XintongHe/Populus_Stomatal_Images_Datasets/resolve/main/Labeled Stomatal Images.zip"
129
- })
130
-
131
- # Load the CSV file containing species and scientific names
132
- species_info = pd.read_csv(data_files["csv"])
133
 
134
- # Get the list of all image files from the CSV
135
- all_files = species_info['FileName'].tolist()
136
 
137
- # Shuffle the list for random split
138
- random.shuffle(all_files)
 
 
 
139
 
140
- # Split the files into train/validation/test
141
- num_files = len(all_files)
142
- train_split_end = int(num_files * 0.7)
143
- val_split_end = train_split_end + int(num_files * 0.15)
144
 
145
- train_files = all_files[:train_split_end]
146
- val_files = all_files[train_split_end:val_split_end]
147
- test_files = all_files[val_split_end:]
148
-
149
- return [
150
- SplitGenerator(
151
- name=Split.TRAIN,
152
- gen_kwargs={
153
- "filepaths": train_files,
154
- "species_info": species_info,
155
- "data_dir": extracted_path,
156
- "split": "train",
157
- },
158
- ),
159
- SplitGenerator(
160
- name=Split.VALIDATION,
161
- gen_kwargs={
162
- "filepaths": val_files,
163
- "species_info": species_info,
164
- "data_dir": extracted_path,
165
- "split": "validation",
166
- },
167
- ),
168
- SplitGenerator(
169
- name=Split.TEST,
170
- gen_kwargs={
171
- "filepaths": test_files,
172
- "species_info": species_info,
173
- "data_dir": extracted_path,
174
- "split": "test",
175
- },
176
- ),
177
- ]
178
-
179
- def _generate_examples(self, filepaths, species_info, data_dir, split):
180
- """Yields examples as (key, example) tuples."""
181
- for file_name in filepaths:
182
- # Extract the base name without the file extension
183
- image_id = os.path.splitext(file_name)[0]
184
-
185
- # Construct the full image file path
186
- image_path = os.path.join(data_dir, f"{image_id}.jpg")
187
- # Construct the full label file path
188
- label_path = os.path.join(data_dir, f"{image_id}.txt")
189
-
190
- # Open image and convert to array
191
- with Image.open(image_path) as img:
192
- pics_array = np.array(img)
193
- width, height = img.size
194
-
195
- # Extract species and scientific name from CSV file
196
- species_row = species_info.loc[species_info['FileName'] == image_id]
197
- species = species_row['Species'].values[0]
198
- scientific_name = species_row['ScientificName'].values[0]
199
-
200
- # Parse YOLO annotations
201
- annotations = self._parse_yolo_labels(label_path, width, height)
202
-
203
- # Yield the final structured example
204
- yield image_id, {
205
- "image_id": image_id,
206
- "species": species,
207
- "scientific_name": scientific_name,
208
- "pics_array": pics_array,
209
- "image_resolution": {"width": width, "height": height},
210
- "annotations": annotations
211
  }
212
-
213
- def _parse_yolo_labels(self, label_path, width, height):
214
- annotations = []
215
- with open(label_path, 'r') as file:
216
- yolo_data = file.readlines()
217
-
218
- for line in yolo_data:
219
- class_id, x_center_rel, y_center_rel, width_rel, height_rel = map(float, line.split())
220
- annotations.append({
221
- "category_id": int(class_id),
222
- "bounding_box": {
223
- "x_center": x_center_rel * width,
224
- "y_center": y_center_rel * height,
225
- "width": width_rel * width,
226
- "height": height_rel * height
227
- }
228
- })
229
- return annotatio
 
115
  )
116
 
117
  def _split_generators(self, dl_manager):
118
+ # Download and extract the dataset using Hugging Face's datasets library
119
+ data_files = dl_manager.download_and_extract({
120
+ "csv": "https://huggingface.co/datasets/XintongHe/Populus_Stomatal_Images_Datasets/resolve/main/Labeled Stomatal Images.csv",
121
+ "zip": "https://huggingface.co/datasets/XintongHe/Populus_Stomatal_Images_Datasets/resolve/main/Labeled Stomatal Images.zip"
122
+ })
123
+
124
+ # Load the CSV file containing species and scientific names
125
+ species_info = pd.read_csv(data_files["csv"])
126
+
127
+ # The directory 'Labeled Stomatal Images' is where the images and labels are stored after extraction
128
+ extracted_images_path = os.path.join(data_files["zip"], "Labeled Stomatal Images")
129
+
130
+ # Get the list of image filenames from the CSV
131
+ all_image_filenames = species_info['FileName'].apply(lambda x: x + '.jpg').tolist()
132
+
133
+ # Shuffle the list for random split
134
+ random.seed(42) # Set a random seed for reproducibility
135
+ random.shuffle(all_image_filenames)
136
+
137
+ # Split the files into train/validation/test
138
+ num_files = len(all_image_filenames)
139
+ train_split_end = int(num_files * 0.7)
140
+ val_split_end = train_split_end + int(num_files * 0.15)
141
+
142
+ train_files = all_image_filenames[:train_split_end]
143
+ val_files = all_image_filenames[train_split_end:val_split_end]
144
+ test_files = all_image_filenames[val_split_end:]
145
+
146
+ return [
147
+ SplitGenerator(
148
+ name=Split.TRAIN,
149
+ gen_kwargs={
150
+ "filepaths": train_files,
151
+ "species_info": species_info,
152
+ "data_dir": extracted_images_path,
153
+ "split": "train",
154
+ },
155
+ ),
156
+ SplitGenerator(
157
+ name=Split.VALIDATION,
158
+ gen_kwargs={
159
+ "filepaths": val_files,
160
+ "species_info": species_info,
161
+ "data_dir": extracted_images_path,
162
+ "split": "validation",
163
+ },
164
+ ),
165
+ SplitGenerator(
166
+ name=Split.TEST,
167
+ gen_kwargs={
168
+ "filepaths": test_files,
169
+ "species_info": species_info,
170
+ "data_dir": extracted_images_path,
171
+ "split": "test",
172
+ },
173
+ ),
174
+ ]
175
 
176
+ import os
177
+ from PIL import Image
178
+ import numpy as np
179
+ import pandas as pd
 
 
 
 
 
 
 
 
180
 
181
+ # ... other necessary imports and class definitions
 
182
 
183
+ def _generate_examples(self, filepaths, species_info, data_dir, split):
184
+ """Yields examples as (key, example) tuples."""
185
+ for file_name in filepaths:
186
+ # Extract the base name without the file extension for image_id
187
+ image_id = os.path.splitext(file_name)[0]
188
 
189
+ # Construct the full image file path and label file path
190
+ image_path = os.path.join(data_dir, f"{image_id}.jpg")
191
+ label_path = os.path.join(data_dir, f"{image_id}.txt")
 
192
 
193
+ # Open image and convert to array
194
+ with Image.open(image_path) as img:
195
+ pics_array = np.array(img)
196
+ width, height = img.size
197
+
198
+ # Extract species and scientific name from CSV file
199
+ species_row = species_info.loc[species_info['FileName'] == file_name]
200
+ species = species_row['Species'].values[0] if not species_row.empty else None
201
+ scientific_name = species_row['ScientificName'].values[0] if not species_row.empty else None
202
+
203
+ # Parse YOLO annotations
204
+ annotations = self._parse_yolo_labels(label_path, width, height)
205
+
206
+ # Yield the final structured example
207
+ yield image_id, {
208
+ "image_id": image_id,
209
+ "species": species,
210
+ "scientific_name": scientific_name,
211
+ "pics_array": pics_array,
212
+ "image_resolution": {"width": width, "height": height},
213
+ "annotations": annotations
214
+ }
215
+
216
+ def _parse_yolo_labels(self, label_path, width, height):
217
+ annotations = []
218
+ with open(label_path, 'r') as file:
219
+ yolo_data = file.readlines()
220
+
221
+ for line in yolo_data:
222
+ class_id, x_center_rel, y_center_rel, width_rel, height_rel = map(float, line.split())
223
+ x_center_abs = x_center_rel * width
224
+ y_center_abs = y_center_rel * height
225
+ bbox_width = width_rel * width
226
+ bbox_height = height_rel * height
227
+ annotations.append({
228
+ "category_id": int(class_id),
229
+ "bounding_box": {
230
+ "x_center": x_center_abs,
231
+ "y_center": y_center_abs,
232
+ "width": bbox_width,
233
+ "height": bbox_height
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
234
  }
235
+ })
236
+ return annotations