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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import fiftyone as fo
|
| 4 |
+
from PIL import Image
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
def load_sample_files(subdir):
|
| 8 |
+
"""
|
| 9 |
+
Load all required files for a single sample.
|
| 10 |
+
|
| 11 |
+
Args:
|
| 12 |
+
subdir (Path): Path to the sample subdirectory
|
| 13 |
+
|
| 14 |
+
Returns:
|
| 15 |
+
tuple: (detections_data, questions_data, mask_file_path, source_file_path, img_dimensions)
|
| 16 |
+
Returns None if any required files are missing.
|
| 17 |
+
"""
|
| 18 |
+
subdir_name = subdir.name
|
| 19 |
+
|
| 20 |
+
# Define file paths
|
| 21 |
+
detection_file = subdir / "detection.json"
|
| 22 |
+
question_file = subdir / "question.json"
|
| 23 |
+
mask_file = subdir / f"mask_{subdir_name}.png"
|
| 24 |
+
source_file = subdir / f"source_{subdir_name}.jpg"
|
| 25 |
+
|
| 26 |
+
# Check all files exist
|
| 27 |
+
if not all(f.exists() for f in [detection_file, question_file, mask_file, source_file]):
|
| 28 |
+
return None
|
| 29 |
+
|
| 30 |
+
# Load JSON data
|
| 31 |
+
with open(detection_file, 'r') as f:
|
| 32 |
+
detections_data = json.load(f)
|
| 33 |
+
|
| 34 |
+
with open(question_file, 'r') as f:
|
| 35 |
+
questions_data = json.load(f)
|
| 36 |
+
|
| 37 |
+
# Get image dimensions
|
| 38 |
+
with Image.open(source_file) as img:
|
| 39 |
+
img_dimensions = img.size
|
| 40 |
+
|
| 41 |
+
return detections_data, questions_data, mask_file, source_file, img_dimensions
|
| 42 |
+
|
| 43 |
+
def convert_detections_to_relative(detections_data, img_width, img_height):
|
| 44 |
+
"""
|
| 45 |
+
Convert absolute bounding boxes to relative coordinates for FiftyOne.
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
detections_data (list): List of detection dictionaries
|
| 49 |
+
img_width (int): Image width in pixels
|
| 50 |
+
img_height (int): Image height in pixels
|
| 51 |
+
|
| 52 |
+
Returns:
|
| 53 |
+
fo.Detections: FiftyOne Detections object
|
| 54 |
+
"""
|
| 55 |
+
detections = []
|
| 56 |
+
|
| 57 |
+
for detection_dict in detections_data:
|
| 58 |
+
for label, bbox in detection_dict.items():
|
| 59 |
+
x, y, width, height = bbox
|
| 60 |
+
# Convert to relative coordinates
|
| 61 |
+
rel_x = x / img_width
|
| 62 |
+
rel_y = y / img_height
|
| 63 |
+
rel_width = width / img_width
|
| 64 |
+
rel_height = height / img_height
|
| 65 |
+
|
| 66 |
+
detection = fo.Detection(
|
| 67 |
+
label=label,
|
| 68 |
+
bounding_box=[rel_x, rel_y, rel_width, rel_height]
|
| 69 |
+
)
|
| 70 |
+
detections.append(detection)
|
| 71 |
+
|
| 72 |
+
return fo.Detections(detections=detections)
|
| 73 |
+
|
| 74 |
+
def add_sample_metadata(sample, english_questions):
|
| 75 |
+
"""
|
| 76 |
+
Add sample-level metadata from questions data.
|
| 77 |
+
|
| 78 |
+
Args:
|
| 79 |
+
sample (fo.Sample): FiftyOne sample to modify
|
| 80 |
+
english_questions (list): List of English question dictionaries
|
| 81 |
+
"""
|
| 82 |
+
if not english_questions:
|
| 83 |
+
return
|
| 84 |
+
|
| 85 |
+
# Sample-level metadata (same for all questions in a sample)
|
| 86 |
+
first_question = english_questions[0]
|
| 87 |
+
sample['location'] = fo.Classification(label=first_question['location'])
|
| 88 |
+
sample['modality'] = fo.Classification(label=first_question['modality'])
|
| 89 |
+
sample['base_type'] = fo.Classification(label=first_question['base_type'])
|
| 90 |
+
sample['answer_type'] = fo.Classification(label=first_question['answer_type'])
|
| 91 |
+
|
| 92 |
+
def add_questions_and_answers(sample, english_questions):
|
| 93 |
+
"""
|
| 94 |
+
Add individual questions and answers to the sample.
|
| 95 |
+
|
| 96 |
+
Args:
|
| 97 |
+
sample (fo.Sample): FiftyOne sample to modify
|
| 98 |
+
english_questions (list): List of English question dictionaries
|
| 99 |
+
"""
|
| 100 |
+
for i, q_data in enumerate(english_questions):
|
| 101 |
+
sample[f'question_{i}'] = q_data['question']
|
| 102 |
+
sample[f'answer_{i}'] = fo.Classification(label=q_data['answer'])
|
| 103 |
+
|
| 104 |
+
def process_single_sample(subdir):
|
| 105 |
+
"""
|
| 106 |
+
Process a single sample directory into a FiftyOne sample.
|
| 107 |
+
|
| 108 |
+
Args:
|
| 109 |
+
subdir (Path): Path to the sample subdirectory
|
| 110 |
+
|
| 111 |
+
Returns:
|
| 112 |
+
fo.Sample or None: FiftyOne sample, or None if processing failed
|
| 113 |
+
"""
|
| 114 |
+
subdir_name = subdir.name
|
| 115 |
+
|
| 116 |
+
# Load all files for this sample
|
| 117 |
+
file_data = load_sample_files(subdir)
|
| 118 |
+
if file_data is None:
|
| 119 |
+
print(f"Warning: Missing files in {subdir_name}, skipping...")
|
| 120 |
+
return None
|
| 121 |
+
|
| 122 |
+
detections_data, questions_data, mask_file, source_file, (img_width, img_height) = file_data
|
| 123 |
+
|
| 124 |
+
# Create FiftyOne sample
|
| 125 |
+
sample = fo.Sample(filepath=str(source_file.absolute()))
|
| 126 |
+
|
| 127 |
+
# Add detections
|
| 128 |
+
sample['detections'] = convert_detections_to_relative(detections_data, img_width, img_height)
|
| 129 |
+
|
| 130 |
+
# Add segmentation mask
|
| 131 |
+
sample['segmentation'] = fo.Segmentation(mask_path=str(mask_file.absolute()))
|
| 132 |
+
|
| 133 |
+
# Filter to English questions only and preserve order
|
| 134 |
+
english_questions = [q for q in questions_data if q.get('q_lang') == 'en']
|
| 135 |
+
|
| 136 |
+
# Add sample-level metadata
|
| 137 |
+
add_sample_metadata(sample, english_questions)
|
| 138 |
+
|
| 139 |
+
# Add individual questions and answers
|
| 140 |
+
add_questions_and_answers(sample, english_questions)
|
| 141 |
+
|
| 142 |
+
return sample
|
| 143 |
+
|
| 144 |
+
def parse_slake_dataset(data_root="SLAKE/imgs", dataset_name="SLAKE"):
|
| 145 |
+
"""
|
| 146 |
+
Parse SLAKE dataset into FiftyOne format.
|
| 147 |
+
|
| 148 |
+
Args:
|
| 149 |
+
data_root (str): Path to the SLAKE/imgs directory
|
| 150 |
+
dataset_name (str): Name for the FiftyOne dataset
|
| 151 |
+
|
| 152 |
+
Returns:
|
| 153 |
+
fo.Dataset: FiftyOne dataset with parsed samples
|
| 154 |
+
"""
|
| 155 |
+
dataset = fo.Dataset(dataset_name, overwrite=True)
|
| 156 |
+
|
| 157 |
+
data_root = Path(data_root)
|
| 158 |
+
samples = []
|
| 159 |
+
|
| 160 |
+
# Process each subdirectory
|
| 161 |
+
for subdir in data_root.iterdir():
|
| 162 |
+
if not subdir.is_dir():
|
| 163 |
+
continue
|
| 164 |
+
|
| 165 |
+
print(f"Processing {subdir.name}...")
|
| 166 |
+
sample = process_single_sample(subdir)
|
| 167 |
+
|
| 168 |
+
if sample is not None:
|
| 169 |
+
samples.append(sample)
|
| 170 |
+
|
| 171 |
+
# Add all samples to dataset efficiently
|
| 172 |
+
dataset.add_samples(samples)
|
| 173 |
+
dataset.compute_metadata()
|
| 174 |
+
|
| 175 |
+
return dataset
|
| 176 |
+
|
| 177 |
+
import fiftyone as fo
|
| 178 |
+
from pathlib import Path
|
| 179 |
+
|
| 180 |
+
def load_mask_targets_from_file(mask_targets_file):
|
| 181 |
+
"""
|
| 182 |
+
Load mask targets mapping from file.
|
| 183 |
+
|
| 184 |
+
Args:
|
| 185 |
+
mask_targets_file (str): Path to the mask targets file
|
| 186 |
+
|
| 187 |
+
Returns:
|
| 188 |
+
dict: Mapping of pixel values to organ labels
|
| 189 |
+
"""
|
| 190 |
+
mask_targets = {}
|
| 191 |
+
|
| 192 |
+
with open(mask_targets_file, 'r') as f:
|
| 193 |
+
for line in f:
|
| 194 |
+
line = line.strip()
|
| 195 |
+
if ':' in line:
|
| 196 |
+
pixel_value, label = line.split(':', 1)
|
| 197 |
+
mask_targets[int(pixel_value)] = label
|
| 198 |
+
|
| 199 |
+
return mask_targets
|
| 200 |
+
|
| 201 |
+
def set_dataset_mask_targets(dataset_name, mask_targets_file, segmentation_field="segmentation"):
|
| 202 |
+
"""
|
| 203 |
+
Set mask targets for an existing FiftyOne dataset.
|
| 204 |
+
|
| 205 |
+
Args:
|
| 206 |
+
dataset_name (str): Name of the FiftyOne dataset
|
| 207 |
+
mask_targets_file (str): Path to the mask targets mapping file
|
| 208 |
+
segmentation_field (str): Name of the segmentation field (default: "segmentation")
|
| 209 |
+
"""
|
| 210 |
+
# Load dataset
|
| 211 |
+
dataset = fo.load_dataset(dataset_name)
|
| 212 |
+
|
| 213 |
+
# Load mask targets from file
|
| 214 |
+
mask_targets = load_mask_targets_from_file(mask_targets_file)
|
| 215 |
+
|
| 216 |
+
# Set mask targets
|
| 217 |
+
dataset.mask_targets = {segmentation_field: mask_targets}
|
| 218 |
+
dataset.save() # Must save after setting mask targets
|
| 219 |
+
|
| 220 |
+
for i, (pixel_val, label) in enumerate(list(mask_targets.items())[:5]):
|
| 221 |
+
print(f" {pixel_val}: {label}")
|
| 222 |
+
if len(mask_targets) > 5:
|
| 223 |
+
print(f" ... and {len(mask_targets) - 5} more")
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
dataset = parse_slake_dataset("SLAKE/imgs", "SLAKE")
|
| 228 |
+
|
| 229 |
+
set_dataset_mask_targets(
|
| 230 |
+
dataset_name="SLAKE", # Your dataset name
|
| 231 |
+
mask_targets_file="SLAKE/mask.txt", # Your mapping file
|
| 232 |
+
segmentation_field="segmentation"
|
| 233 |
+
)
|