File size: 13,475 Bytes
4ab0193 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 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 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 | import csv
import json
import os
import random
from collections import defaultdict
from multiprocessing import Pool
from PIL import Image
BASE_DIR = "./Chest_imagenome"
DATA_DIR = os.path.join(BASE_DIR, "gold")
BBOX_CSV = os.path.join(DATA_DIR, "gold_bbox_coordinate_annotations_1000images.csv")
SENTENCES = os.path.join(DATA_DIR, "gold_all_sentences_500pts_1000studies.txt")
SILVER_DIR = os.path.join(BASE_DIR, "silver")
SG_DIR = os.path.join(SILVER_DIR, "scene_graph")
SPLIT_DIR = os.path.join(SILVER_DIR, "split")
MIMIC_DIR = "./mimic_original/2.0.0/files"
GOLD_CROP_DIR = os.path.join(BASE_DIR, "gold_crop")
SILVER_CROP_DIR = os.path.join(BASE_DIR, "silver_sample_crop")
OUTPUT_TRAIN_JSON = os.path.join(BASE_DIR, "Chest_imagenome_train.json")
OUTPUT_TEST_JSON = os.path.join(BASE_DIR, "Chest_imagenome_test.json")
TARGET_TOTAL = 1_000_000
MIN_SIZE = 28
NUM_WORKERS_GOLD = 8
NUM_WORKERS_SILVER = 16
MAX_TEST_SAMPLES = 1000
RANDOM_SEED = 42
SEED = 42
TRAIN_IMAGE_ROOT = MIMIC_DIR
TRAIN_CROP_ROOT = BASE_DIR
TEST_IMAGE_ROOT = MIMIC_DIR
TEST_CROP_ROOT = BASE_DIR
def crop_with_min_size(img, x_min, y_min, x_max, y_max, min_size=MIN_SIZE):
cx = (x_min + x_max) // 2
cy = (y_min + y_max) // 2
w = max(x_max - x_min, min_size)
h = max(y_max - y_min, min_size)
x_min = max(0, cx - w // 2); x_max = min(img.width, x_min + w); x_min = max(0, x_max - w)
y_min = max(0, cy - h // 2); y_max = min(img.height, y_min + h); y_min = max(0, y_max - h)
return img.crop((x_min, y_min, x_max, y_max))
def normalize_path(path):
return str(path).replace("\\", "/")
def remove_root_prefix(path, root):
path = normalize_path(path)
root = normalize_path(root).rstrip("/")
if path.startswith(root + "/"):
return path[len(root) + 1:]
elif path == root:
return ""
return path
def process_gold_image(args):
image_id, regions, class_to_id, img_path = args
try:
img = Image.open(img_path)
except Exception as e:
return None, f"open {image_id}: {e}"
map_rows = []
for bbox_name, box in regions:
class_id = class_to_id[bbox_name]
crop_path = os.path.join(GOLD_CROP_DIR, f"{image_id}_{class_id}_0.png")
try:
crop_with_min_size(img, *box).save(crop_path)
except Exception as e:
return None, f"crop {image_id} {bbox_name}: {e}"
map_rows.append({
"image_path": img_path,
"class_name": bbox_name,
"crop_image_paths": [crop_path],
})
return map_rows, None
def run_gold():
os.makedirs(GOLD_CROP_DIR, exist_ok=True)
img_to_path = {}
with open(SENTENCES, newline="") as f:
for row in csv.DictReader(f, delimiter="\t"):
image_id = row["image_id"]
if image_id in img_to_path:
continue
patient_id = row["patient_id"]
study_id = row["study_id"]
jpg_name = image_id.replace(".dcm", ".jpg")
img_to_path[image_id] = os.path.join(
MIMIC_DIR, f"p{patient_id[:2]}", f"p{patient_id}", f"s{study_id}", jpg_name
)
print(f"[gold] image path mapping: {len(img_to_path)}")
image_regions = defaultdict(list)
all_names = set()
with open(BBOX_CSV, newline="") as f:
for row in csv.DictReader(f):
image_id = row["image_id"]
bbox_name = row["bbox_name"]
box = (
max(0, int(float(row["original_x1"]))),
max(0, int(float(row["original_y1"]))),
max(0, int(float(row["original_x2"]))),
max(0, int(float(row["original_y2"]))),
)
image_regions[image_id].append((bbox_name, box))
all_names.add(bbox_name)
class_to_id = {name: idx for idx, name in enumerate(sorted(all_names))}
print(f"[gold] regions: {len(class_to_id)} images: {len(image_regions)}")
tasks = []
for image_id, regions in image_regions.items():
if image_id not in img_to_path:
continue
img_id_short = image_id.replace(".dcm", "")
tasks.append((img_id_short, regions, class_to_id, img_to_path[image_id]))
print(f"[gold] tasks: {len(tasks)} workers: {NUM_WORKERS_GOLD}")
records = []
errors = 0
with Pool(NUM_WORKERS_GOLD) as pool:
for i, (map_rows, err) in enumerate(
pool.imap_unordered(process_gold_image, tasks, chunksize=4), start=1
):
if err:
print(f" ERROR: {err}"); errors += 1
elif map_rows:
records.extend(map_rows)
if i % 200 == 0:
print(f" [gold {i}/{len(tasks)}] errors={errors}")
print(f"[gold] done. records={len(records)} errors={errors}")
return records
def scan_one_json(args):
sg_path, dicom_id = args
try:
with open(sg_path) as f:
sg = json.load(f)
except Exception:
return None
names = [obj["bbox_name"] for obj in sg.get("objects", []) if obj.get("original_x1") is not None]
return (dicom_id, names) if names else None
def process_silver_image(args):
dicom_id, img_path, sg_path, split, selected_names, class_to_id = args
try:
with open(sg_path) as f:
sg = json.load(f)
except Exception as e:
return None, f"json {dicom_id}: {e}"
obj_map = {obj["bbox_name"]: obj for obj in sg.get("objects", [])}
try:
img = Image.open(img_path)
except Exception as e:
return None, f"open {dicom_id}: {e}"
map_rows = []
for bbox_name in selected_names:
obj = obj_map.get(bbox_name)
if obj is None:
continue
ox1, oy1, ox2, oy2 = obj.get("original_x1"), obj.get("original_y1"), obj.get("original_x2"), obj.get("original_y2")
if any(v is None for v in (ox1, oy1, ox2, oy2)):
continue
box = (max(0, int(ox1)), max(0, int(oy1)), max(0, int(ox2)), max(0, int(oy2)))
class_id = class_to_id[bbox_name]
crop_path = os.path.join(SILVER_CROP_DIR, f"{dicom_id}_{class_id}_0.png")
try:
crop_with_min_size(img, *box).save(crop_path)
except Exception as e:
return None, f"crop {dicom_id} {bbox_name}: {e}"
map_rows.append({
"image_path": img_path,
"class_name": bbox_name,
"split": split,
"crop_image_paths": [crop_path],
})
return map_rows, None
def run_silver():
os.makedirs(SILVER_CROP_DIR, exist_ok=True)
random.seed(SEED)
id_map = {}
for split_name, csv_name in [("training", "train.csv"), ("validation", "valid.csv"), ("test", "test.csv")]:
with open(os.path.join(SPLIT_DIR, csv_name), newline="") as f:
for row in csv.DictReader(f):
id_map[row["dicom_id"]] = (row["subject_id"], row["study_id"], split_name)
print(f"[silver] split mapping: {len(id_map)}")
sg_files = [fn for fn in os.listdir(SG_DIR) if fn.endswith("_SceneGraph.json")]
scan_args = [
(os.path.join(SG_DIR, fn), fn.replace("_SceneGraph.json", ""))
for fn in sg_files
if fn.replace("_SceneGraph.json", "") in id_map
]
print(f"[silver] scanning {len(scan_args)} JSONs...")
anatomy_to_images = defaultdict(list)
with Pool(NUM_WORKERS_SILVER) as pool:
for i, result in enumerate(pool.imap_unordered(scan_one_json, scan_args, chunksize=256)):
if result:
dicom_id, names = result
for name in names:
anatomy_to_images[name].append(dicom_id)
if (i + 1) % 50000 == 0:
print(f" scanned {i+1}/{len(scan_args)}")
n_anatomy = len(anatomy_to_images)
per_anatomy = TARGET_TOTAL // n_anatomy
print(f"[silver] anatomy types: {n_anatomy} per anatomy: {per_anatomy}")
image_selected = defaultdict(set)
for bbox_name, img_list in sorted(anatomy_to_images.items()):
n_sample = min(per_anatomy, len(img_list))
for dicom_id in random.sample(img_list, n_sample):
image_selected[dicom_id].add(bbox_name)
class_to_id = {name: idx for idx, name in enumerate(sorted(anatomy_to_images.keys()))}
tasks = []
for dicom_id, selected_names in image_selected.items():
subject_id, study_id, split = id_map[dicom_id]
img_path = os.path.join(MIMIC_DIR, f"p{subject_id[:2]}", f"p{subject_id}", f"s{study_id}", f"{dicom_id}.jpg")
sg_path = os.path.join(SG_DIR, f"{dicom_id}_SceneGraph.json")
tasks.append((dicom_id, img_path, sg_path, split, list(selected_names), class_to_id))
print(f"[silver] tasks: {len(tasks)} workers: {NUM_WORKERS_SILVER}")
records = []
errors = 0
with Pool(NUM_WORKERS_SILVER) as pool:
for i, (map_rows, err) in enumerate(
pool.imap_unordered(process_silver_image, tasks, chunksize=32), start=1
):
if err:
print(f" ERROR: {err}"); errors += 1
elif map_rows:
records.extend(map_rows)
if i % 10000 == 0:
print(f" [silver {i}/{len(tasks)}] errors={errors}")
print(f"[silver] done. records={len(records)} errors={errors}")
return records
def convert_record(record, image_root, crop_root):
img_path_rel = remove_root_prefix(record["image_path"], image_root)
crop_paths_rel = [remove_root_prefix(p, crop_root) for p in record.get("crop_image_paths", [])]
tgt_img_path = crop_paths_rel if len(crop_paths_rel) <= 1 else [crop_paths_rel]
return {
"qry_inst": "<|image_1|> Locate the specific region that corresponds to the provided text description.",
"qry_text": record["class_name"],
"qry_img_path": img_path_rel,
"tgt_inst": "Match the target",
"tgt_text": ["<|image_1|>\n"],
"tgt_img_path": tgt_img_path,
}
def deduplicate(data):
seen = set()
result = []
for s in data:
key = (s.get("qry_img_path", ""), s.get("qry_text", ""))
if key not in seen:
seen.add(key)
result.append(s)
removed = len(data) - len(result)
return result, removed
def sample_test_data(data, max_samples, seed=RANDOM_SEED):
if len(data) <= max_samples:
return data
rng = random.Random(seed)
class_to_samples = defaultdict(list)
for s in data:
class_to_samples[str(s.get("qry_text", "")).strip()].append(s)
for v in class_to_samples.values():
rng.shuffle(v)
class_names = list(class_to_samples.keys())
sampled = []
used_paths = set()
used_ids = set()
still_has = True
while still_has and len(sampled) < max_samples:
still_has = False
rng.shuffle(class_names)
for cls in class_names:
candidates = class_to_samples[cls]
if not candidates:
continue
still_has = True
chosen_idx = next(
(i for i, s in enumerate(candidates)
if s.get("qry_img_path") not in used_paths and id(s) not in used_ids),
None
)
if chosen_idx is None:
chosen_idx = next(
(i for i, s in enumerate(candidates) if id(s) not in used_ids), None
)
if chosen_idx is None:
continue
chosen = candidates.pop(chosen_idx)
sampled.append(chosen)
used_ids.add(id(chosen))
used_paths.add(chosen.get("qry_img_path", ""))
if len(sampled) >= max_samples:
break
if len(sampled) < max_samples:
remaining = [s for v in class_to_samples.values() for s in v if id(s) not in used_ids]
unique_r = [s for s in remaining if s.get("qry_img_path") not in used_paths]
dup_r = [s for s in remaining if s.get("qry_img_path") in used_paths]
rng.shuffle(unique_r); rng.shuffle(dup_r)
for s in unique_r + dup_r:
if len(sampled) >= max_samples:
break
sampled.append(s)
rng.shuffle(sampled)
return sampled[:max_samples]
def main():
gold_records = run_gold()
silver_records = run_silver()
test_data = [convert_record(r, TEST_IMAGE_ROOT, TEST_CROP_ROOT) for r in gold_records]
train_data = [convert_record(r, TRAIN_IMAGE_ROOT, TRAIN_CROP_ROOT) for r in silver_records]
rng = random.Random(RANDOM_SEED)
rng.shuffle(train_data)
rng.shuffle(test_data)
train_data, rm_train = deduplicate(train_data)
test_data, rm_test = deduplicate(test_data)
print(f"train dedup removed: {rm_train} remaining: {len(train_data)}")
print(f"test dedup removed: {rm_test} remaining: {len(test_data)}")
original_test_count = len(test_data)
test_data = sample_test_data(test_data, MAX_TEST_SAMPLES, RANDOM_SEED)
print(f"test samples: {original_test_count} -> {len(test_data)}")
for path, data in [(OUTPUT_TRAIN_JSON, train_data), (OUTPUT_TEST_JSON, test_data)]:
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
print(f"Saved: {path}")
if __name__ == "__main__":
main()
|