minhanhto09 commited on
Commit
dd1630f
1 Parent(s): bdf7c58

Update annotation_coordinates

Browse files
Files changed (1) hide show
  1. NuCLS_dataset.py +66 -51
NuCLS_dataset.py CHANGED
@@ -76,31 +76,24 @@ class NuCLSDataset(GeneratorBasedBuilder):
76
  ])
77
  type = ClassLabel(names=['rectangle', 'polyline'])
78
 
79
- # Assuming a maximum length for polygon coordinates.
80
- max_polygon_length = 20
81
-
82
  # Define features
83
  features = Features({
84
- # Images will be loaded as arrays; you'll dynamically handle the varying sizes in the generator function
85
- 'rgb_image': Image(decode=False),
86
- 'mask_image': Image(decode=False),
87
- 'visualization_image': Image(decode=False),
88
-
89
- # Annotation coordinates
90
- 'annotation_coordinates': Features({
91
- 'raw_classification': raw_classification,
92
- 'main_classification': main_classification,
93
- 'super_classification': super_classification,
94
- 'type': type,
95
- 'xmin': Value('int64'),
96
- 'ymin': Value('int64'),
97
- 'xmax': Value('int64'),
98
- 'ymax': Value('int64'),
99
- 'coords_x': Sequence(Value('float32')),
100
- 'coords_y': Sequence(Value('float32')),
101
- })
102
  })
103
-
104
  return DatasetInfo(
105
  description=_DESCRIPTION,
106
  features=features,
@@ -163,41 +156,63 @@ class NuCLSDataset(GeneratorBasedBuilder):
163
  """Yield examples as (key, example) tuples."""
164
 
165
  for key, paths in filepaths.items():
166
- # Initialize an example dictionary
167
- example = {
168
- 'rgb_image': self._read_image_file(paths['fov']),
169
- 'mask_image': self._read_image_file(paths['mask']),
170
- 'visualization_image': self._read_image_file(paths['visualization']),
171
- 'annotation_coordinates': self._read_csv_file(paths['csv']),
 
 
 
 
 
 
 
 
172
  }
173
 
174
- yield key, example
175
-
176
- def _read_image_file(self, file_path: str) -> PilImage:
177
- """Reads an image file and returns it as a PIL Image object."""
178
  try:
179
  with open(file_path, 'rb') as f:
180
- image = PilImage.open(f)
181
- return np.array(image)
182
  except Exception as e:
183
  print(f"Error reading image file {file_path}: {e}")
184
  return None
185
 
186
- def _read_csv_file(self, file_path: str):
187
- """Reads a CSV file and returns the contents in the expected format."""
188
- try:
189
- csv_df = pd.read_csv(file_path)
190
- if csv_df.empty:
191
- print(f"Warning: CSV file {file_path} is empty.")
192
- return None
193
- else:
194
- # Convert the DataFrame into the structure that matches your features' annotation_coordinates
195
- return self._process_csv_data(csv_df)
196
- except Exception as e:
197
- print(f"Error reading CSV file {file_path}: {e}")
198
- return None
 
 
 
 
199
 
200
- # Implement this method to process and convert CSV data into the format expected by your dataset's features
201
- def _process_csv_data(self, csv_df):
202
- # Process the DataFrame and return the data in the correct format
203
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  ])
77
  type = ClassLabel(names=['rectangle', 'polyline'])
78
 
 
 
 
79
  # Define features
80
  features = Features({
81
+ 'rgb_image': Image(decode=True),
82
+ 'mask_image': Image(decode=True),
83
+ 'visualization_image': Image(decode=True),
84
+ 'annotation_coordinates': Features({
85
+ 'raw_classification': Sequence(Value("string")),
86
+ 'main_classification': Sequence(Value("string")),
87
+ 'super_classification': Sequence(Value("string")),
88
+ 'type': Sequence(Value("string")),
89
+ 'xmin': Sequence(Value('int64')),
90
+ 'ymin': Sequence(Value('int64')),
91
+ 'xmax': Sequence(Value('int64')),
92
+ 'ymax': Sequence(Value('int64')),
93
+ 'coords_x': Sequence(Sequence(Value('int64'))), # Lists of integers
94
+ 'coords_y': Sequence(Sequence(Value('int64'))), # Lists of integers
95
+ })
 
 
 
96
  })
 
97
  return DatasetInfo(
98
  description=_DESCRIPTION,
99
  features=features,
 
156
  """Yield examples as (key, example) tuples."""
157
 
158
  for key, paths in filepaths.items():
159
+ # Read the images using a method to handle the image files
160
+ rgb_image = self._read_image_file(paths['rgb'])
161
+ mask_image = self._read_image_file(paths['mask'])
162
+ visualization_image = self._read_image_file(paths['visualization'])
163
+
164
+ # Read the CSV and format the data as per the defined features
165
+ annotation_coordinates = self._read_csv_file(paths['csv'])
166
+
167
+ # Yield the example
168
+ yield key, {
169
+ 'rgb_image': rgb_image,
170
+ 'mask_image': mask_image,
171
+ 'visualization_image': visualization_image,
172
+ 'annotation_coordinates': annotation_coordinates,
173
  }
174
 
175
+ def _read_image_file(self, file_path: str, ) -> bytes:
176
+ """Reads an image file and returns it as a bytes_like object."""
 
 
177
  try:
178
  with open(file_path, 'rb') as f:
179
+ return f.read()
 
180
  except Exception as e:
181
  print(f"Error reading image file {file_path}: {e}")
182
  return None
183
 
184
+ def _read_csv_file(self, filepath):
185
+ """Reads the annotation CSV file and formats the data."""
186
+
187
+ with open(filepath, 'r', encoding='utf-8') as csvfile:
188
+ reader = csv.DictReader(csvfile)
189
+ annotations = {
190
+ 'raw_classification': [],
191
+ 'main_classification': [],
192
+ 'super_classification': [],
193
+ 'type': [],
194
+ 'xmin': [],
195
+ 'ymin': [],
196
+ 'xmax': [],
197
+ 'ymax': [],
198
+ 'coords_x': [],
199
+ 'coords_y': []
200
+ }
201
 
202
+ for row in reader:
203
+ annotations['raw_classification'].append(row.get('raw_classification', ''))
204
+ annotations['main_classification'].append(row.get('main_classification', ''))
205
+ annotations['super_classification'].append(row.get('super_classification', ''))
206
+ annotations['type'].append(row.get('type', ''))
207
+ annotations['xmin'].append(int(row.get('xmin', 0)))
208
+ annotations['ymin'].append(int(row.get('ymin', 0)))
209
+ annotations['xmax'].append(int(row.get('xmax', 0)))
210
+ annotations['ymax'].append(int(row.get('ymax', 0)))
211
+
212
+ # Handle coords_x and coords_y safely
213
+ coords_x = row.get('coords_x', '')
214
+ coords_y = row.get('coords_y', '')
215
+ annotations['coords_x'].append([int(coord) if coord.isdigit() else 0 for coord in coords_x.split(',')])
216
+ annotations['coords_y'].append([int(coord) if coord.isdigit() else 0 for coord in coords_y.split(',')])
217
+
218
+ return annotations