Spaces:
Sleeping

File size: 10,334 Bytes
8e53b90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6646720
8e53b90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import gradio as gr
import pydicom
import numpy as np
import matplotlib.pyplot as plt

# Image to K-space Conversion via FFT Functions & Vice-versa
def fft2c(image):
    """ Computes the centered 2D FFT of an image in NumPy. """
    return np.fft.fftshift(np.fft.fft2(np.fft.ifftshift(image, axes=(-2, -1))), axes=(-2, -1))

def ifft2c(kspace):
    """ Computes the centered 2D IFFT of k-space data using NumPy. """
    return np.fft.ifftshift(np.fft.ifft2(np.fft.fftshift(kspace, axes=(-2, -1))), axes=(-2, -1))

# Function to process the DICOM file
def dicomMatrix(path, apply_rescale=True):
    ds = pydicom.dcmread(path)
    arr = ds.pixel_array.astype(np.float32)  # 2D for single-slice images

    # Apply HU/intensity rescale if present (common for CT)
    if apply_rescale and hasattr(ds, "RescaleSlope") and hasattr(ds, "RescaleIntercept"):
        arr = arr * float(ds.RescaleSlope) + float(ds.RescaleIntercept)
    return arr, ds

# Function to display the DICOM image
def show_dicom_image(dicom_file):
    # Load and process the DICOM file
    M, ds = dicomMatrix(dicom_file.name)

    # Display the DICOM image
    plt.figure(figsize=(8, 8))
    plt.imshow(M, cmap='gray')
    plt.title("DICOM Image")
    plt.axis("off")

    # Return the image plot as output
    return plt

# Function to create the low-pass filter
def createLowPass(shape, cutoff_radius):
    """ Create a 2D low-pass filter mask based on the cutoff radius. """
    y, x = np.indices(shape)
    center = np.array(shape) // 2
    dist_sq = (x - center[1])**2 + (y - center[0])**2
    lowPassFilter = np.where(dist_sq <= cutoff_radius**2, 1, 0)
    return lowPassFilter

# Low-pass filter function
def lowFilter(MRIsam, cutoff_radius):
    """Computes the 2D FFT, applies a low-pass filter, and reconstructs the image."""
    lowPassFilter = createLowPass(MRIsam.shape, cutoff_radius)
    kspMRI = fft2c(MRIsam)
    kspMRI_L = kspMRI * lowPassFilter
    spaMRI_L = np.abs(ifft2c(kspMRI_L))
    return kspMRI, kspMRI_L, spaMRI_L

# High-pass filter function
def highFilter(MRIsam, cutoff_radius):
    """Computes the 2D FFT, applies a high-pass filter, and reconstructs the image."""
    lowPassFilter = createLowPass(MRIsam.shape, cutoff_radius)
    highPassFilter = 1 - lowPassFilter
    kspMRI = fft2c(MRIsam)
    kspMRI_H = kspMRI * highPassFilter
    spaMRI_H = np.abs(ifft2c(kspMRI_H))
    return kspMRI, kspMRI_H, spaMRI_H

