Stroke-ia commited on
Commit
6f78e96
·
verified ·
1 Parent(s): b71f9e4

Create test_model.py

Browse files
Files changed (1) hide show
  1. test_model.py +109 -0
test_model.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import torch
4
+ import nibabel as nib
5
+ import numpy as np
6
+ from pathlib import Path
7
+ import SimpleITK as sitk
8
+
9
+ # =======================
10
+ # CONFIG
11
+ # =======================
12
+ SAVE_DIR = "./results"
13
+ os.makedirs(SAVE_DIR, exist_ok=True)
14
+
15
+ MODEL_PATH = "model.best" # ton modèle entraîné
16
+
17
+ # =======================
18
+ # CHARGEMENT DU MODÈLE
19
+ # =======================
20
+ def load_model():
21
+ print("🔄 Chargement du modèle...")
22
+ model = torch.load(MODEL_PATH, map_location="cpu")
23
+ model.eval()
24
+ return model
25
+
26
+ # =======================
27
+ # PRÉPROCESSING
28
+ # =======================
29
+ def load_image(file_path):
30
+ ext = Path(file_path).suffix.lower()
31
+
32
+ if ext in [".nii", ".gz"]:
33
+ img = nib.load(file_path)
34
+ data = img.get_fdata()
35
+ affine = img.affine
36
+ return data, affine
37
+
38
+ elif ext == ".dcm":
39
+ itk_img = sitk.ReadImage(file_path)
40
+ data = sitk.GetArrayFromImage(itk_img)
41
+ affine = np.eye(4) # placeholder simple
42
+ return data, affine
43
+
44
+ else:
45
+ raise ValueError("❌ Format non supporté (seulement NIfTI ou DICOM).")
46
+
47
+ # =======================
48
+ # INFERENCE
49
+ # =======================
50
+ def run_inference(model, data):
51
+ data = (data - np.min(data)) / (np.max(data) - np.min(data) + 1e-8)
52
+ data_tensor = torch.tensor(data, dtype=torch.float32).unsqueeze(0).unsqueeze(0) # (B,C,H,W,D)
53
+
54
+ with torch.no_grad():
55
+ pred = model(data_tensor)
56
+ pred = torch.argmax(pred, dim=1).squeeze().cpu().numpy()
57
+ return pred
58
+
59
+ # =======================
60
+ # RAPPORT
61
+ # =======================
62
+ def generate_report(pred, save_path):
63
+ volume_total = np.prod(pred.shape)
64
+ volume_tumeur = np.sum(pred > 0)
65
+ ratio = (volume_tumeur / volume_total) * 100
66
+
67
+ report = [
68
+ "📄 RAPPORT MÉDICAL AUTOMATISÉ",
69
+ "-----------------------------------",
70
+ f"Dimensions de l'image : {pred.shape}",
71
+ f"Volume total voxels : {volume_total}",
72
+ f"Volume suspect tumeur : {volume_tumeur}",
73
+ f"Ratio suspect : {ratio:.2f} %",
74
+ "",
75
+ "⚠️ Rapport automatique à valider par un médecin."
76
+ ]
77
+
78
+ with open(save_path, "w", encoding="utf-8") as f:
79
+ f.write("\n".join(report))
80
+
81
+ print("\n".join(report))
82
+
83
+ # =======================
84
+ # MAIN
85
+ # =======================
86
+ if __name__ == "__main__":
87
+ if len(sys.argv) < 2:
88
+ print("❌ Utilisation : python test_model.py <chemin_fichier_IRM>")
89
+ sys.exit(1)
90
+
91
+ input_path = sys.argv[1]
92
+ print(f"📂 Fichier en entrée : {input_path}")
93
+
94
+ # Load
95
+ model = load_model()
96
+ data, affine = load_image(input_path)
97
+
98
+ # Inference
99
+ pred = run_inference(model, data)
100
+
101
+ # Save segmentation
102
+ out_seg_path = os.path.join(SAVE_DIR, "segmentation_pred.nii.gz")
103
+ nib.save(nib.Nifti1Image(pred.astype(np.uint8), affine), out_seg_path)
104
+ print(f"✅ Segmentation sauvegardée : {out_seg_path}")
105
+
106
+ # Save report
107
+ out_report_path = os.path.join(SAVE_DIR, "segmentation_report_detailed.txt")
108
+ generate_report(pred, out_report_path)
109
+ print(f"✅ Rapport sauvegardé : {out_report_path}")