Programming lesson
From K-Space to Diagnosis: A MATLAB Guide for MPHY0020 MRI Coursework
Master MATLAB signal processing for brain MRI reconstruction, filtering, and segmentation. This tutorial covers key concepts for MPHY0020 coursework with practical code examples and timely analogies from AI and sports imaging.
Introduction: Why MRI Signal Processing Matters in 2026
In 2026, MRI technology is more advanced than ever, with AI-assisted reconstruction and real-time imaging becoming clinical standards. The MPHY0020 coursework at UCL bridges foundational MATLAB skills with real-world medical imaging challenges. This tutorial will guide you through the essential steps—from raw k-space data to a fully segmented brain image—while highlighting best practices that can boost your grade by up to 25% for clarity and 15% for efficient coding.
Whether you're aiming for a career in medical physics, AI diagnostics, or biomedical engineering, mastering these techniques is your first step. Let's dive into the tasks, using examples inspired by current trends like AI image generation and sports injury analysis.
Task 1: Visualizing K-Space with Proper Scaling
K-space is the frequency-domain representation of an MRI image. Think of it like the Fourier transform of a photo—each point encodes a spatial frequency component. In 2026, similar concepts power AI image compression and neural radiance fields.
Loading and Displaying K-Space
Your first script should load kspace_single_slice.mat. Use load() to bring the variable into the workspace. Then, compute the magnitude and apply a logarithmic transform: L = log10(abs(E)). This compresses the wide dynamic range typical of k-space (often 60+ dB) into a viewable scale.
% Task1_kspace_visualization.m
load('kspace_single_slice.mat'); % loads variable E
L = log10(abs(E));
imagesc(L, [min(L(:)), min(L(:))+20]); % 20 dB dynamic range
colormap('gray'); colorbar;
xlabel('kx (mm^{-1})'); ylabel('ky (mm^{-1})');
title('Log-Magnitude K-Space');Converting Pixel Indices to Spatial Frequency
The axes must show frequency in mm⁻¹, not pixel indices. Given pixel spacing Δx = Δy = 0.43 mm, compute the field of view: FOVx = Nx * Δx. Then frequency axes: kx = (-Nx/2 : Nx/2-1) / FOVx. Use fftshift to center zero frequency.
Nx = size(E,2); Ny = size(E,1);
dx = 0.43; dy = 0.43;
FOVx = Nx * dx; FOVy = Ny * dy;
kx = (-Nx/2 : Nx/2-1) / FOVx;
ky = (-Ny/2 : Ny/2-1) / FOVy;
imagesc(kx, ky, L, [min(L(:)), min(L(:))+20]);
axis xy; % correct orientationThis matches the coursework requirement and demonstrates clear axis labeling—a key point for the 25% clarity mark.
Task 2: Image Reconstruction via Inverse FFT
Reconstructing the image is straightforward: apply the 2D inverse FFT to the k-space data. In MATLAB, ifft2 does the job. But remember to shift the zero-frequency component back to the center using fftshift before and after.
% Task2_reconstruction.m
img = ifftshift(ifft2(fftshift(E)));
img = abs(img);
img = img / max(img(:)); % scale to [0,1]
imshow(img);
title('Reconstructed MRI Slice');This simple reconstruction is analogous to how AI models like DALL·E decode latent vectors into images—just with Fourier transforms instead of neural networks.
Task 3: K-Space Filtering for Contrast and Edge Enhancement
Filtering in k-space is equivalent to convolution in image space. Low-pass filters smooth the image; high-pass filters enhance edges. This is similar to how social media apps apply filters to photos, but here we do it in frequency domain for medical precision.
Designing a Low-Pass Filter
Create a circular binary mask that retains only low frequencies. The radius determines the cutoff.
% Task3_filtering.m
[KX, KY] = meshgrid(kx, ky);
radius = 0.1; % fraction of Nyquist
mask = sqrt(KX.^2 + KY.^2) <= radius * max(abs(kx(:)));
E_filtered = E .* mask;
img_low = abs(ifft2(ifftshift(E_filtered)));
img_low = img_low / max(img_low(:));Display side-by-side with the original reconstruction. Use subplot and imshow for clear visualisation.
High-Pass Filtering for Edge Detection
Similarly, a high-pass mask is 1 - mask. This reveals fine details like tumour boundaries—critical for segmentation later.
mask_high = 1 - mask;
E_high = E .* mask_high;
img_high = abs(ifft2(ifftshift(E_high)));
img_high = img_high / max(img_high(:));In 2026, edge detection filters are used in real-time sports imaging to track player movements—just like you'll track anatomical structures.
Task 4: Rotation Correction in 3D
MRI volumes often suffer from patient motion. Rotation correction is essential for accurate diagnosis. This task builds on the previous ones: you'll apply a rotation to the k-space data and then correct it.
Simulating a Rotation
Assume a known rotation angle θ (e.g., 5°). Rotate the k-space data using imrotate with 'crop' to preserve size.
theta = 5;
E_rotated = imrotate(E, theta, 'bilinear', 'crop');Estimating and Correcting the Rotation
One method: compute the magnitude of the Fourier transform of the rotated image, then find the angle that minimizes the difference with the original magnitude. Use fminsearch or a brute-force scan over angles.
% Simplified: brute-force search
angles = -10:0.1:10;
error = zeros(size(angles));
for i = 1:length(angles)
E_candidate = imrotate(E, angles(i), 'bilinear', 'crop');
error(i) = sum(abs(abs(fft2(E_candidate)) - abs(fft2(E))), 'all');
end
[~, idx] = min(error);
estimated_theta = angles(idx);
E_corrected = imrotate(E_rotated, -estimated_theta, 'bilinear', 'crop');This technique is similar to how AI stabilizes shaky videos on smartphones—a hot topic in 2026 consumer tech.
Task 5: Segmentation of Brain Structures and Tumours
Segmentation is the holy grail: separating white matter, grey matter, and tumours. In 2026, deep learning models like U-Net dominate, but classical methods still teach fundamental principles.
Thresholding Based on Intensity
After reconstruction, apply Otsu's thresholding to segment brain tissue.
level = graythresh(img);
mask_brain = imbinarize(img, level);
For tumour segmentation, use region growing or k-means clustering. Here's a simple region-growing approach:
seed = [100, 120]; % example seed point
threshold = 0.2;
segmented = regiongrowing(img, seed(1), seed(2), threshold);
Visualize the segmentation overlay using imshowpair or labeloverlay.
Best Practices for High Marks
To secure the 25% clarity and 15% good practice marks, follow these guidelines:
- Use descriptive variable names:
kspace_datainstead ofE,reconstructed_imginstead ofimg. - Comment your code: Explain each step, especially the mathematical formulas.
- Vectorize operations: Avoid loops where possible. For example, use
meshgridfor filter masks. - Memory management: Clear large variables when no longer needed (
clear E). - Error checking: Validate that the input file exists before loading.
These practices are standard in industry and academia—think of them as the coding equivalent of a clean surgical field.
Conclusion: From Coursework to Real-World Impact
Completing this coursework equips you with skills directly applicable to medical imaging research and AI development. In 2026, companies like Siemens and GE HealthCare are integrating similar MATLAB pipelines into their scanners. By mastering k-space visualization, Fourier reconstruction, filtering, rotation correction, and segmentation, you're not just passing an assignment—you're building a foundation for a career in biomedical technology.
Remember to submit all .m files, a text file mapping tasks to scripts, and a single .zip file named with your student number only. Good luck!