-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRAPNO_script.py
More file actions
2109 lines (1549 loc) · 87.1 KB
/
Copy pathRAPNO_script.py
File metadata and controls
2109 lines (1549 loc) · 87.1 KB
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
""" RAPNO project
This file contains the main function to run the RAPNO project on every datasets and every segmentation models
"""
## IMPORT LIBRARIES
import csv
import os
import pandas as pd
from sentry_sdk import ai
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import numpy as np
import shutil
import SimpleITK as sitk
from scipy.spatial.distance import cdist
from sympy import Point
from collections import namedtuple
from skimage.measure import find_contours
import nibabel as nib
from skimage.morphology import label
from tqdm import tqdm
import SimpleITK as sitk
import subprocess
from collections import defaultdict
from datetime import datetime
from skimage.measure import label
from matplotlib.patches import Patch
from matplotlib.cm import get_cmap
import ast
import torch
torch.cuda.empty_cache()
""" IMPORTANT INFO
We have 3 different csv files to work with:
- 3D volume dataset: it contains 3D volumes and pat_id (OUTPUT OF PIPELINE)
- 2D cross-sectional areas dataset: it contains 2D cross-sectional areas for all planes (axial, sagittal and coronal) or for the only one you specify, diameters,
pat_id and the slice number used to compute 2D cross-sectional areas (OUTPUT OF PIPELINE)
- clinical dataset: it contains the clinical info of patients (trial, pat_id, RT start date, RT end date,
Date of First Progression and total_scandates) (INPUT OF PIPELINE)
Please rename the variables in clinical dataset as specified below:
- trial: name of trial such as PNOC008 or PNOC022 (not necessary)
- pat_id: pat_id
- RT start date: RT_start_date
- RT end date: RT_end_date
- Date of First Progression: Progression_date (first progression after first period of RT)
- total_scandates: total_scandates (the date of scans you have available; available images and masks)
- tumor location: tumor_location (e.g pons, dipg....)
- sex: Sex
- Age:Age
total_scandates presents a list of dates for each patient as follows:
pat_id | total_scandates
1 | [date1 - date2 - date3 - ...]
scandates presented in the list are in the format: yyyymmdd
RT end and start dates are in the format: yyyy-mm-dd
PS: IF YOUR DATASET DOESN'T HAVE THIS FORMAT, PLEASE USE "normalize_columns" FUNCTION TO CHANGE THE NAMES OF THE COLUMNS
We will work with 3 images folders:
- segmented tumor mask (INPUT OF PIPELINE)
- Images (png) with drawing the contours and diameters (OUTPUT OF PIPELINE)
- Images overlapped: multiple semgented tumors mask overlap on a MRI (OUTPUT OF PIPELINE)
"""
"#################################################################################################################################################"
""" ########## PREPARE THE CSV DATASET ############# """
"#################################################################################################################################################"
import re
import re
import pandas as pd
def is_yyyymmdd_format(date_str):
"""Return True if string is in YYYYMMDD format."""
return bool(re.match(r"^\d{8}$", str(date_str)))
def reformat_date_str(val):
"""Convert a single date string to YYYYMMDD, leaving already-formatted or missing values alone."""
if pd.isna(val) or str(val).strip() in ("", "N/A"):
return None
val = str(val).strip()
if is_yyyymmdd_format(val):
return val
dt = pd.to_datetime(val, errors='coerce')
return dt.strftime("%Y%m%d") if pd.notna(dt) else None
def reformat_multi_date_str(val):
"""Handle total_scandates fields that may contain multiple dates joined by '-'."""
if pd.isna(val) or str(val).strip() in ("", "N/A"):
return None
parts = [p.strip() for p in str(val).split('-') if p.strip()]
formatted = [reformat_date_str(p) for p in parts]
formatted = [f for f in formatted if f is not None]
return "-".join(formatted) if formatted else None
def normalize_columns(dataset_path, final_dataset_path):
df = pd.read_csv(dataset_path, dtype={"pat_id": str})
# pat_id is already clean and separate from Trial in this dataset — no split needed.
if "pat_id" in df.columns:
df["pat_id"] = df["pat_id"].astype(str).str.strip()
# RT_start_date / RT_end_date: single date per row
if "RT_start_date" in df.columns:
df["RT_start_date"] = df["RT_start_date"].apply(reformat_date_str)
if "RT_end_date" in df.columns:
df["RT_end_date"] = df["RT_end_date"].apply(reformat_date_str)
# total_scandates: may contain multiple dates joined by "-"
if "total_scandates" in df.columns:
df["total_scandates"] = df["total_scandates"].apply(reformat_multi_date_str)
print('this', df.head())
df.to_csv(final_dataset_path, index=False)
return df
"#################################################################################################################################################"
""" #### CODE TO OVERLAP MASKS #### """
"#################################################################################################################################################"
"""
This code overlaps the segmentation masks on the MRI images and saves the resulting figures as PNG files in a folder.
You can decide wich MRI modality you want to use as background (T1w, T2w, FLAIR, etc.) by changing the variable "expected_image_prefix" in the function "save_masks_img".
"""
def _load_mask_dict(scan_list, mask_folder):
"""Load all masks into {scandate: np.ndarray}, including the latest."""
latest_scan_date, latest_mask, img = scan_list[-1]
mask_data_dict = {}
for scandate, mask in scan_list[:-1]:
mask_path = os.path.join(mask_folder, mask)
mask_data_dict[scandate] = nib.load(mask_path).get_fdata()
latest_mask_path = os.path.join(mask_folder, latest_mask)
mask_data_dict[latest_scan_date] = nib.load(latest_mask_path).get_fdata()
return mask_data_dict, img
def _extract_slice(volume, plane, slice_idx, orient_fn=None):
"""Extract a 2D slice from a 3D volume given a plane and index."""
if plane == 'axial':
slc = volume[:, :, slice_idx]
elif plane == 'sagittal':
slc = volume[slice_idx, :, :]
if orient_fn:
slc = orient_fn(slc)
elif plane == 'coronal':
slc = volume[:, slice_idx, :]
if orient_fn:
slc = orient_fn(slc)
else:
raise ValueError(f"Unknown plane: '{plane}'")
return slc
def save_masks_img(mask_folder, image_folder):
pat = {}
for mask in os.listdir(mask_folder):
if mask.endswith("_mask.nii.gz"):
basename = mask[:-7] # remove '.nii.gz'
id, scan, _ = basename.split("_")
if id not in pat:
pat[id]=[(scan, mask)]
else:
pat[id].append((scan, mask))
#print("pat", pat)
for id in pat:
pat[id] = sorted(pat[id], key=lambda x: x[0])
for id, scans in pat.items(): ## we are taking the image of more recent scan; so we can use as backgrund during the overlapping
# print(id, scans)
latest_scan_date, latest_mask = scans[-1]
#print(scans[-1])
expected_image_prefix = f"{id}_{latest_scan_date}_t1c" ## CHANGE IF WE WANT DIFFERENT MODALITY AS BACKGROUND
#print(expected_image_prefix)
matched_image = None
for img in os.listdir(image_folder):
if img.endswith(".nii.gz") and img.startswith(expected_image_prefix):
matched_image = img
#print(img)
break
pat[id][-1] = (latest_scan_date, latest_mask, matched_image) ## replace the last tuple with the new one
if matched_image is None:
print(f"[WARNING] No matching image found for patient {id}, "
f"scan {latest_scan_date} (expected prefix '{expected_image_prefix}')")
print(pat)
return pat
def orient_for_display(slice_2d):
rotated = np.rot90(slice_2d)
return rotated
def overlap_masks_img(pat, mask_folder, img_folder, output_folder, largest_slice_csv_path = None):
"""
Overlay segmentation masks on MRI images and save PNG figures.
With CSV → pairwise comparison (red = earlier, green = later)
using radiologist-selected slice and plane. it's the csv file obtained from the AI-RAPNO pipeline
Without CSV → one image per scan date, auto-selected axial slice.
"""
os.makedirs(output_folder, exist_ok=True)
slice_df = (
pd.read_csv(largest_slice_csv_path)
if largest_slice_csv_path is not None
else pd.DataFrame()
)
# Pre-format CSV columns once
if not slice_df.empty:
if 'total_scandates' not in slice_df.columns and 'scandate' in slice_df.columns:
slice_df = slice_df.rename(columns={'scandate': 'total_scandates'})
slice_df['pat_id'] = slice_df['pat_id'].astype(str).str.zfill(2)
slice_df['total_scandates'] = slice_df['total_scandates'].astype(str)
for patient_id, scan_list in pat.items():
mask_data_dict, img_file = _load_mask_dict(scan_list, mask_folder)
img_nii = nib.load(os.path.join(img_folder, img_file))
img_data = img_nii.get_fdata()
sorted_dates = sorted(mask_data_dict.keys())
patient_id_str = str(patient_id).zfill(2)
print(f"Patient {patient_id_str} — dates: {sorted_dates}")
# ── NO CSV + overlap just mask and 1 img: auto-selected axial slice ─────────
if slice_df.empty:
for scandate in sorted_dates:
mask = mask_data_dict[scandate]
_, slice_idx = get_valid_slice(mask, axis=2)
img_slice = img_data[:, :, slice_idx]
mask_slice = mask[:, :, slice_idx]
out_path = os.path.join(output_folder, f"{patient_id}_{scandate}.png")
scandate = datetime.strptime(scandate, "%Y%m%d").strftime("%Y-%m-%d")
plt.figure(figsize=(6, 6))
plt.imshow(img_slice, cmap='gray')
plt.imshow(m1_slice, cmap='Reds', alpha=0.6) ## previous one
legend_elements = [
Patch(facecolor='red', edgecolor='r', label=f'{scandate_1}'),
]
plt.legend(handles=legend_elements, fontsize=10, loc='lower right')
plt.title(f'{scandate_1}', fontsize=14)
plt.text(20, 20, f'Slice num: {slice_idx}', color='white', fontsize=12)
plt.axis('off')
out_name = f"{patient_id}_{scandate}.png"
out_path = os.path.join(output_folder, out_name)
plt.savefig(out_path, bbox_inches='tight')
plt.close()
# ── WITH CSV + overlap 2 masks and 1 img: pairwise comparison using radiologist slice ─────────────
else:
for scandate1, scandate2 in zip(sorted_dates[:-1], sorted_dates[1:]):
slice_row = slice_df[
(slice_df['pat_id'] == patient_id_str) &
(slice_df['total_scandates'].str.contains(scandate1))
]
if slice_row.empty:
print(f" No CSV row for {patient_id_str} / {scandate1} — skipping")
continue
row = slice_row.iloc[0]
slice_idx = int(row['pipeline_slice_number']) ## we are taking the slice number selected by AI-RAPNO pipeline
plane = row['pipeline_plane'].lower() ## use the plane selected by AI-RAPNO pipeline
try:
img_slice = _extract_slice(img_data, plane, slice_idx, orient_for_display)
m1_slice = _extract_slice(mask_data_dict[scandate1], plane, slice_idx, orient_for_display)
m2_slice = _extract_slice(mask_data_dict[scandate2], plane, slice_idx, orient_for_display)
except ValueError as e:
print(f" {e} — skipping {scandate1} vs {scandate2}")
continue
out_path = os.path.join(
output_folder, f"{patient_id}_{scandate1}_{scandate2}.png"
)
scandate_1 = datetime.strptime(scandate1, "%Y%m%d").strftime("%Y-%m-%d")
scandate_2 = datetime.strptime(scandate2, "%Y%m%d").strftime("%Y-%m-%d")
plt.figure(figsize=(6, 6))
plt.imshow(img_slice, cmap='gray')
plt.imshow(m1_slice, cmap='Reds', alpha=0.6) ## previous one
plt.imshow(m2_slice, cmap='Greens', alpha=0.5)
legend_elements = [
Patch(facecolor='red', edgecolor='r', label=f'{scandate_1}'),
Patch(facecolor='green', edgecolor='g', label=f'{scandate_2}')
]
plt.legend(handles=legend_elements, fontsize=10, loc='lower right')
plt.title(f'ID {patient_id}: {scandate_1} vs {scandate_2}', fontsize=14)
plt.text(20, 20, f'Slice num: {slice_idx}', color='white', fontsize=12)
plt.axis('off')
out_name = f"{patient_id}_{scandate1}_{scandate2}.png"
out_path = os.path.join(output_folder, out_name)
plt.savefig(out_path, bbox_inches='tight')
plt.close()
print(f"Saved overlay: {out_path}")
"#################################################################################################################################################"
""" #### MAIN FUNCTIONS TO COMPUTE 2D CROSS SECTIONAL AREA #### """
"#################################################################################################################################################"
## Eclidean /pairwise distance
class Point(namedtuple('Point', 'x y')):
__slots__ = ()
@property
def length(self):
return (self.x ** 2 + self.y ** 2) ** 0.5 #length from the origin
def __sub__(self, p):
return Point(self.x - p.x, self.y - p.y) #subtract self.x, self.y by coordinates of Point p
def __str__(self):
return 'Point: x=%6.3f y=%6.3f length=%6.3f' % (self.x, self.y, self.length)
#print the coordinates and the length of the Point
def compute_pairwise_distances(P1, P2, min_length=10): ## change and CHECK D!!!
"""
Compute pairwise Euclidean distances between points in P1 and P2,
filtering out pairs with distances below `min_length`.
Output is the pairwise matrix and a sorted list of distances
"""
#creates a 2D array where the element correlate with the location between the point from P1 and point from P2
# Compute Euclidean distance matrix
euc_dist_matrix = cdist(P1, P2, metric='euclidean')
#print(euc_dist_matrix)
indices = []
for x in range(euc_dist_matrix.shape[0]):
for y in range(euc_dist_matrix.shape[1]):
p1 = Point(*P1[x])
p2 = Point(*P2[y])
d = euc_dist_matrix[x, y]
# Skip if points are the same or below minimum distance threshold
if p1 != p2 or d > min_length:
#print(p1,p2,d)
indices.append([p1, p2, d]) ## d is in mm (as voxel is in mm)
# Sort valid indices by increasing distance
sorted_indices = sorted(indices, key=lambda x: x[2], reverse = True)
#print("Euclidean Distance Matrix:")
#print(euc_dist_matrix)
#print("\nSorted Pairs (Point1, Point2, Distance):")
for p1, p2, dist in sorted_indices:
printed = '({p1}, {p2}) -> Distance: {dist}'
# print(f"({p1}, {p2}) -> Distance: {dist}")
return euc_dist_matrix, sorted_indices
## Take the maximum distances and figure out if they are perpendicular
def interpolate(p1, p2, d):
"Interpolate-> create the lines creating a lot of points between p1 and p2"
#numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
if not np.isfinite(d) or d <= 0:
# print(f"Skipping interpolation: invalid distance {d} for points ({p1}, {p2})")
return [] # Return empty list if distance is invalid
X = np.linspace(p1.x, p2.x, int(round(d))).astype(int)
Y = np.linspace(p1.y, p2.y, int(round(d))).astype(int)
# Create unique points from X and Y coordinates
XY = np.asarray(list(set(zip(X, Y))))
return XY
def ccw(A,B,C):
"Counterwise order test--> to see if there is perpendicularity"
return (C.y-A.y) * (B.x-A.x) > (B.y-A.y) * (C.x-A.x)
def intersect(A,B,C,D):
"Check the intersection of 2 lines"
return ccw(A,C,D) != ccw(B,C,D) and ccw(A,B,C) != ccw(A,B,D)
def vector_norm(p):
"The length of vector"
length = p.length # Ensure this attribute exists in `p`
if length == 0:
return Point(0, 0) # Handle division by zero
else:
return Point(p.x / length, p.y / length) # Properly indented return
def max_distance(sorted_indices, img, tolerance):
#print(sorted_indices)
for i, (p1, p2, d1) in enumerate(sorted_indices):
# print("first diam", p2,p1,d1)
XY = interpolate(p1, p2, d1)
# print(XY)
intersections = sum(img[x, y] == 0 for x, y in XY) ## to see if we are considering background!
intersections_ratio = intersections / float(len(XY))
if intersections_ratio < 0.1:
V = vector_norm(Point(p2.x - p1.x, p2.y - p1.y)) ## length =1 because normalized
#print("v", V)
#print("check first pairs")
for j, (q1, q2, d2) in enumerate(sorted_indices[i:]):
dist_p1_q1 = np.sqrt((q1.x - p1.x) ** 2 + (q1.y - p1.y) ** 2) # Calculate distance between p1 and q1
if dist_p1_q1 < 10: # Skip if points are too close
# print("point to close!!")
continue
W = vector_norm(Point(q2.x - q1.x, q2.y - q1.y))
# print("W", W)
if abs(np.dot(V, W)) < tolerance:
XY = interpolate(q1, q2, d2)
intersections = sum(img[x, y] == 0 for x, y in XY)
intersections_ratio = intersections / float(len(XY))
# print("check second pairs")
if intersections_ratio < 0.1 and intersect(p1, p2, q1, q2): ##
#max_perpendicular_pair = (p1, p2, q1, q2)
#
#print(f"Perpendicular Pair Found: {p1}, {p2}, {q1}, {q2}") # print different points so good
return p1, p2, q1, q2
def get_neighbors(mask):
"Connectivity and filter points"
conn_comp = label(np.round(mask),connectivity=3).astype(float)
# print("connected", conn_comp)
## Empty and new mask
new_mask = np.zeros_like(mask)
# Loop through each connected component
for i in range(1,len(np.unique(conn_comp))): # Labels start from 1
# Create a mask for the current component
curr_mask = np.zeros(conn_comp.shape)
idx = np.where(conn_comp==np.unique(conn_comp)[i]) #index where the connected component mask equals the component of interest
curr_mask[idx] = 1.0
curr_mask = curr_mask.astype(int)
# print(curr_mask)
if curr_mask is None:
print('None',curr_mask)
new_mask[curr_mask == 1] = 1 # Mark the selected component as 1 in the new mask
return new_mask ##3D mask
def rapno_2D_area(max_perpendicular_pair, vox_x=1):
"Compute diameters and the final RAPNO measure"
p1,p2,q1,q2 = max_perpendicular_pair ## these are 4 points
rapno_measure = ((p2 - p1).length * (q2 - q1).length) * vox_x * vox_x
diam2= round((q2 - q1).length, 2)
diam1 = round((p2 - p1).length, 2)
return rapno_measure, diam1, diam2
def plot_contours(contours, lw=4, alpha=0.5):
"For contouring visualization"
for n, contour in enumerate(contours):
plt.plot(contour[:, 1], contour[:, 0], linewidth=lw, alpha=alpha, c='r')
def get_valid_slice(mask, axis): ## 0 for sagittal, 1 for coronal and 2 for axial
"## Select the slice for each slide. Images can have tumors at different slide."
"Take the slice with maximum number of pixel =1 (maximum area) "
# Order slices by descending lesion area (GIVE ME THE SLICE NUMBER OF EACH AREA)
area_sorted_ix = list(np.sum(mask, axis=(0, 1)).argsort()[::-1]) if axis == 2 else \
list(np.sum(mask, axis=(0, 2)).argsort()[::-1]) if axis == 1 else \
list(np.sum(mask, axis=(1, 2)).argsort()[::-1])
max_area = -1
for j in area_sorted_ix:
slice = mask.take(j, axis = axis)
area = np.sum(slice)
if area > max_area:
max_area = area
max_slice = slice
# print(type(max_slice), np.sum(slice), j)
return max_slice, j
def plot_contour_pixels(image, contours):
plt.imshow(image, cmap="gray")
for point in contours:
y, x = int(point[0]), int(point[1]) # Get pixel coordinates
plt.text(x, y, str(image[y, x]), color="red", fontsize=8, ha="center", va="center")
plt.title("Contour Area with Pixel Values")
plt.axis("off")
# plt.show()
def process_contours(plane_spec, slice_mask, plane, file, scandate, id, results_dict, vox_x=1, target_slice = None, current_slice = None):
"""Process contours and calculate diameters for a given plane."""
if slice_mask is None or np.all(slice_mask == 0):
#print(f"Skipping {file}: No segmentation found in {plane} plane.")
return
slice_mask[slice_mask == 2] = 0 ## edema ot count!!!
slice_mask[slice_mask == 1] = 255
slice_mask[slice_mask == 3] = 255
labeled_mask = label(np.round(slice_mask>0), connectivity=2).astype(float) ## LABEL FEATURES IN A IMAGE!!!
num_lesions = labeled_mask.max()
#print(labeled_mask, num_lesions)
color_map = get_cmap("tab10")
fig = plt.figure(figsize=(10, 10), frameon=False)
plt.margins(0, 0)
plt.gca().set_axis_off()
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())
background_image = None
if background_image is not None:
plt.imshow(background_image, cmap='gray')
else:
plt.imshow(slice_mask, cmap='gray')
results = []
text_y = 10
for lesion_id in range(1, int(num_lesions) + 1):
# Step 2: Extract the binary mask for this specific lesion
lesion_mask = (labeled_mask == lesion_id).astype(np.uint8) * 255
# print(lesion_mask)
contours = find_contours(lesion_mask, level=1) ## find the contours of the mask at each slide
# print("contours", contours)
if len(contours) == 0:
#print(f"No {plane} contours found for {file}")
return
#comb_contours = contours[0]
##for i in range(1,len(contours)):
# comb_contours = np.concatenate((comb_contours,contours[i]))
#combined_contours = comb_contours.astype(int)
combined_contours = np.concatenate(contours).astype(int)
#print(combined_contours)
euc_dist_matrix, ordered_diameters = compute_pairwise_distances(combined_contours, combined_contours) ## compute the pairwise matrix
#print(type(ordered_diameters))
result = max_distance(ordered_diameters, slice_mask, tolerance=0.1)
print("result for 1 lesion", result)
if result is None:
#print("Error: max_distance returned None. Unable to unpack values.")
# Handle the error case (e.g., continue to the next iteration, return early, or set default values)
p1, p2, q1, q2 = (None, None, None, None) # or any other appropriate default values
rapno_measure = None
diam1 = None
diam2 = None
results.append(("-", "-", "-"))
continue
else:
p1, p2, q1, q2 = result
diam1 = (p2 - p1).length
diam2 = (q2 - q1).length
diam1_cm = diam1/10
diam2_cm = diam2/10 # convert mm → cm
rapno_measure = diam1_cm * diam2_cm
if diam1_cm < 1 or diam2_cm < 1: ## NOT MEASURABLE
print("One of the 2 diamters is less than 1 cm, skipping this lesion.")
continue
#print("rapno measure", rapno_measure)
#rapno_measure, diam1, diam2 = rapno_2D_area(max_perp_points)
print("for 1 lesion", diam1_cm, diam2_cm, rapno_measure)
results.append((round(rapno_measure, 2), diam1_cm, diam2_cm))
### Save the mask with diameters and contours #####
color_d1 = color_map((2 * lesion_id - 1) % 10)
color_d2 = color_map((2 * lesion_id) % 10)
# Plot contours and diameters
plot_contours(contours, lw=1.5, alpha=1.0)
D1 = np.asarray([[p1.x, p2.x], [p1.y, p2.y]])
D2 = np.asarray([[q1.x, q2.x], [q1.y, q2.y]])
plt.plot(D1[1, :], D1[0, :], lw=2, c=color_d1, label=f'Lesion {lesion_id} D1: {round(diam1_cm, 2)} cm')
plt.plot(D2[1, :], D2[0, :], lw=2, c=color_d2, label=f'Lesion {lesion_id} D2: {round(diam2_cm, 2)} cm')
# Dynamically position text
plt.text(10, text_y, f'Lesion {lesion_id} RAPNO: {round(rapno_measure, 2)} cm²', fontsize=12, color='r')
text_y += 7
# if target_slice is not None:
# if current_slice != target_slice:
# plt.close()
# return results
filename = file[:-7]
output_file = f'{img_folder}/{filename}_{plane_spec}_{current_slice}.png'
plt.legend(fontsize = 16)
plt.savefig(output_file, bbox_inches='tight', pad_inches=0.0, dpi=100)
plt.close(fig)
print("results", results)
return results
"#################################################################################################################################################"
""" #### FUNCTION TO CREATE A CSV WITH LARGEST PERPENDICULAR DIAMETERS (D1, D2) AND AREA FOR EACH SLICE FOR EACH SCAN #### """
"#################################################################################################################################################"
"""
It saves the cross-sectional measurments for each slice of each scan per each plane (Sagittal, Coronal, Axial) in a CSV file.
Then It computes the largest perpendicular diameters and area among all scans and plane and saves them in a separate CSV file.
The final csv file has the lagest perpendicular diameters and area among slices and plane for each scan each scan.
"""
def compute_diameters_all_slices(plane_spec, mask, axis, file, scandate, id, vox_x=1):
"""
Returns:
dict of {slice_index: [(area_cm2, diameter1_cm, diameter2_cm), ...]} for each lesion
"""
from collections import defaultdict
results_dict = []
num_slices = mask.shape[axis]
filename_key = file[:-12] # match your key format
print(filename_key)
for slice_idx in range(num_slices):
# print("slices", filename_key, slice_idx, target_slice)
# if slice_idx != target_slice: ## WORK ONLY ON SLIDES YOU WANT!!
# continue
slice_mask = np.take(mask, slice_idx, axis=axis)
if np.sum(slice_mask) == 0:
continue ## Skip empty slices
# res = process_contours(slice_mask, plane, file, scandate, id, results_dict, vox_x=vox_x)
res = process_contours(plane_spec, slice_mask, plane, file, scandate, id, results_dict, vox_x=vox_x, target_slice = None, current_slice=slice_idx)
print("res", res)
if len(res) > 1:
# Check if any lesion is '-'
if any(t[0] == '-' for t in res):
continue
else:
# SAVE MULTIPLE AREAS all rapno_measure values safely
multiple_rapno_measure = " and ".join(str(t[0]) for t in res)
diam1_values = [str(t[1]) for t in res] # collect diam1s as strings
diam1_list = " and ".join(diam1_values)
diam2_values = [str(t[2]) for t in res] # collect diam1s as strings
diam2_list = " and ".join(diam2_values)
results_dict.append((multiple_rapno_measure, diam1_list, diam2_list, slice_idx))
elif len(res) == 1:
if res[0][0] != '-':
rapno_measure = float(res[0][0])
diam1 = float(res[0][1])
diam2 = float(res[0][2])
results_dict.append((rapno_measure, diam1, diam2, slice_idx))
return results_dict
def tumor_measurements_2d_all_slices(plane, folder_tumor, output_folder_2D, data_path):
##in case of no dataset skip these 2 lines
# if data_path is not None:
# data = pd.read_csv(data_path)
# total_scandates = sorted(data["total_scandates"].tolist()) # Ensure chronological order
default_keys = {
"Axial_area": [],
"Axial_d1": [],
"Axial_d2": [],
"Slice_number_Axial": [],
"Sagittal_area": [],
"Sagittal_d1": [],
"Sagittal_d2": [],
"Slice_number_Sagittal": [],
"Coronal_area": [],
"Coronal_d1": [],
"Coronal_d2": [],
"Slice_number_Coronal": [],
"Number_of_lesions": []}
results_dict = defaultdict(lambda: defaultdict(lambda: {k: [] for k in default_keys}))
# Loop over all files in the tumor folder
for file in os.listdir(folder_tumor):
# print(file)
if file.endswith("_mask.nii.gz"): ## CHANGE BASED ON HOW YOU CALL YOUR PREDICTIONS
filename = file[:-7]
# id, scandate = filename.split('_') # CHANGE THIS PART OF CODE IF YOU HAVE ADDED AN ADDITIONAL PART TO THE NAME
# trial, id, scandate, _ = filename.split('_')
id, scandate, _ = filename.split('_')
# print( id, scandate)
# id_full = f"{trial}_{id}" ## did it because i have the name of clinical trial
# results_dict[id]["trial"] = trial
# results_dict[id]["id_full"] = id_full
image_path = os.path.join(folder_tumor, file)
img_data = nib.load(image_path).get_fdata()
new_mask = get_neighbors(img_data) # Reduce the number of points of mask
#print("binary mask", np.unique(new_mask))
# Process the different planes
if plane == "Axial":
slice_results = compute_diameters_all_slices(plane, new_mask, 2, file, scandate, id, vox_x=1)
if slice_results and len(slice_results) > 0:
for slices in slice_results:
rapno_measure, diam1, diam2, num_slice = slices
print("slice", slices)
# Append diameters if valid, else "-"
if diam1 is not None and diam2 is not None:
if isinstance(diam1, (int, float)) and isinstance(diam2, (int, float)):
results_dict[id][scandate]["Axial_d1"].append(round(diam1, 2))
results_dict[id][scandate]["Axial_d2"].append(round(diam2, 2))
results_dict[id][scandate]["Slice_number_Axial"].append(num_slice)
elif isinstance(diam1, str) and isinstance(diam2, str):
results_dict[id][scandate]["Axial_d1"].append(diam1)
results_dict[id][scandate]["Axial_d2"].append(diam2)
results_dict[id][scandate]["Slice_number_Axial"].append(num_slice)
else:
results_dict[id][scandate]["Axial_d1"].append("-")
results_dict[id][scandate]["Axial_d2"].append("-")
results_dict[id][scandate]["Slice_number_Axial"].append("-")
else:
results_dict[id][scandate]["Axial_d1"].append("-")
results_dict[id][scandate]["Axial_d2"].append("-")
results_dict[id][scandate]["Slice_number_Axial"].append("-")
# Save total area sum separately if needed
results_dict[id][scandate]["Axial_area"].append(rapno_measure)
else:
results_dict[id][scandate]["Axial_area"].append("-")
results_dict[id][scandate]["Axial_d1"].append("-")
results_dict[id][scandate]["Axial_d2"].append("-")
results_dict[id][scandate]["Slice_number_Axial"].append("-")
results_dict[id][scandate]["Axial_area"] = "-"
elif plane == "Sagittal":
slice_results = compute_diameters_all_slices(plane, new_mask, 0, file, scandate, id, vox_x=1)
if slice_results and len(slice_results) > 0:
for slices in slice_results:
rapno_measure, diam1, diam2, num_slice = slices
if diam1 is not None and diam2 is not None:
if isinstance(diam1, (int, float)) and isinstance(diam2, (int, float)):
results_dict[id][scandate]["Sagittal_d1"].append(round(diam1, 2))
results_dict[id][scandate]["Sagittal_d2"].append(round(diam2, 2))
results_dict[id][scandate]["Slice_number_Sagittal"].append(num_slice)
elif isinstance(diam1, str) and isinstance(diam2, str):
results_dict[id][scandate]["Sagittal_d1"].append(diam1)
results_dict[id][scandate]["Sagittal_d2"].append(diam2)
results_dict[id][scandate]["Slice_number_Sagittal"].append(num_slice)
else:
results_dict[id][scandate]["Sagittal_d1"].append("-")
results_dict[id][scandate]["Sagittal_d2"].append("-")
results_dict[id][scandate]["Slice_number_Sagittal"].append("-")
else:
results_dict[id][scandate]["Sagittal_d1"].append("-")
results_dict[id][scandate]["Sagittal_d2"].append("-")
results_dict[id][scandate]["Slice_number_Sagittal"].append("-")
# Save total area sum separately if needed
results_dict[id][scandate]["Sagittal_area"].append(rapno_measure)
else:
results_dict[id][scandate]["Sagittal_area"].append("-")
results_dict[id][scandate]["Sagittal_d1"].append("-")
results_dict[id][scandate]["Sagittal_d2"].append("-")
results_dict[id][scandate]["Slice_number_Sagittal"].append("-")
results_dict[id][scandate]["Sagittal_area"] = "-"
elif plane == "Coronal":
slice_results = compute_diameters_all_slices(plane, new_mask, 1, file, scandate, id, vox_x=1)
if slice_results and len(slice_results) > 0:
for slice in slice_results:
rapno_measure, diam1, diam2, num_slice = slices
if diam1 is not None and diam2 is not None:
if isinstance(diam1, (int, float)) and isinstance(diam2, (int, float)):
results_dict[id][scandate]["Coronal_d1"].append(round(diam1, 2))
results_dict[id][scandate]["Coronal_d2"].append(round(diam2, 2))
results_dict[id][scandate]["Slice_number_Coronal"].append(num_slice)
elif isinstance(diam1, str) and isinstance(diam2, str):
results_dict[id][scandate]["Coronal_d1"].append(diam1)
results_dict[id][scandate]["Coronal_d2"].append(diam2)
results_dict[id][scandate]["Slice_number_Coronal"].append(num_slice)
else:
results_dict[id][scandate]["Coronal_d1"].append("-")
results_dict[id][scandate]["Coronal_d2"].append("-")
results_dict[id][scandate]["Slice_number_Coronal"].append("-")
else:
results_dict[id][scandate]["Coronal_d1"].append("-")
results_dict[id][scandate]["Coronal_d2"].append("-")
results_dict[id][scandate]["Slice_number_Coronal"].append("-")
# Save total area sum separately if needed
results_dict[id][scandate]["Coronal_area"].append(rapno_measure)
else:
results_dict[id][scandate]["Coronal_area"].append("-")
results_dict[id][scandate]["Coronal_d1"].append("-")
results_dict[id][scandate]["Coronal_d2"].append("-")
results_dict[id][scandate]["Slice_number_Coronal"].append("-")
results_dict[id][scandate]["Coronal_area"] = "-"
elif plane == "all":
#print("Axial", slice_mask_axial, num_slice_axial, "Coronal", slice_mask_coronal, num_slice_coronal, "Sagittal", slice_mask_sagittal, num_slice_sagittal)
planes = {
"Axial": (new_mask, 2),
"Sagittal": (new_mask, 0),
"Coronal": (new_mask, 1)
}
for p, (mask, axis) in planes.items():
slice_results = compute_diameters_all_slices(p, mask, axis, file, scandate, id, vox_x=1)
# print("result", result)
#if result is None or not None:
if slice_results and len(slice_results) > 0:
for slice in slice_results:
rapno_measure, diam1, diam2, num_slice = slice
if p == "Axial":
results_dict[id][scandate]["Axial_area"].append(rapno_measure)
if diam1 is not None and diam2 is not None:
if isinstance(diam1, (int, float)) and isinstance(diam2, (int, float)):
results_dict[id][scandate]["Axial_d1"].append(round(diam1, 2))
results_dict[id][scandate]["Axial_d2"].append(round(diam2, 2))
results_dict[id][scandate]["Slice_number_Axial"].append(num_slice)
elif isinstance(diam1, str) and isinstance(diam2, str):
results_dict[id][scandate]["Axial_d1"].append(diam1)
results_dict[id][scandate]["Axial_d2"].append(diam2)
results_dict[id][scandate]["Slice_number_Axial"].append(num_slice)