Spaces:
Sleeping

Kspace_App / app.py
Tdanyim's picture
Rename appKspEnh.py to app.py
5c5e602 verified
Raw History Blame Contribute Delete
10.3 kB
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)