You are on page 1of 48

Fundamental of Medical Imaging

MATLAB Tutorial III


Junmo An
jman@cs.uh.edu
Office Hour: Monday 2:30pm – 4:30pm (PGH 533)

Department of Computer Science, University of Houston


Free Trial of MATLAB
• A free trial of MATLAB for the
next 8 weeks.
• www.coursera.org
• Digital Signal Processing
– by Paolo Prandoni, Martin Vetterli
• The MATLAB Alternatives
– Octave
– FreeMat
– Scilab

2
Agenda
• Image Types
• Image Tool
• Arithmetic and Logic Operations
– Image addition, subtraction, multiplication,
division, inversion, etc.
• Image Processing
– Object Detection, Edge Detection, Masking,
etc.
• MATLAB Demo

3
Binary (1-Bit) Image

4
Grayscale (8-Bit) Image

5
Intensity Image
Saggital = dicomread('IM-0002-0001.dcm'); 206 489 930 1200 1258 1138 868 548 233 114
figure, imshow(Saggital,'DisplayRange',[]);
hold on; 247 558 1006 1248 1277 1125 794 485 200 84

rectangle('Position',[227 153 10 10], … 283 611 1085 1299 1233 1056 715 425 171 52
'LineWidth',1, 'EdgeColor','g'); %Draw rectangle.
309 648 1129 1321 1162 994 681 361 143 23
hold off;
312 664 1166 1335 1109 951 615 259 98 0

296 667 1167 1296 1099 893 529 198 65 8

283 666 1128 1235 1100 823 460 174 37 15

274 634 1077 1224 1048 724 394 134 31 16

259 577 995 1200 1002 660 334 95 32 15

210 526 917 1147 932 569 271 71 15 17

• uint8 – [0, 255]


• uint16 – [0, 65,535]
• double – [0.0, 1.0]
6
Color Image: 24-Bit (RGB) Color Images

Red Green Blue

7
Color Image: Indexed Color Images

8
Image Types
• Binary images
– logical array of 0s and 1s; obtained using function
logical on a numeric array of ones and zeros
(halftone).
• Intensity images
– generally grayscale images whose values
represent image intensity; class can be double
(floating point), uint8 (integers from 0 to 255),
uint16 (integers from 0 to 65535) or scaled double in
the range [0,1].
• RGB images
– image with 3 complementary color sets of
intensity.
• Indexed images
– image with two components, namely a data matrix of
integers, X, and a color map matrix, map.
9
Converting from Grayscale Image to Binary Image

f = imread('cell.tif'); %Read built-in image


g = f;
g(find(f >= 128)) = 1;
g(find(f < 128)) = 0;
b = logical(g);
figure, imshow(g, 'DisplayRange',[]);

10
Image Tool
f = imread('spine.tif'); %Read built-in image
imtool(f); %Open the image tool

11
Tools associated with the Image Tool
Tool Description
Pixel Information Displays information about the pixel under the mouse
pointer.
Pixel Region Superimposes pixel values on a zoomed-in pixel view.
Distance Measures the distance between two pixels.
Image Information Displays information about images and image files.
Adjust Contrast Adjusts the contrast of the displayed image.
Crop Image Defines a crop region and crops the image.
Display Range Shows the display range of the image data.
Overview Shows the currently visible image.

imtool is extremely useful tool for gaining an understanding of image properties.

12
Image Addition
A = imread('cameraman.tif'); %Read built-in image
subplot(1,2,1), imshow(A); %Display image
B = imadd(A, 100); %Add 100 to each pixel value in image A
subplot(1,2,2), imshow(B); %Display result image B

13
Image Subtraction
A = imread('cola1.png'); %Read 1st image
B = imread('cola2.png'); %Read 2nd image
subplot(3,1,1), imshow(A); %Display 1st image
subplot(3,1,2), imshow(B); %Display 2nd image
-
Output = imsubtract(A, B); %Subtract images
subplot(3,1,3), imshow(Output); %Display result

• Absolute Difference
Ioutput = |IA – IB|
Output = imabsdiff(A, B); %Subtract images
figure, imshow(Output); %Display result
=

14
Image Multiplication and Division
A = imread('cameraman.tif'); %Read built-in image
subplot(3,1,1), imshow(A); %Display image
Output = immultiply(A,1.5); %Multiply image by 1.5
subplot(1,3,3), imshow(Output); %Display result
Output = imdivide(A,4); %Divide image by 4
subplot(1,3,3), imshow(Output); %Display result

Original Original * 1.5 Original / 4

