Computers in Medicine Bone visualization and analyses - An introduction to Matlab - Presented by: Kathryn Stok ETH Zurich [email protected] Prepared by: Steven Boyd University of Calgary
Jan 20, 2016
Computers in Medicine
Bone visualization and analyses - An introduction to Matlab -
Presented by: Kathryn Stok
ETH Zurich
Prepared by: Steven Boyd
University of Calgary
Objectives (I)
Provide an overview of Matlab– What is Matlab?– Basic commands– Accessing online help– Writing M-files– Programming style– Create plots
Objectives (II)
Work through examples– Reading an image file– Probe the data– Filtering– Create a histogram– Thresholding– Counting voxels– Calculating 2nd moment of area
Why bone visualization?
Carries the body→ it should be strong
But in many cases, bone strength is impaired.– congenital deformities– osteoporosis– fracture– fatigue (stress fracture)
Bone architecture
Bone structure – femoral head
Young Normal Osteoporotic
Bone structure – lumbar spine
Young Normal Osteoporotic
Why bone visualization?
Bone (structure) analyses and visualization are of great importance in – Diagnosis– Treatment– Prevention
Why Matlab?
High-performance language for technical computing.– Matrix Laboratory
Advantages– Easy to use:
– No dimensioning required.– No compiling– Good for prototyping, testing
– Functionality is greatly expanded by toolboxes. – Many fields of application.
Disadvantages:– Uses much memory (slow for large applications)– Not good for final software design
What is matlab?
Matlab language– matrix/array language– control flow (if, for, while)– functions
Working environment– workspace for computing, importing, and
exporting data– text editor for creating M-files
This Matlab course
It covers: • Using the development environment.• Syntax of the language. • Basic matrix operations. • Basic graphics features. • Writing Matlab scripts and functions (m-files)
It does not cover: • Any of the toolboxes including Simulink. • c-mex and f-mex files, Matlab compilers.
Possibilities…
Develop tools for:– Image processing and basic analysis.– Visualization: 2D and 3D.– Simulation: Simulate bone loss.
Matlab Environment
Matrices
Albrecht Dürer
Magic square
Matrices
semicolon
Entering matrices– explicitly
Matrices
Sum, transpose
Matrices
Diagonal (diag)
Matrices
Subscripts: A(i,j)
row column
Matrices
Colon operator ' : '
Matrices
Colon operator ' : '
Matlab is 1-based
Matrix multiplication ( * )
Matrix multiplication ( .* )
Variables
Scalar, vector, matrix
Variables
Check workspace– command line– window
Numbers
Integer
Real
Exponential
Imaginary
-3
0.0001
1.60210e-20
5 + 2i
Operators: Arithmetic
+ Addition - Subtraction * Multiplication (or .* element-wise) / Division ^ Power (or .^ element-wise) ' Transpose () Brackets for evaluation order
A = [ 4 1 3]A.^2 = [16 1 9]A.*2 = [ 8 2 6]
A '* A 16 4 124 1 312 3 9
Operators: Relational
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
~= Not equal to
Operators: Logical
& AND
| OR
~ NOT
Type help ops to see: the arithmetic,relational and logical functions.
Matrices
Entering matrices– explicitly– load from external file– your own M-files– built-in function
Albrecht Dürer
Generating matrices
Loaddata file
Generating matrices
M-files
Generating matrices
Built-in functions
Help
Help Window– pop-up window
Type help
Online help
Online help
Online help
Useful commands
(up arrow)– recall previous command– p recalls previous command starting with ‘p’
clear– clear workspace– clear A Z Q clears only A, Z, and Q.
size– size(A) returns size of matrix A
Multidimensional matrices
page k,Z
rowi, X
column j, Y
Multidimensional matrices
Generate a 3D array manually
Advanced indexing
Matrices are always stored as columns– subscripts (i,j,k)– array dimension [d1 d2 d3]
– if A is of dimension 3 x 3 x 3 then A(3,3,3) = A(27) = 8
3 2 7 5 1 1 4 6 8 6 2 6 1 4 9 3 6 7 5 6 7 9 5 6 1 2 8
3 5 4 2 1 6 7 1 8
3 5 4 2 1 6 7 1 8
6 1 3 2 4 6 6 9 7
6 1 3 2 4 6 6 9 7
5 9 1 6 5 2 7 6 8
5 9 1 6 5 2 7 6 8
ij
k
Characters and Text
s = 'myimage'– 7 character array (string)
num2str() - convert a number to string
User input
Keyboard inputa_number = input('Enter number');a_string = input('Enter filename', 's');
[filename,path] = uigetfile('*.*');
Using GUI
Graphics: plot
Graphics: plot(s)
‘hold on’allows more plots to be added
Graphics: contours
Graphics: subplots
Graphics: labels and titles
Graphics: labels and titles
… or use the Figure window !
Graphics: mesh
Flow control
if, else, and elseif
switch
while
for
if, else, and elseif
if logical_expression statementsend
if (rem(a,2) == 0) disp(‘a is even’)end
if (n<0) disp(‘Input must be positive’)elseif (rem(n,2) == 0) disp(‘a is even’)else disp(‘a is odd’)end
switch
switch expression case value1 statements case value2 statements otherwise statementsend
switch (input_num) case (-1) disp(‘negative one’) case (0) disp(‘zero’) case (1) disp(‘positive one’) otherwise disp(‘othervalue’)end
while, for
while expression statementsend
n = 1;while (prod(1:n) < 1e10) n = n + 1;end
for index = start:inc:end statementsend
for i = 2:6 x(i) = 2*x(i-1);end
for i = 1:m for j = 1:n A(i,j) = 1/(i + j - 1); endend
Vectorization
Efficiency!– Example: Table of logarithms
–Find log10 of numbers between 0 and 10.
x = 0;for k = 1:1001 y(k) = log10(x); x = x + 0.01;end
x = 0:0.01:10;y = log10(x);
Looped code Vectorized code
AVOID LOOPS!
Scripts and functions
Scripts– No input arguments nor
output arguments.
– Operate on data in the workspace
– Useful for automating a series of steps that will be performed many times
Functions– Can accept input
arguments and return output arguments
– Variables are local to the function
– Useful for extending the MATLAB language beyond the built-in functions
Script example
Comment lines
Computations
Graphicsoutput
Create m-files:– type edit – use the interface
Script example
Hit return to advance plot
Script Example
Function example
Function definition
Help comments
Error check
Calculations
function [y] = average(x)
keyword
output argumentfunction name
input argument
Function example
semi-colon
M-files
Tips:– use descriptive variable names
–e.g. number_students = 20– functions end with “_fcn”
–e.g. an_example_fcn(number_students)– indent if, for, while statements 3-4 spaces– add comments using ‘%’– develop with smaller portions of data– debug by pasting line-by-line from M-file
Online tutorial
http://www.imrtweb.ethz.ch/matlab/
Or google “mathworks tutorial”
Fundamentals
Exercises
Examples
Part II: Practical Programming
Image analysis on 2D section– Read image data (micro-CT)– Plot the image– Examine image– Filter the image– Create a histogram– Threshold (distinguish between bone and marrow)
– Calculate porosity– Centroid, principal axes
Read 2D Image
Want to import the image from micro-CT
Write a program to:– clear workspace– set filename– load file
– Image data to visualize:/Phalanx/hp2d_34-95_380.bmp
Set up main program (a script file)
comments
clear workspace
close all figure windows
file to load
load it
Note: You need to write the 2D image reading function.
Read in 2D image
Read the file
Convert data
Display input data
Display input data
Display input data
Examine image
min, max, mean
Examine image
min, max, mean
Image Processing
Filter
Thresholding– histogram
Porosity = 1 - (bone area / total area)
Moment of area– First moment of area– Centroid– Second moment of area
Filtering – example 1
Filtering – example 2
filtered original image filtered noisy image
original image noisy image
Filtering the data
Apply Gaussian filtration– Shape of filter depends on:
window size [n1 n2] and
Filtering
Window = 3 = 1.2
Filter
Filtering
Window = 5 = 1.2
Filter
Filtering
Window = 15 = 1.2
Filter
Filtering
Window = 15 = 7
Filter
Filtering
Window = 15 = 100
Filter
Filtering: Convolution
zyx fff
Filtering: Edge Effects
edge data nulled
• Important to begin with image dimensions large enough to account for edge effects
Filtering
Use built-in functions:– fspecial– imfilter– (smooth3)
Thresholding
• Good to try different thresholds to see the effect.
Segmentation of bone– divides bone from other tissue
Thresholding
threshold2D = zeros matrixFind all indices (i,j) where element(i,j) > threshold threshold2D(i,j) = 1
Thresholding
Thresholding
Threshold = 90 Threshold = 120
Histogram
– lookfor and help
Histogram
hist works on vectors, not 2D matrices– need reshape function to vectorize
Porosity
Porosity = 1 - (Bone volume divided by total volume)
Need total bone volume (area)– Create mask:
– filter image to remove holes– threshold filtered image
– Count total “mask” pixels– Count total “bone” pixels
within mask
Porosity
Create mask:
original image
filtered image
threshold filtered image
Image 3 super-imposedon image 1
1 2 3
Porosity
Porosity = 1 -Mask pixels
Bone pixels within mask
Thresholded image (bone)
Mask image
Image of bone within the mask
Image analysis – determine porosity
Original
Segmenting the boneFiltered Thresholded
Creating the maskFiltered Thresholded
Find bone within mask
Porosity = 1 - Areabone
Areamask
Erosion, dilation
Erode Erode = 2 Erode = 4
Dilate Dilate = 2 Dilate = 4
Part of MAIN program
Stress in Pure Bending
Mechanical stiffness– First moment of area– Centroid of area– Second moment of area
First moment of an area
First moment of area with respect to the X axis:
First moment of area with respect to the Y axis:
Can be positive, negative, or zero depending on the axis location
(mm3)
(mm3)
Centroid of an area
Centroid of area defined as:
Knowing the first moment:
First moment of area
Second moment of area
Stress resulting from bending: σ = My/I
Resistance against bending.– Take Ix, Iy, Ixy about centroid C
– Or use the parallel axis theorem: Ix = Ixc + Ad2
Second moment of area - rotation
Transformation of 2nd moments:
Second moment of area - principal axes
Two values of for which Ixy = 0.
Can calculate the max/min 2nd moments:
maximum associatedwith Ix
minimum associatedwith Iy
Principal axes & Transformation
2D: Pompe Disease
Radius Tibia
Mouse knees
NTRTCTRL