Team Ai
Apppublic

SusanneSchmid/Normalization_Histogram

sourceHugging Faceupdated 3y agoView on Hugging Face
0likes
app.py190 linesDownload Raw Back to root
1#____________________________________________________________
2#            August 2, 2023
3#____________________________________________________________
4import os
5import numpy as np
6import gradio as gr
7import SimpleITK as sitk
8import seaborn as sns
9import matplotlib.pyplot as plt
10
11def LoadImage(path_img):
12    try:
13        img_itk, voxel_size= Load_itk_image(path_img)
14    except FileNotFoundError:
15        print('ERROR: File not found', path_img)
16
17    img_numpy = sitk.GetArrayFromImage(img_itk[0])
18    img_load=img_numpy.transpose()
19
20    #remove background = 0
21    img_load[img_load==0]=np.nan
22
23    return img_load
24
25
26def Load_itk_image(path_img):
27    #Read header
28    file_reader = sitk.ImageFileReader()
29    file_reader.SetFileName(path_img)
30    file_reader.ReadImageInformation()
31    dim_total = file_reader.GetSize()
32    img_vol_ITK = []
33
34    if len(dim_total)==4:
35        dim_vol = (dim_total[0:3])
36        # make volume for all images
37        img_load_all = sitk.ReadImage(path_img, sitk.sitkFloat32)
38
39        img_vol_ITK = []
40        for vol_n in range(dim_total[3]):
41            #Extract vol out of object
42            size = list(dim_total)
43            size[3] = 0
44            index = [0,0,0,vol_n]
45            extractor = sitk.ExtractImageFilter()
46            extractor.SetSize(size)
47            extractor.SetIndex(index)
48
49            img_vol_ITK.append(extractor.Execute(img_load_all))
50
51    else:
52        img_ITK = sitk.ReadImage(path_img, sitk.sitkFloat32)
53        img_vol_ITK.append(img_ITK)
54        dim_vol = dim_total
55
56    #Voxelsize in mm. forth dimension has no meaning in spacing.
57    voxel_size = img_vol_ITK[0].GetSpacing()
58    return  img_vol_ITK, voxel_size
59
60
61
62def NormalizeMinMax(img):
63    #Normalization for Volumes
64    minVal = np.nanmin(img)
65    maxVal = np.nanmax(img)
66 
67    img_normalized = (img - minVal)*(1/(maxVal- minVal))
68    return img_normalized
69
70def NormalizePercentile(img, minP, maxP):
71    #Normalization for Volumes
72    minVal = np.nanpercentile(img, minP)
73    maxVal = np.nanpercentile(img, maxP)
74    img_normalized = (img - minVal)*(1/(maxVal- minVal))
75    return img_normalized
76
77def NormalizeZScore(img):
78    #Normalization for Volumes
79    meanVal = np.nanmean(img)
80    stdVal = np.nanstd(img)
81     
82    img_normalized = (img-meanVal)*(1/stdVal)
83    
84    return img_normalized
85 
86
87def PrepImage(pathName):
88      
89     
90    img_load = LoadImage(pathName)
91    img_normalized = NormalizeMinMax(img_load)
92    img_normalized_per =NormalizePercentile(img_load, 10, 90)
93    img_normalized_per98 =NormalizePercentile(img_load, 2, 98)
94    img_normalized_zscore= (NormalizeZScore(img_load) ) 
95
96    return img_load.flatten(),img_normalized.flatten(),img_normalized_per.flatten(),img_normalized_zscore.flatten(), img_normalized_per98.flatten()
97
98
99
100
101def Norm_image(vol_path,normalization_technique):
102
103    imglist = []
104    imgClist=[]
105    imgNlist=[]
106    imgNPlist=[]
107    imgNZlist=[]
108    imgNPer98list=[]
109    print(len(vol_path))
110    for file in vol_path:
111        pathName = file.name
112
113        img_load = LoadImage(pathName)
114        imglist.append(img_load.flatten())
115          
116
117        if 'MinMax' in normalization_technique:
118            imgNlist.append(NormalizeMinMax(img_load).flatten())
119        
120        if 'Z-Score' in normalization_technique:
121            imgNZlist.append(NormalizeZScore(img_load).flatten())
122        
123        if 'Percentile (2th - 98th)'in normalization_technique:
124            imgNPer98list.append(NormalizePercentile(img_load, 2, 98).flatten())
125            
126        if 'Percentile (10th - 90th)' in normalization_technique:
127            imgNPlist.append(NormalizePercentile(img_load, 10, 90).flatten())
128
129    gr.Info('The volumes are loaded succesfully and different normalization techniques are calculated.')   
130
131    log_scale = False
132    plt.figure(11)
133    fig, ax = plt.subplots(1,1)
134    for i, file in enumerate(vol_path):
135        sns.histplot(data=imglist[i].flatten(), kde=False, label=os.path.basename(file.name)[0:25], log_scale=log_scale,element="step", fill=False,bins=500,legend=True).set(title='Original')
136    ax.legend()
137    plt.savefig("Original.png")
138    plots=["Original.png"]
139    
140    if 'MinMax' in normalization_technique:
141        fig, ax = plt.subplots(1,1)
142        for i, file in enumerate(vol_path):
143            sns.histplot(data=imgNlist[i].flatten(), kde=False, label=os.path.basename(file.name)[0:25], log_scale=log_scale,element="step", fill=False,bins=500,legend=True).set(title='Min-Max')
144        ax.legend()
145        plt.savefig("MinMax.png")
146        plots.append("MinMax.png")
147            
148    if 'Z-Score' in normalization_technique:
149        fig, ax = plt.subplots(1,1)
150        for i, file in enumerate(vol_path):
151            sns.histplot(data=imgNZlist[i].flatten(), kde=False, label=os.path.basename(file.name)[0:25], log_scale=log_scale,element="step", fill=False,bins=500,legend=True).set(title='Z-Score')
152        ax.legend()
153        plt.savefig("Zscore.png")
154        plots.append("Zscore.png")
155        
156
157    if 'Percentile (2th - 98th)'in normalization_technique:
158        fig, ax = plt.subplots(1,1)
159        for i, file in enumerate(vol_path):
160            sns.histplot(data=imgNPer98list[i].flatten(), kde=False, label=os.path.basename(file.name)[0:25], log_scale=log_scale,element="step", fill=False,bins=500,legend=True).set(title='Percentile 2-98')
161        ax.legend()
162        plt.savefig("Per98.png")
163        plots.append("Per98.png")
164
165    if 'Percentile (10th - 90th)' in normalization_technique:
166        fig, ax = plt.subplots(1,1)
167        for i, file in enumerate(vol_path):
168            sns.histplot(data=imgNPlist[i].flatten(), kde=False, label=os.path.basename(file.name)[0:25], log_scale=log_scale,element="step", fill=False,bins=500,legend=True).set(title='Percentile 10 - 90')
169        ax.legend()
170        plt.savefig("Per90.png")
171        plots.append("Per90.png")
172        
173
174
175    return plots
176
177
178description = 'You can upload mutiple image volumes (recommonded 3-5). The files get read by ITK so mulitple different file formats are possible (e.g. *.nii , *.nii.gz, jpeg,..). You need to wait until the data is uploaded. \
179    Once pressing submit the histograms for multiple normalization techniques are calculated. Depending on file size and selected techniques it might take a while to do the calculations. \
180          \n The uploaded data is not stored and is deleted once the window is closed. '
181
182inputs = [gr.File(file_count="multiple", label=None),gr.CheckboxGroup(["MinMax", "Z-Score", "Percentile (2th - 98th)", "Percentile (10th - 90th)"])]
183demo = gr.Interface(fn=Norm_image,
184             inputs=inputs,
185             outputs=[gr.Gallery(label="Profiling Dashboard")], #.style(grid=(2,3))],
186             description=description,
187             )
188             
189demo.launch().queue()
190