-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnifti_generator.py
More file actions
58 lines (44 loc) · 1.84 KB
/
Copy pathnifti_generator.py
File metadata and controls
58 lines (44 loc) · 1.84 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
import os
import pydicom
import numpy as np
import nibabel as nib
# Charger et trier les fichiers DICOM
dossier = "./data"
fichiers = [
pydicom.dcmread(os.path.join(dossier, f))
for f in os.listdir(dossier) if f.endswith('.dcm')
]
fichiers.sort(key=lambda x: float(x.ImagePositionPatient[2]))
# Dimensions du volume dans le repere NumPy (Z, Y, X)
nz = len(fichiers)
ny, nx = fichiers[0].pixel_array.shape
print(f"Volume DICOM detecte : {nx}x{ny}x{nz} voxels (X x Y x Z)")
# Creation d'un masque 3D vide
masque_3d = np.zeros((nz, ny, nx), dtype=np.uint8)
# Definition des coordonnees du centre et des rayons de l'ellipse
cz, cy, cx = nz // 2, ny // 2, nx // 2
rz, ry, rx = max(2, nz // 6), ny // 8, nx // 8
# Generation d'une forme elliptique 3D au centre du volume
z, y, x = np.ogrid[:nz, :ny, :nx]
ell = ((z - cz)**2 / rz**2 + (y - cy)**2 / ry**2 + (x - cx)**2 / rx**2) <= 1
masque_3d[ell] = 1
# Passage du repere NumPy (Z, Y, X) au repere NIfTI (X, Y, Z)
masque_nifti_data = np.transpose(masque_3d, (2, 1, 0))
# Extraction securisee de la resolution spatiale
spacing_x, spacing_y = map(float, fichiers[0].PixelSpacing)
if nz > 1:
pos1 = float(fichiers[1].ImagePositionPatient[2])
pos0 = float(fichiers[0].ImagePositionPatient[2])
slice_thick = abs(pos1 - pos0)
else:
raw_thick = getattr(fichiers[0], 'SliceThickness', None)
slice_thick = float(raw_thick) if raw_thick not in (None, "") else 1.0
print(f"Voxel Spacing : {spacing_x:.2f}mm x {spacing_y:.2f}mm x "
f"{slice_thick:.2f}mm")
# Construction de la matrice d'orientation spatiale (Affine)
affine = np.diag([spacing_x, spacing_y, slice_thick, 1.0])
# Sauvegarde du masque au format NIfTI compresse
img_nifti = nib.Nifti1Image(masque_nifti_data, affine)
output_path = "masque_pancreas.nii.gz"
nib.save(img_nifti, output_path)
print(f"Masque NIfTI genere avec succes : {output_path}")