-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Temporal analysis of MS lesions #40
Draft
plbenveniste
wants to merge
26
commits into
main
Choose a base branch
from
plb/nnunet
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 15 commits
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
8739639
Added folder for nnunet experiment
c495a26
Formatting
cfe61fd
added code to crop img along sc
plbenveniste 24bcb0c
script for seg of full dataset
plbenveniste 919477f
modified seg and crop algo
plbenveniste 926078d
edited qc for seg and crop
plbenveniste 8b8e1a9
lesion clustering accross slides
plbenveniste 65138b0
removed unused files for seg and crop of lesion
plbenveniste fc33182
created file to compare two time point
plbenveniste db106a4
modified lesion time point comparison
plbenveniste 511c168
trying to register M0 to M12
plbenveniste 6e70cb1
problem with registration with vert levels
plbenveniste 86a77d9
registration and lesion matching
plbenveniste 51374e1
need to fix the identification of lesions accross files
plbenveniste 7188349
first working version of lesion comparison
plbenveniste c63ba5f
formatting of script
plbenveniste b195245
data analysis of canproco
plbenveniste c9ab813
added healthy control analysis
plbenveniste 11a1f5b
modified to select wanted contrast
plbenveniste ee3e865
added image of poor quality
plbenveniste af03d7e
removed useless line
plbenveniste 4b7d247
extract labeled slices and convert to nnunet format
plbenveniste 6406dac
renamed file to explain conversion to nnunet format
plbenveniste accea6e
extract slice and sc_seg for region-based training
plbenveniste f18e846
finished file for sc seg, slice extraction and conversion to nnunet f…
plbenveniste cf8ca41
code for sc seg on 3d and conversion to nnunet format
plbenveniste File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,150 @@ | ||
""" | ||
In this file we analyse the results of the segmentation of the MS lesion on the spinal cord. | ||
The objective is to output the number of lesions segmented on the spinal cord for each patient. | ||
Also, we want to output the segmentation file of the lesions in different color | ||
|
||
Usage: | ||
python3 lesion_seg_analysis.py -i <input_image> -seg <segmentation> -o <output_folder> | ||
python3 canproco/lesion_analysis/lesion_seg_analysis.py -i ./data/lesion_comparison/sub-cal072_ses-M12_STIR.nii.gz -seg ./data/lesion_comparison/canproco_003.nii.gz -o ./data/lesion_comparison/output | ||
|
||
Args: | ||
-i/--input_image: path to the image | ||
-seg/--segmentation: path to the segmentation | ||
-o/--output_folder: path to the output folder | ||
--plot: whether to plot the results or not | ||
|
||
Returns: | ||
None | ||
|
||
Todo: | ||
* | ||
|
||
Pierre-Louis Benveniste | ||
""" | ||
|
||
import os | ||
import argparse | ||
from pathlib import Path | ||
import nibabel as nib | ||
import numpy as np | ||
import matplotlib.pyplot as plt | ||
from sklearn.cluster import DBSCAN | ||
|
||
def get_parser(): | ||
""" | ||
This function parses the arguments given to the script. | ||
|
||
Args: | ||
None | ||
|
||
Returns: | ||
parser: parser containing the arguments | ||
""" | ||
|
||
parser = argparse.ArgumentParser(description='Analyse the results of the segmentation of the MS lesion on the spinal cord.') | ||
parser.add_argument('-i', '--input_image', required=True, | ||
help='Path to the image') | ||
parser.add_argument('-seg', '--segmentation', required=True, | ||
help='Path to the segmentation') | ||
parser.add_argument('-o', '--output_folder', required=True, | ||
help='Path to the output folder') | ||
parser.add_argument('--plot', action='store_true', | ||
help='Whether to plot the results or not') | ||
return parser | ||
|
||
plbenveniste marked this conversation as resolved.
Show resolved
Hide resolved
|
||
def main(): | ||
""" | ||
This function is the main function of the script. | ||
|
||
Args: | ||
None | ||
|
||
Returns: | ||
None | ||
""" | ||
#get the parser | ||
parser = get_parser() | ||
args = parser.parse_args() | ||
|
||
#load image | ||
img = nib.load(args.input_image) | ||
img_data = img.get_fdata() | ||
|
||
#load segmentation | ||
seg = nib.load(args.segmentation) | ||
seg_data = seg.get_fdata() | ||
|
||
#perform clustering on the entire segmentation volume | ||
##first we modify the seg data | ||
X = [] | ||
Y = [] | ||
Z = [] | ||
for x in range(seg_data.shape[0]): | ||
for y in range(seg_data.shape[1]): | ||
for z in range(seg_data.shape[2]): | ||
if seg_data[x,y,z] != 0: | ||
X.append(x) | ||
Y.append(y) | ||
Z.append(z) | ||
coords = np.stack((X,Y,Z), axis=1) | ||
|
||
##then we perform the clustering using DBSCAN | ||
db = DBSCAN(eps=10, min_samples=5).fit(coords) | ||
core_samples_mask = np.zeros_like(db.labels_, dtype=bool) | ||
core_samples_mask[db.core_sample_indices_] = True | ||
labels = db.labels_ | ||
# Number of clusters in labels, ignoring noise if present. | ||
n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0) | ||
|
||
print('Estimated number of clusters: %d' % n_clusters_) | ||
|
||
plot = args.plot | ||
if plot: | ||
#build color dictionnary | ||
colors = {} | ||
for i in range(n_clusters_): | ||
colors[i] = np.random.rand(3,) | ||
colors[-1] = [0,0,0] | ||
|
||
#plot the clusters for each slice | ||
fig, axs = plt.subplots(ncols=seg_data.shape[2], nrows=1,figsize=(20,3)) | ||
for i in range(seg_data.shape[2]): | ||
slice_coords = coords[coords[:,2] == i] | ||
slice_labels = labels[coords[:,2] == i] | ||
axs[i].scatter(slice_coords[:,0], slice_coords[:,1], color=[colors[x] for x in slice_labels]) | ||
# plt.savefig(os.path.join(args.output_folder, f'cluster_slice_{i}.png')) | ||
# plt.close() | ||
axs[i].set_xlim(0,seg_data.shape[0]) | ||
axs[i].set_ylim(0,seg_data.shape[1]) | ||
plt.show() | ||
|
||
#saving the results in a nifti file | ||
#first we create the new segmentation | ||
new_seg_data = np.zeros_like(seg_data) | ||
for i in range(len(labels)): | ||
new_seg_data[coords[i,0], coords[i,1], coords[i,2]] = labels[i] + 1 | ||
#then we save it | ||
new_seg = nib.Nifti1Image(new_seg_data, seg.affine, seg.header) | ||
nib.save(new_seg, os.path.join(args.output_folder, 'clustered_seg.nii.gz')) | ||
|
||
#for each lesion calculate volume and get center | ||
##first we get the volume of one voxel | ||
voxel_volume = np.prod(seg.header.get_zooms()) | ||
##then we get the volume of each lesion and its center | ||
lesion_volumes = [] | ||
lesion_centers = [] | ||
for i in range(n_clusters_): | ||
lesion_volumes.append(len(labels[labels == i])*voxel_volume) | ||
lesion_centers.append(np.mean(coords[labels == i], axis=0)) | ||
|
||
#save the results in a text file | ||
with open(os.path.join(args.output_folder, 'lesion_analysis.txt'), 'w') as f: | ||
f.write(f'Number of lesions: {n_clusters_}\n') | ||
f.write('Volume and center of each lesion (mm3):\n') | ||
for i in range(n_clusters_): | ||
f.write(f'Lesion {i+1} : volume: {round(lesion_volumes[i],2)} mm3, center: {lesion_centers[i]}\n') | ||
return None | ||
|
||
if __name__ == '__main__': | ||
main() | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
apparently this file is not used anymore-- so, consider removing. Also, consider discussing why not using
sct_analyse_lesion
. And if the SCT function has issues (eg: slow, etc.), consider modifyingsct_analyse_lesion
instead.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Also see #38 (comment)