Skip to content

Commit 6ad12ec

Browse files
committed
bug fixes
1 parent bdca70e commit 6ad12ec

File tree

6 files changed

+152
-7
lines changed

6 files changed

+152
-7
lines changed

TPTBox/core/np_utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ def np_unique(arr: np.ndarray) -> list[int]:
145145
return [idx for idx, i in enumerate(cc3dstatistics(arr)["voxel_counts"]) if i > 0]
146146
except Exception:
147147
pass
148-
return [i for i in np.unique(arr) if i > 0]
148+
return list(np.unique(arr))
149149

150150

151151
def np_unique_withoutzero(arr: UINTARRAY) -> list[int]:
@@ -1336,7 +1336,7 @@ def _pad_to_parameters(
13361336

13371337
def _to_labels(arr: np.ndarray, label_ref: LABEL_REFERENCE = None) -> Sequence[int]:
13381338
if label_ref is None:
1339-
label_ref = list(np_unique(arr))
1339+
label_ref = list(np_unique_withoutzero(arr))
13401340
if not isinstance(label_ref, Sequence):
13411341
label_ref = [label_ref]
13421342
return label_ref

TPTBox/stitching/stitching.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -98,11 +98,11 @@ def get_max_affine_and_shape(points: np.ndarray, affines, min_spacing=None, dtyp
9898

9999
new_spacing = np.min(np.round(np.stack(spacings), decimals=6), 0)
100100
if min_spacing is not None and min_spacing != 0:
101-
new_spacing = np.array([max(min_spacing, s) for s in new_spacing])
101+
new_spacing = np.maximum(min_spacing, new_spacing)
102102

103103
shape: np.ndarray = np.ceil(min_shape / new_spacing)
104104
print("Choose the following spacing:", new_spacing) if verbose else None
105-
print(f"Output shape is {shape}, which utilizes {min_possible_volume / min_volume*100:.1f} % of all voxels.") if verbose else None
105+
print(f"Output shape is {shape}, which utilizes {min_possible_volume / min_volume * 100:.1f} % of all voxels.") if verbose else None
106106
affine = get_ras_affine(min_rotation, new_spacing, origen[0])
107107
print("The new origin is ", np.round(affine[:3, 3], 2)) if verbose else None
108108
print("The optimal rotation came from file number ", opt_id, " ", np.round(min_rotation.reshape(-1), 2)) if verbose else None
@@ -340,7 +340,7 @@ def main( # noqa: C901
340340
niis: list[nib.nifti1.Nifti1Image] = []
341341
print("### loading ###") if verbose else None
342342
for f_name in images:
343-
if isinstance(f_name, (Path , str)):
343+
if isinstance(f_name, (Path, str)):
344344
print("Load ", f_name, Path(f_name)) if verbose else None
345345
# Load Nii
346346
nii: nib.nifti1.Nifti1Image = nib.load(f_name) # type: ignore
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
import os
2+
from pathlib import Path
3+
4+
import pandas as pd
5+
from tqdm import tqdm
6+
7+
from examples.dicom_select.a03_totalspineseg import black_list
8+
from TPTBox import BIDS_Family, BIDS_Global_info, Print_Logger, calc_poi_from_subreg_vert, to_nii
9+
from TPTBox.core.bids_constants import formats
10+
from TPTBox.spine.snapshot2D import snapshot
11+
12+
13+
def update_poi_and_snp(fam: BIDS_Family, f, new_vert=None, override=False, poi_not_younger=True):
14+
try:
15+
new_vert = new_vert or fam["msk_seg-vert"][0]
16+
except KeyError:
17+
return
18+
19+
subreg = fam.get("msk_seg-subreg", fam.get("msk_seg-spine"))[0] # type: ignore
20+
p = fam[f][0]
21+
path = p.get_nii_file()
22+
if path is None:
23+
return
24+
snp_paths = p.get_changed_path(
25+
"png",
26+
bids_format="snp",
27+
parent="derivative-spineps",
28+
info={"seg": "spine", "mod": p.format, "ovl": None},
29+
non_strict_mode=False,
30+
make_parent=False,
31+
)
32+
poi_path = p.get_changed_path(
33+
"json",
34+
bids_format="ctd",
35+
parent="derivative-spineps",
36+
info={"seg": "spine", "mod": p.format, "ovl": None},
37+
non_strict_mode=False,
38+
make_parent=False,
39+
)
40+
41+
if not override and poi_path.exists() and snp_paths.exists() and poi_not_younger:
42+
ref_mtime = os.path.getmtime(path)
43+
if os.path.getmtime(poi_path) >= ref_mtime and os.path.getmtime(snp_paths) >= ref_mtime:
44+
return
45+
poi = calc_poi_from_subreg_vert(new_vert, subreg, subreg_id=[40, 50])
46+
poi.save(poi_path) # type: ignore
47+
snapshot(p, new_vert, poi_path, subreg, out_path=snp_paths, mode="CT" if f == "ct" else "MRI")
48+
49+
50+
# totalspineseg INPUT_FOLDER/ OUTPUT_FOLDER/ --step1 -k step1_levels step1_vert
51+
def do_update_cdt_via_canada(bgi: BIDS_Global_info, select_xlsx_path: Path):
52+
if not select_xlsx_path.exists():
53+
return
54+
df_select = pd.read_excel(select_xlsx_path, dtype={"FileID": str})
55+
# exit()
56+
t = tqdm(bgi.iter_subjects())
57+
for sub, subj in t:
58+
t.desc = f"update cdt by {select_xlsx_path.name}; Subject {sub}"
59+
q = subj.new_query(flatten=True)
60+
q.filter_dixon_only_inphase()
61+
q.unflatten()
62+
for fam in q.loop_dict():
63+
for f in formats:
64+
if f in fam:
65+
if f in black_list:
66+
continue
67+
update_poi_and_snp(fam, f, override=False)
68+
for fam in q.loop_dict():
69+
try:
70+
poi_path = fam["ctd_seg-subreg"][0] if "ctd_seg-subreg" in fam else fam["ctd_seg-spine"][0]
71+
except KeyError:
72+
poi_path = None
73+
if poi_path is None:
74+
continue
75+
for f in formats:
76+
if f in fam:
77+
p = fam[f][0]
78+
selected_row = df_select[df_select["FileID"] == p.BIDS_key]
79+
if selected_row.empty:
80+
continue
81+
# selected_row_dict = selected_row.to_dict(orient="records")[0]
82+
83+
update_canada = selected_row["vert_brocken_try_canada"].to_numpy()[0]
84+
update_canada = None if pd.isna(update_canada) else (update_canada) # type: ignore
85+
if update_canada is not None:
86+
subreg = fam["msk_seg-subreg"][0] if "msk_seg-subreg" in fam else fam["msk_seg-spine"][0]
87+
88+
out = subreg.get_changed_path(parent=subreg.parent, info={"seg": "vert", "desc": "canada"})
89+
if out.exists():
90+
# if "msk_seg-vert" in fam and len(fam["msk_seg-vert"]) != 1:
91+
# print("remap", fam)
92+
# file = fam["msk_seg-vert"][0]
93+
# if file.get("desc") == "canada":
94+
# file = fam["msk_seg-vert"][1]
95+
# file = file.get_nii_file()
96+
# assert file is not None
97+
# file.rename(str(file).replace("vert_msk.", "vert_backup."))
98+
# print("rename", str(file), "to", str(file).replace("vert_msk.", "vert_backup."))
99+
# # exit()
100+
101+
continue
102+
# vert =
103+
poi_path = fam["ctd_seg-subreg"][0] if "ctd_seg-subreg" in fam else fam["ctd_seg-spine"][0]
104+
105+
vert_canada = subreg.get_changed_path(
106+
bids_format="msk",
107+
info={"seg": "vert", "desc": "totalspineseg", "mod": p.bids_format},
108+
parent="derivative-canada",
109+
)
110+
vert_c = to_nii(vert_canada, True)
111+
if subreg.get("mod") == "ct":
112+
vert_c[vert_c >= 60] = 0
113+
vert_c[vert_c >= 61] = 0
114+
vert_c[vert_c >= 100] = 0
115+
new_vert = subreg.open_nii().clamp(0, 1) * vert_c
116+
new_vert.save(subreg.get_changed_path(parent=subreg.parent, info={"seg": "vert", "desc": "canada"}))
117+
if "msk_seg-vert" in fam:
118+
file = fam["msk_seg-vert"][0].get_nii_file()
119+
assert file is not None
120+
file.rename(str(file).replace("vert_msk.", "vert_backup."))
121+
update_poi_and_snp(fam, f, new_vert, override=True)
122+
123+
124+
if __name__ == "__main__":
125+
dataset_path = Path("/DATA/NAS/datasets_source/dataset-MRCT-Spine/MR-CT-Spine/dataset-MRCT-Spine")
126+
parent_in = ["sourcedata2", "derivative-spineps"]
127+
parent_out = "sourcedata3"
128+
info_folder = "info"
129+
130+
dataset_path = Path("/DATA/NAS/datasets_processed/MRI_spine/dataset-SpineGAN")
131+
dataset_name = Path(dataset_path).name
132+
parent_in = ["rawdata", "derivative-spineps"]
133+
t13_vertebra_are_a_lie = True
134+
# parent_out = "sourcedata3"
135+
update_cdt_via_reference = False
136+
137+
select_xlsx = dataset_name + "_select.xlsx"
138+
139+
select_xlsx_path = (dataset_path) / info_folder / select_xlsx
140+
# random.seed(42)
141+
log = Print_Logger()
142+
bgi = BIDS_Global_info([dataset_path], parents=parent_in)
143+
# filter_dataset(bgi)
144+
do_update_cdt_via_canada(bgi, select_xlsx_path)
145+
################

examples/registration/IVD_transfer/__init__.py

Whitespace-only changes.

examples/registration/IVD_transfer/transfare_spine_seg.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import os
44
import pickle
5+
import random
56
from collections.abc import Sequence
67

78
# Step 1
@@ -373,8 +374,6 @@ def register_IVD_to_ct(vert: Image_Reference):
373374
return a
374375

375376

376-
import random
377-
378377
j = 0
379378
if __name__ == "__main__":
380379
for r in [

examples/registration/atlas_poi_transfer_leg/example.ipynb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
"%load_ext autoreload\n",
5151
"%autoreload 2\n",
5252
"import os\n",
53+
"\n",
5354
"os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"3\"\n"
5455
]
5556
},

0 commit comments

Comments
 (0)