# Function to apply the undersampling mask to the k-space data
def undersample(kspace: np.ndarray, factor: int, compress: bool):
    """ Skipping every nth kspace line, starting from the midline.
    Simulates acquiring every nth (where n is the acceleration factor) line
    of kspace, common in SENSE algorithm.
    
    Parameters:
        kspace: Complex k-space numpy.ndarray
        factor: Only scan every nth line (n=factor) starting from midline
        compress: compress kspace by removing empty lines (rectangular FOV)
    """
    if factor > 1:
        mask = np.ones(kspace.shape, dtype=bool)
        midline = kspace.shape[0] // 2
        mask[midline::factor] = 0
        mask[midline::-factor] = 0

        if compress:
            # Remove empty lines and compress
            q = kspace[~mask]
            q = q.reshape(q.size // kspace.shape[1], kspace.shape[1])
            kspace[:] = q[:]
        else:
            kspace[mask] = 0
    return kspace

# Function to convert to k-space and apply undersampling
def undersampling_function(dicom_file, undersampling_factor, compress=False):
    # Load and process the DICOM file
    M, ds = dicomMatrix(dicom_file.name)

    # Perform K-space conversion
    kspMRI = fft2c(M)

    # Apply undersampling
    kspMRI_us = undersample(kspMRI.copy(), undersampling_factor, compress)
    spaMRI_us = np.abs(ifft2c(kspMRI_us))

    # Plot the original k-space, image, undersampled k-space, and undersampled image
    fig, axs = plt.subplots(1, 4, figsize=(20, 6))

    # Original Image
    axs[0].imshow(M, cmap='gray')
    axs[0].set_title("Original Image")
    axs[0].axis("off")

    # Original K-space (Magnitude)
    axs[1].imshow(np.log(np.abs(kspMRI) + 1e-9), cmap='gray')
    axs[1].set_title("Original K-space")
    axs[1].axis("off")

    # Undersampled K-space (Magnitude)
    axs[2].imshow(np.log(np.abs(kspMRI_us) + 1e-9), cmap='gray')
    axs[2].set_title(f"Undersampled K-space (R={undersampling_factor})")
    axs[2].axis("off")

    # Reconstructed Image from Undersampled K-space
    axs[3].imshow(spaMRI_us, cmap='gray')
    axs[3].set_title("Undersampled Image")
    axs[3].axis("off")

    plt.tight_layout()
    return fig

# Function to convert to k-space and plot the K-space visualization
def convert_to_kspace_and_plot(dicom_file):
    # Load and process the DICOM file
    M, ds = dicomMatrix(dicom_file.name)

    # Perform the K-space conversion
    kspMRI = fft2c(M)
    spaMRI = np.abs(ifft2c(kspMRI))

    # Plot original image, k-space, and reconstructed image
    fig, axs = plt.subplots(1, 3, figsize=(20, 6))

    # Original Image
    axs[0].imshow(M, cmap='gray')
    axs[0].set_title("Original Image")
    axs[0].axis("off")

    # K-space (Magnitude)
    axs[1].imshow(np.log(np.abs(kspMRI) + 1e-9), cmap='gray')
    axs[1].set_title("K-space (Original)")
    axs[1].axis("off")

    # Reconstructed Image from K-space
    axs[2].imshow(spaMRI, cmap='gray')
    axs[2].set_title("Reconstructed Image")
    axs[2].axis("off")

    plt.tight_layout()
    return fig

# Function to apply the filter (low-pass or high-pass) to K-space and plot
def convert_to_kspace_with_filter(dicom_file, filter_type, cutoff_radius):
    # Load and process the DICOM file
    M, ds = dicomMatrix(dicom_file.name)

    # Apply either low-pass or high-pass filtering based on user selection
    if filter_type == "Low-pass":
        kspMRI, kspMRI_L, spaMRI_L = lowFilter(M, cutoff_radius)
    elif filter_type == "High-pass":
        kspMRI, kspMRI_H, spaMRI_H = highFilter(M, cutoff_radius)

    # Plot original image, k-space, filtered k-space, and reconstructed image
    fig, axs = plt.subplots(1, 4, figsize=(20, 6))

    # Original Image
    axs[0].imshow(M, cmap='gray')
    axs[0].set_title("Original Image")
    axs[0].axis("off")

    # Original K-space (Magnitude)
    axs[1].imshow(np.log(np.abs(kspMRI) + 1e-9), cmap='gray')
    axs[1].set_title("K-space (Original)")
    axs[1].axis("off")

    # Filtered K-space (Magnitude)
    if filter_type == "Low-pass":
        axs[2].imshow(np.log(np.abs(kspMRI_L) + 1e-9), cmap='gray')
        axs[2].set_title(f"K-space ({filter_type} Filtered)")
    elif filter_type == "High-pass":
        axs[2].imshow(np.log(np.abs(kspMRI_H) + 1e-9), cmap='gray')
        axs[2].set_title(f"K-space ({filter_type} Filtered)")
    axs[2].axis("off")

    # Reconstructed Image from Filtered K-space
    if filter_type == "Low-pass":
        axs[3].imshow(spaMRI_L, cmap='gray')
        axs[3].set_title(f"Image ({filter_type} Reconstructed)")
    elif filter_type == "High-pass":
        axs[3].imshow(spaMRI_H, cmap='gray')
        axs[3].set_title(f"Image ({filter_type} Reconstructed)")
    axs[3].axis("off")

    plt.tight_layout()
    return fig

# Build the Gradio interface with improved aesthetics and navigation
def build_dicom_interface():
    with gr.Blocks() as demo:
        gr.Markdown("""
        # 🧠 MRI Processing Tool πŸ§‘β€πŸ”¬
        Welcome to the MRI processing interface! 
        Use the tabs below to upload a DICOM file and explore different MRI processing features:
        - **MRI Visualization** πŸ“·
        - **K-space Conversion** βš™οΈ
        - **Filtering** 🧰
        - **Undersampling** 🩻
        """)

        with gr.Tab("MRI Visualization πŸ“·"):
            with gr.Row():
                dicom_input = gr.File(label="Upload DICOM File")
                example_button = gr.Button("πŸ’‘ Use Example DICOM File", variant="primary")

            with gr.Row():
                show_image_button = gr.Button("Show Image")

            with gr.Row():
                image_output = gr.Plot(label="DICOM Image Visualization")

            example_button.click(fn=lambda: "13660", inputs=[], outputs=[dicom_input])
            show_image_button.click(fn=show_dicom_image, inputs=dicom_input, outputs=image_output)

        with gr.Tab("K-space Conversion βš™οΈ"):
            with gr.Row():
                view_kspace_button = gr.Button("View K-space Conversion")

            with gr.Row():
                kspace_output = gr.Plot(label="K-space and Reconstructed Image")

            view_kspace_button.click(fn=convert_to_kspace_and_plot, inputs=dicom_input, outputs=kspace_output)

        with gr.Tab("Filtering 🧰"):
            with gr.Row():
                filter_type = gr.Radio(["Low-pass", "High-pass"], value="Low-pass", label="Select Filter Type")
                cutoff_radius_slider = gr.Slider(minimum=0, maximum=50, step=1, value=10, label="Cut-off Radius")

            with gr.Row():
                convert_button = gr.Button("Convert to K-space with Filtering")

            with gr.Row():
                filter_output = gr.Plot(label="Filtered K-space and Reconstructed Image")

            convert_button.click(fn=convert_to_kspace_with_filter, inputs=[dicom_input, filter_type, cutoff_radius_slider], outputs=filter_output)

        with gr.Tab("Undersampling 🩻"):
            with gr.Row():
                undersampling_factor_slider = gr.Slider(minimum=1, maximum=10, step=1, value=2, label="Undersampling Factor")

            with gr.Row():
                undersample_button = gr.Button("Apply Undersampling")

            with gr.Row():
                undersample_output = gr.Plot(label="Undersampled K-space and Image")

            undersample_button.click(fn=undersampling_function, inputs=[dicom_input, undersampling_factor_slider], outputs=undersample_output)
        
        # Corrected link placement at the bottom, outside of the tabs
        with gr.Row():
            gr.Markdown("""
            ---
            ## For a detailed tutorial and more code examples:
            [Explore the Jupyter Notebook Tutorial](https://www.kaggle.com/code/danieltweneboaha/imageformation)
            """)
            
    return demo

# Launch the interface
demo = build_dicom_interface()
demo.launch(share=True)