15
Image Inversion
Ioutput(i,j) = MAX - Ioutput(i,j)
A = imread('cameraman.tif'); %Read built-in image
subplot(1,2,1), imshow(A); %Display image
B = imcomplement(A); %Invert the image
subplot(1,2,2), imshow(B); %Display result image B

16
Thresholding
I = imread('trees.tif'); %Read built-in image
T = im2bw(I, 0.1); %Perform thresholding. Value 1 is white and value 0 is black.
subplot(1,2,1), imshow(I); %Display original image
subplot(1,2,2), imshow(T); %Display thresholded image

17
Resizing an Image
I = imread('circuit.tif'); %Read built-in image
J = imresize(I,2); %Enlarge image (*2)
figure, imshow(I); %Display image
figure, imshow(J); %Display enlarged image
K = imresize(I,[100 150]); %Create an output image with 100 rows and 150 columns
figure, imshow(K); %Display 100 x 150 image

Original * 2

100 x 500
Original

18
Image Rotation
mri_image1 = imread('image1.jpg');
mri_image2 = imread('image2.jpg');
figure, imshow(mri_image1);
title('IMAGE 1');
figure, imshow(mri_image2);
title('IMAGE 2');

angle = 90; %Rotate 90 degree (CCW)


demo2 = imrotate(mri_image1,angle) + mri_image2;
figure, imshow(demo2);
title(' IMAGE 1 is rotated 90 degree and then IMAGE
2 is added to IMAGE 1.');

19
Contrast Enhancement
load clown;
figure, image(X);
colormap(gray);
cmap = contrast(X);
figure, image(X);
colormap(cmap);

Original Contrast Enhanced.


20 20

40 40

60 60

80 80

100 100

120 120

140 140

160 160

180 180

200 200
50 100 150 200 250 300 50 100 150 200 250 30020
Edge Detectors
I = imread('coins.png'); % built-in image
BW1 = edge(I,'sobel');
BW2 = edge(I,'canny');
figure, imshow(I);
figure, imshow(BW1);
Origin
figure, imshow(BW2);

• Parameters
– Sobel Method
• edge(I,'sobel')
– Canny Method
• edge(I,'canny')
– Prewitt Method Sobel
• edge(I,'prewitt')
– Roberts Method
• edge(I,'roberts')
– Laplacian of Gaussian Method
• edge(I,'log‘)
– Zero-Cross Method

Canny
21
Tracing Object Boundaries
I = imread('coins.png'); % built-in image
BW = im2bw(I);
dim = size(BW);
col = round(dim(2)/2)-90;
row = min(find(BW(:,col)));
boundary = bwtraceboundary(BW,[row, col],'N');
figure, imshow(I);
hold on;
plot(boundary(:,2),boundary(:,1),'g','LineWidth',3);
BW_filled = imfill(BW,'holes');
boundaries = bwboundaries(BW_filled);
for k=1:10
b = boundaries{k};
plot(b(:,2),b(:,1),'b','LineWidth',3);
end

22
Extraction Example
img = imread(‘lung.jpg'); % Read image
figure, imshow(img);
%% Crop out unnecessary parts
cropped = img(90:400,40:460);
%% Threshold to isolate lung tissue
thresholded = cropped < 86;
%% Remove artifacts attached to border
clearThresh = imclearborder(thresholded);
%% Remove objects less than 40 pixels in size
imgBigTissue = bwareaopen(clearThresh,100);
figure, imshow(imgBigTissue);

23
Example
%3x3 matrix %3x4 matrix
f = [255 230 180; 155 130 105; 80 50 0]; X = [1 2 3 4; 5 6 7 8; 9 10 11 12];
figure, imshow(f,[],'InitialMagnification','fit'); h = image(X); colormap(colorcube(12));

24
Example
value1 = 0; %the intensity of the band 1
value2 = 100; %the intensity of the band 2
value3 = 30; %the intensity of the band 3
for i = 1:40
for j = 1:10
object(i,j) = value1;
end
for j = 11:30
object(i,j) = value2;
end
for j = 31:40
object(i,j) = value3;
end
end
figure, image(object);
colormap(gray);

25
Adding Text to Images
% Create the text in an axis:
t = text(.05,.1,'Mandrill Face', ...
'FontSize',20, 'FontWeight','demi');
% Capture the text from the screen:
F = getframe(gca,[10 10 200 200]);
% Select any plane of the resulting RGB image:
c = F.cdata(:,:,1);
% Determine where the text was (black is 0):
[i,j] = find(c == 0);
% Read in or load the image that is to contain the text:
load mandrill
% Use the size of that image, plus the row/column locations
% of the text, to determine locations in the new image:
ind = sub2ind(size(X),i,j);
% Index into new image, replacing pixels with white:
X(ind) = uint8(255);
% Display and color the new image:
figure, imagesc(X);
axis image;
colormap(bone);
26
Masking an Image
mri_image = imread('image1.jpg');
figure, image(mri_image);
value1 = 0; % the intensity of the opaque band
value2 = 1; % the intensity of the transparent band
size = 256;
start1 = 50;
start2 = 150;
for i = 1:256
for j = 1:start1
mask(i,j) = value1;
end
for j = start1+1:start2
mask(i,j) = value2;
end
for j = start2+1:size
colormap(gray);
mask(i,j) = value1; original_image (:,:) = double(mri_im
end age(:,:,1));
end new_image = original_image.*mask;
intensify = 100; figure, image(new_image);
figure, image(intensify*mask); colormap(gray);
27
Loading an Excel File
filename = 'plot.xlsx';
column = xlsread(filename); %Open an Excel file
figure, plot(column);
hleg = legend('Column 1', 'Column 2', 'Column 3'); %Graph legend
set(hleg, 'FontAngle', 'italic', 'TextColor', [.3,.2,.1], 'Location', 'East'); %Legend style
xlabel('Frequency (MHz)');
ylabel('|S_1_1| (dB)');
grid on;
grid minor;

28
Matrix Indexing Example
f = imread('eight.tif'); fp = f(end:-1:1,:); %flip vertically
figure, imshow(f); figure, imshow(fp);

fs = f(1:2:end,1:2:end);
figure, imshow(fs);
fc = f(150:229,158:237); %Crop (80x80)
figure, imshow(fc);

29
Matrix Indexing Example
figure, imshow(fc);
hold on;
plot([1 80], [70 70], 'b', 'LineWidth', 2);
hold off;

figure, surf(double(fc));

figure, plot(fc(70,:));

30
Connected-Component Labeling
BW = [0 0 0 0 0 0 0 0 0;
0 1 1 0 0 0 1 1 1;
Connected-Components
0 1 1 0 0 0 0 1 1;
0 1 1 0 0 0 0 0 0;
0 0 0 0 1 1 0 0 0;
0 0 0 0 1 1 0 0 0;
0 0 0 0 1 1 0 0 0;
0 0 0 0 0 0 0 0 0];
cc = bwconncomp(BW) %computes connected components
labeled = labelmatrix(cc); %Construct a label matrix
%Create a pseudo-color image
RGB_label = label2rgb(labeled, @copper, 'c', 'shuffle'); cc =
imshow(RGB_label,'InitialMagnification','fit'); Connectivity: 8
ImageSize: [8 9]
NumObjects: 3
PixelIdxList: {[6x1 double] [6x1 double]
31
[5x1 double]}
Selecting Objects in Binary Image
url = 'http://blogs.mathworks.com/images/steve/163/plateaus.png';
bw = imread(url);
figure, imshow(bw)
annotation(gcf,'ellipse','LineWidth',3,...
'Position',[0.4931 0.463 0.07575 0.2029],...
'Color',[1 0 0]);
pond = bwselect(bw, 183, 170);
figure, imshow(pond);

32
Selecting Objects in Binary Image
BW1 = imread('text.png');
c = [43 185 212];
r = [38 68 181];
BW2 = bwselect(BW1,c,r,4);
imshow(BW1), figure, imshow(BW2)

33
Counting Grains of Rice in an Image
• raw image shows grains of rice
– the image has non‐uniform illumination; the
background is brighter in the center of the
image than at the bottom
– goal is to enhance the image to correct for the
non‐uniform illumination
– use the enhanced image to identify individual
grains
– compute the grain statistic

34
Counting Grains of Rice in an Image
%Step 1 - Read built-in image and display
I = imread('rice.png');
figure, imshow(I);

%Step 2 - estimate background using morphological


opening operation
background = imopen(I,strel('disk',15));

%Step 3 - view background approximation as a


surface
figure, surf(double(background(1:8:end,1:8:end)));

%limit range to that of uint8 data to match input


image (for subtraction)
zlim([0 255]);

% reverse y-axis of display to provide better view of


surface
set(gca,'ydir','reverse');

35
Counting Grains of Rice in an Image
%Step 4 - subtract background image from original
image
I2 = I - background;
figure, imshow(I2);

%Step 5 - increase image contrast --background is


too dark, using imadjust
I3 = imadjust(I2);
figure, imshow(I3);

36
Counting Grains of Rice in an Image
%Step 6 - threshold image to create binary version of
image in order to count the number of grains of rice
%scale to binary image
level = graythresh(I3);
%im2bw converts grayscale image to binary image using
thresholding
bw = im2bw(I3,level);
%bwareaopen removes background noise
bw = bwareaopen(bw,50);
figure, imshow(bw);

%Step 7 - identify objects in image


cc = bwconncomp(bw,4);
cc.NumObjects ans = 95

%Step 8 - examine a single detected object; each distinct


object is labeled (show 50th connected component)
grain = false(size(bw));
grain(cc.PixelIdxList{50}) = true;
figure, imshow(grain);
37
Counting Grains of Rice in an Image
%Step 9 - view all objects
labeled = labelmatrix(cc);
whos labeled
%label2rgb creates colormap, choose background color, and
maps objects in labelmatrix map to colors in colormap
RGB_label = label2rgb(labeled,@spring,'c','shuffle');
figure, imshow(RGB_label);

%Step 10 - compute area of each object


%regionprops operates on cc tocompute object areas
graindata = regionprops(cc,'basic')
%find area of 50th component
graindata(50).Area ans = 194

%Step 11 - compute area-based statistics


grain_areas = [graindata.Area];
%find grain with smallest area
[min_area,idx] = min(grain_areas);
grain = false(size(bw));
grain(cc.PixelIdxList{idx}) = true;
figure, imshow(grain); min_area = 61
min_area
38
Counting Grains of Rice in an Image

%Step 12 - create area histogram


nbins = 20;
figure, hist(grain_areas,nbins);
title('Histogram of Rice Grain Area');

39
Fourier Transformation
fileToRead1 = 'MIR_2010_partialFourierdata.txt';
MIR_2010_partialFourierdata = importdata(fileToRead1);
ksp = reshape(MIR_2010_partialFourierdata(:,1)+j*MIR_2010_partialFourierdata(:,2), 256, 256);
figure, image(abs(ksp)*1e6); colormap(gray);
im = fftshift(ifft2(fftshift(ksp)));
figure, imagesc(abs(im)); colormap(gray);

FT

http://ymk.k-space.org/medical_image_reconstruction.htm
40
Simple MRI Simulator

(2) (4)
(1) (3) (5)

• The two outside (1) and (5) are empty


space!
• Areas (2) and (3) are the same type of
tissue.
• Area (3) is a different one.
Each of these areas has particular type of properties (physical parameters)
associate with the tissue or type of material it represents
41
Simple MRI Simulator
• We assume we are using a special way to
collect MR images that emphasize T1 (T1-
weighted) and T2 (T2-weighted) differences.
• For this example, we can assume that the MR
scanner collects images by waiting the
signal by

𝑆 = 𝑆0(2 − 𝑒 −𝑇𝑅 𝑇1 )(𝑒 −𝑇𝐸 𝑇2 )


• Where T1 is a “relaxation time” of the tissue
• TR is an operator defined parameter.
NOTE: This is a simplification! Do not use it in studies!
42
Simple MRI Simulator
−𝑇𝑅 𝑇1 −𝑇𝐸 𝑇2
𝑆 = 𝑆0(2 − 𝑒 )(𝑒 )
• If TR (Repetition Time) increases, the MR
image contrast is reduced.

Contrast is reduced!!!

• If TE (Echo Time) increases, the MR image


contrast is reduced.
43
Some Available Tools for Medical Image
Processing
• ITK
– NLM Insight Segmentation & Registration
Toolkit
– Project at the National Library of Medicine (at
NIH)
– Goals
• Support the Visible Human Project
• Create a repository of fundamental algorithms
• Develop a platform for advanced product
development
• Grow a self-sustaining community of software
users and developers

44
ITK – Pros and Cons
• Pros
– Growing and very active community
– Can handle N-dimensional data
– Open Source: FREE
– Very advanced algorithms
• Cons
– Steep learning curve
– No built-in GUI
• FLTK, Qt, Windows MFC
• VTK (visualization)
45
References
• Book
– “MATLAB Graphics and Data Visualization
Cookbook” by Nivedita et al.
– "MATLAB® 7 3-D Visualization" by The
MathWorks
– “Fundamentals of Digital Image Processing”
by Chris Solomon and Toby Breckon
– “Practical Image and Video Processing Using
MATLAB” by Oge Marques

46
MATLAB DEMO

47
? Do you have any questions?

Junmo An
jman@cs.uh.edu
http://mrl.cs.uh.edu

Thank you
48

You might also like