postprocessing mri images - massachusetts institute of

37
Post Processing Brain MRI Images 2.1._Pre-Processing Question 1. Print a picture of the slice and put it in your lab report. The picture of the slice is shown n Figure 1 Figure 1 Picture of a slice of the brain Question 2. Try to find a good threshold for separating white and gray matter and say what it is in your lab report, and put in a picture of the result. The threshold that I found was the following img > 79 This is the best threshold I was able to find. The compromise was to keep the white matter while trying to get rid of the gray matter as much as possible. The resulting image after the threshold operation to separate the white matter from the gray matter is shown in Figure 2.

Upload: others

Post on 25-Jan-2022

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: postprocessing MRI images - Massachusetts Institute of

Post Processing Brain MRI Images

2.1._Pre-Processing

Question 1.

Print a picture of the slice and put it in your lab report. The picture of the slice is shownn Figure 1

Figure 1 Picture of a slice of the brain

Question 2.

Try to find a good threshold for separating white and gray matter and say what it is inyour lab report, and put in a picture of the result.

The threshold that I found was the following

img > 79

This is the best threshold I was able to find. The compromise was to keep the whitematter while trying to get rid of the gray matter as much as possible. The resulting imageafter the threshold operation to separate the white matter from the gray matter is shownin Figure 2.

Page 2: postprocessing MRI images - Massachusetts Institute of

Figure 2. White matter resulting from threshold operation of image at Image>79

Question 3.

Try to find a smoothing standard deviation that is a "reasonable" compromise betweenstructural faithfulness and noise reduction. Say what the setting is and turn in a pictureof the result.

In the original code, the standard deviation sigma = 2 smoothed out the image too much,and the sigma of 0.1 did not do much to the image. I played with the standard deviationvalue and I found that the best value that trades structural faithfulness and noise reductionis:

standard deviation = 1

Figure 3 shows the image of the blurred image after applying the 2D low pass Gaussianfilter. The threshold operation after the low pass filtering for the white matter is shown inFigure 4.

Page 3: postprocessing MRI images - Massachusetts Institute of

Figure 3 Blurred Image after applying the 2DlLow pass Gaussian Filter

Figure 4. Threshold operation after the low pass filtering for the white matter

Page 4: postprocessing MRI images - Massachusetts Institute of

Question 4.

Try to find a combination of threshold and median filter neighborhood size that is a"reasonable" compromise between structural faithfulness and noise reduction. Say whatthe setting is and turn in a picture of the result.

In the original code, the order of the filter = 7 makes the image too chunky, and the order= 1 did not do much to the image. I played with the order of the median filter and I foundthat the best value that trades structural faithfulness and noise reduction is:

Order = 3

Figure 5 shows the image of the blurred image after applying the 2D Median filter. Thethreshold operation after the median filtering for the white matter is shown in Figure 6.

Figure 5. Image of the blurred image after applying the 2D Median filter

Page 5: postprocessing MRI images - Massachusetts Institute of

Figure 6. Threshold operation for the white matter after median filtering the image

2.2._Statistical Classification

The data that we have is the following.

?We have 124 MRI images of the head of a person in the oo5 directory named slice.001thru slice.124

?We also have 124 classified images by an expert named output.001 to output.124. Foreach pixel in the image, the expert put the labels LABEL_WHITE =8,LABEL_GRAY = 4 and LABEL_CSF = 5 respectively.

The Slices that were selected to be used as training data were slices 30 32 34 36 38 40 4244. We also selected the images to test our classify.m code once we have finished. Thistesting images are slices 26 thru 64.

In Figure 7 I show an example of a MRI image (slice 45) and in Figure 8, I show anexample of the Image labeled by the expert.

Page 6: postprocessing MRI images - Massachusetts Institute of

Figure 7. Example of a MRI image (slice 45)

Figure 8. Example of the Image labeled by the expert for slice 45.

Page 7: postprocessing MRI images - Massachusetts Institute of

Question 5.

Histogramming is one approach to estimating probability density functions (PDFs). Ifyou inspect the histogram plotted above, you may notice that it is not a legitimate PDF,because, when viewed as a function over the real line, it does not integrate to one.

Your task in this problem is to implement a histogram based estimate of the PDF for theintensity of white matter in the training data. Your implementation will probably need toconstruct Matlab function that has two parts, one that constructs the state of thehistogram from the training data, by, among other things, establishing an array of "bins"and counting the number of training data points that fall into each bin. The other part would implement the PDF itself as a function from real-valuedintensities to probability density. In this situation, each bin will corresponds to a rangeof intensity values. Keep in mind that probability density must be non-negative, and thePDF must integrate to one.

There is some freedom available in making histograms, for example the choice of thenumber of bins. Plot your histogram-based PDF with several choices for bin count.Pick your favorite count, say why you think it is a good choice, and turn in thecorresponding plot.

During this part of the lab, I filled out the missing parts of the classify.m and HistPDF.mfiles. The code for this functions can be found in section II of the appendix.

First of all, I would like to show the steps followed in the classify.m file.

?Loop for all training slices

i._Read the slice image

ii._Read the labeled image

iii._Find all the pixel intensities observed for each class and store them in the variables called intensity_white, intensity_gray, and intensity_csf.

?I Plotted the histogram of the white matter. The histogram of the white matterintensities is shown in figure 9.

Page 8: postprocessing MRI images - Massachusetts Institute of

Figure 9. Plot the histogram of the white matter

?I wrote a matlab function to convert the Histogram (Figure 9) calculated for the whitematter to a probability density function. I had to make this histogram functionintegrable to one. This is, make it obey the laws for the pdf's.

The function I wrote is

Density = HistPDF(Intensity, TrainingData, NumBins)

The function takes as parameters intensity, which is a vector containing the desiredrange of intensities for the pdf, TrainingData, which is basically all the intensitiesobserved for the class we want to build the pdf and NumBins which is the number of binswe want to divide the histogram into. The code for this function can be found in sectionIII of the appendix.

The steps followed in the construction of this histogram based pdf are the following: i._Count the length of the vector containing all the intensities observed for the class we want to build the pdf (length of TrainingData).. ii._Calculate the histogram of the TrainingData using the specified number of bins (NumBins) and store the result thing bin counts (BinCount) and the centers of the bins (BinCenters). iii_Calcultate the BinWidth. This is, the distance between the centers of two consecutive bins. iv._Calculate the lowest intensity. This can be done substracting half of the bandwidth from the first bin center. v._Loop over all the intensity values specified (Intensity) for each intensity value, count the number of data values. Store the values in the variable Retreivedcounts

Page 9: postprocessing MRI images - Massachusetts Institute of

vi._Normalize the new histogram generated, so that it is integrable to one. This is done by multiplying RetreiveCounts by the factor

Normalization = 1/(TotalCount*BinWidth)

vii._Return the normalized histogram.

I selected the number of bins equal to 20. This is because it has a better resolution. Theplot of the new probability density function generated from the histogram is shown inFigure 10.

Figure 10 PDF generated from the Histogram for the white matter for number of bins =20

Question 6.

Your next task is to implement the maximum likelihood method for estimating the parameters of Gaussian class conditional densities.

You will need to set the two vectors defined above with three values each that arederived from the observed class conditional intensities: intensity_white, intensity_gray,and intensity_csf. Turn in your lines of code that set values for "tissue_means" and"tissue_vars".

?In this part, I calculated the parameters for the Gaussian class conditional densitiesusing the Maximum Likelihood Model. The parameters using the ML model are themean and the variance. The following, are the lines of code in MATLAB that I used todo this.

tissue_means = [ mean(intensity_white) mean(intensity_gray) mean(intensity_csf)];

Page 10: postprocessing MRI images - Massachusetts Institute of

tissue_vars = [ var(intensity_white) var(intensity_gray) var(intensity_csf)];

Question 7.

At this point we have estimated tissue class conditional PDFs on intensity by the use ofGaussian models. This was done by using the ML method to estimate the mean andvariance parameters for each class, based on the training intensities.

These Gaussian models may be visualized by plotting, e.g. plot(gauss([0:500],tissue_means(1), sqrt(tissue_vars(1))), 'r'); Previously, we constructed and displayed ahistogram estimate of the PDF for white matter.

Arrange for a plot that, for white matter, shows the histogram basedPDF, along with its Gaussian counterpart. Comment on the differences yousee between the two models.

?In this part of the lab, I am asked to plot the pdf generated from the Histogram and thepdf generated using Gaussians and the ML model. This plot is shown in figure 11. Ialso think that in order to completely understand the Statistical classification process,it is useful to plot the Gaussian Pdf's generated for each class (white matter, graymatter and Csf). This plot is shown in figure 12.

Figure 11. Comparison of the Pdf generated from the Histogram and the Pdf generatedusing Gaussians and the ML model for the White matter.

Page 11: postprocessing MRI images - Massachusetts Institute of

Figure 12. Gaussian Pdf's generated for each class (white matter, gray matter and Csf).

?Next we implement ML classification of the image intensities using the Gaussianmodels that we have constructed. The steps are the following.

i._Loop over the test slices and perform ML classification *read slice *use the values of the intensities in the image and calculate the probabilities using the Gaussian pdf for each class and store the results in the matrix W.

Question 8.

At this point, the matrix w (65536x3) contains the tissue likelihoods for each pixel in theimage img. Your task is to fill in the matrix "classification" with the ML classification ofthe image. "classification" has the same dimensions as img, and should contain theredefined tissue labels LABEL_WHITE, LABEL_GRAY, LABEL_CSF to indicate theclassification of the image. Seriously: try to do this the MATLAB way, and avoidlooping over pixels. Turn in your lines of code that go after this comment.

IN ADDITION: As the classifier runs, it displays the tissue likelihoods as well as the resulting classification. What different information do the likelihoods and classification contain? Turn in your answer to this question.

?In this part of the lab, I implemented the code to do the ML classification. The code isas follows.

Page 12: postprocessing MRI images - Massachusetts Institute of

classification=zeros(size(img));

% order in w white gray csfclassificationt = (w(:,1)>w(:,2)&w(:,1)>w(:,3))*LABEL_WHITE + ... (w(:,2)>w(:,1)&w(:,2)>w(:,3))*LABEL_GRAY + ... (w(:,3)>w(:,2)&w(:,3)>w(:,1))*LABEL_CSF;

%converting the image from a vector to a 256x256 matrixfor z = 1:256, classification(:,z) = classificationt(256*(z-1)+1:z*256);end

First, I create a temporal vector called classificationt to store the labels resulting from theclassification. Since W is now a one dimension vector containing all the labels, I have toconvert it again back to a 2D matrix representing an image. Once I have done thistransformation, I store the results in the Classification matrix.

?As the classifier runs, it displays the likelihood’s as well as the resulting classification.The difference between the likelihoods and classification is that the likelihoodsrepresent the areas of the image(pixels) which are more probable to belong to thedifferent classes (white, gray and csf). On the other hand, the classification is the resultof assigning the pixel to the class that its pdf has the greater value. For example,imagine that for pixel x, the white_pdf gives a value of 0.7, for gray_pdf gives a valueof 0.2 and for csf is 0.5. All these values are the likelihoods for the pixel, while theclassification is just white_pdf, since it is the one with highest value or probability.Figure 13 shows the original test image, Figure 14 the likelihoods image and Figure15 the classification image.

Figure 13. Original test image to be classified (Slice 26)

Page 13: postprocessing MRI images - Massachusetts Institute of

Figure 14. likelihoods for image Slice 26

Figure 15. Classification for image Slice 26.

Page 14: postprocessing MRI images - Massachusetts Institute of

Making the comparison between the classified image and the expert labeled image, wecan see that the main difference is that all the area located out of the head is classified asCSF, and thus, it shows in a yellow color in the classified image. This is because theintensity for the color black falls in the pdf of the CSF.

2.3_Brain Isolation

This part of the lab concerns an attempt at isolating the brain structure. The code(morphology.m) expects as inputs the slices that are labeled as white matter, gray matterand CSF. It uses the "conditional morphology/largest connected component" strategy toextract the brain.

Question 9.

You probably noticed that this brain isolation algorithm failed on slice 26. It may alsofail on other slices as well. Try to figure out a way to improve it so that it handles slice26, as well as 25-64. Turn in a summary of how well your improvement works.

Running the code, I noticed that it fail in slice 26. This is because the Brain isolationassumes a largest connected component strategy. This means, that it is going to classifythe largest connected component as the brain. This is expected to fail in some slices suchas slice 26, where the largest connected component is not the brain.

Before showing my strategy to improve the brain isolation, it worth looking at the stepsfollowed by the program morphology.m to isolate the brain.

?Loop for all the test images i._read the slice resulting from the classification step ii._extract the brain region (white matter + grey matter) to a matrix iii._erode the brain matrix extracted to disconnect it from the scalp iv._create a mask image containing all the labeled connected components v._sort the mask so that the largest connected component is the last object in the vector vi._assume brain is the largest connected component (extract last object in vector) vii._dilate the brain conditioned on original image viii._extract original white and grey matter pixels for each of the pixels in brain which have a value of 1. ix._return to step i

The improvement that I introduced for this brain isolation algorithm, is based on adding aspatial feature to the isolation. The original brain isolation is based on the classificationresult for each image and the assumption that the brain is the largest connectedcomponent. If the algorithm also consider the space location of the labeled connected

Page 15: postprocessing MRI images - Massachusetts Institute of

objects (x,y coordinates of the image), it would have an improved performance. So, sincethe (x,y) coordinates of each pixel are available at all times, I added this consideration tothe brain isolation algorithm.

I calculated the mean x, and mean y coordinate position for each of the labeled andconnected components (objects found), between steps v and vi of the brain isolationalgorithm.

Then, I calculated the mean x and mean y spatial coordinates for each of the labeledconnected objects of all the tests slices. I did this in order to know what where the higherand lower variation of the mean x and mean y values for all the correct and incorrectclassifications generated by the brain isolation algorithm. The variations I found can beseen on Table 1 and Table 2.

Minimum Variation Maximum VariationX mean 103 119Y mean 124 126

Table 1. Highest and lowest variations in the mean X and Mean Y values for the correctclassifications. (values are given in pixels)

Minimum Variation Maximum VariationX mean 180 181Y mean 124 126

Table 2. Highest and lowest variations in the mean X and Mean Y values for the incorrectclassifications. (values are given in pixels)

NOTE: Remember that the maximum X and Y values for all the slice images that we haveis 256x256 pixels.

Thus, based on the results shown in tables 1 and 2, I was able to set up a threshold for thecorrect and incorrect classifications for the X mean value. I did not use the Y mean valuebecause there is no considerable variation of it observed in correct and incorrectclassifications. The threshold that I used for the X mean value was 130. If the X mean ofthe largest connected component is greater than 130, then choose the second largestconnected component as the brain. Otherwise, select the largest connected component asthe brain.

Thus the code that I added between steps v and vi of the brain isolation algorithm is:

Page 16: postprocessing MRI images - Massachusetts Institute of

%CODE ADDED FOR IMPROVED CLASSIFICATION----------------------------------------

%brain is equal to the largest connected component brain_cc = (cc==I(num)); %calculating the x,y median position of largest connected component. 256 is maximum values [xvalues yvalues] = find(brain_cc==1); xmean = mean(xvalues) ymean = mean(yvalues) %if the largest connected component has a xmean greater than the largest xmean variation %for the correct brain classification, then the brain is the second largest connected %component if xmean > 130.0, brain_cc = (cc==I(num-1)); end %-----------------------------------------------------------------------------------

The code that I added works just fine for all the test images. The only problem is that Iwas not able to connect the two little missing parts of the brain to it. If I had more time, Iwould implement this important characteristic. The code for this improvement is found insection IV.

Figure 16 shows the initial classified image for (slice 26). Figure 17 Shows the erodedversion for the slice 26 image. Figure 18 Shows the connected components regions forslice 26 and Figure 19 Shows the brain region extracted (white + gray matter pixels).

Figure 16 shows the initial classified image for (slice 26)

Page 17: postprocessing MRI images - Massachusetts Institute of

Figure 17 Connected components regions for slice 26 after erosion

Figure 18 Brain region extracted (white + gray matter pixels)

Page 18: postprocessing MRI images - Massachusetts Institute of

2.4_ Validation

Question 10:

You will notice that your result is not the same as the "gold standard" that was done byan expert using better tools, in particular, he is getting good CSF segmentation, wherewe did not attempt to differentiate CSF from air. (But he also was using a T2 weightedscan that has good water contrast).

Figure out a way to quantify the agreement of your segmentation and his with respect towhite matter and gray matter in slice 41, and include that in your report.

In this part of the lab, I needed to figure out a code to qualify the agreement of myclassification and the one done by the expert. First of all, I would like to show you theImage of my classification and the one done by the expert for slice 41. Figure 20 showsmy classification and Figure 21 shows the classification done by the expert for slice 41.

Figure 19 My classification for slice 41

Page 19: postprocessing MRI images - Massachusetts Institute of

Figure 20 Classification done by the expert for slice 41

In order to quantify the agreement of my classification (segmentation) and the one doneby the expert, I am going to use an error approach.

If we examine the different errors that might happen during classification for whitematter and gray matter, we have three cases.

Case A

The expert classified a pixel as white matter and I did not classify that pixel as whitematter.

Case B

The expert classified a pixel as white matter and I also classified that pixel as whitematter.

Case C

The expert did not classify a pixel as white matter and I classified that pixel as whitematter.

The same cases A, B and C exist for the Grey matter case.

Page 20: postprocessing MRI images - Massachusetts Institute of

Now, lets see how can we calculate the erros Case A, B and C. The procedure is asfollows:

i._extract all the pixels classified as white matter from the expert image and store them in a matrix (ewmatter). ii._extract all the pixels classified as white matter from my classification image and store them in a matrix (wmatter). iii._Substract the my white matter pixel classification from the white matter pixel classification of the expert

wmismatches = ewmatter - wmatter;

Then, in the matrix wmismatches, we are going to have the following data according tothe class of error Case A, Case B and Case C.

We are going to have "1" 's if the error is the explained in Case A. We are going to have "0" 's if the error is the explained in Case B. We are going to have "-1" 's if the error is the explained in Case C.

Thus, we can just extract the number of elements in wmismatches which have values of 1and -1 to calculate the errors associated with cases A and C. If we multiply the numberof elements resulting for cases A and C by (100/total_number_pixels_in_image), we aregoing to have a percent of error for cases A and C.

The total error, can be quantified as follow:

TotalError = %Error_CaseA_ white_matter + %Error_CaseC_white_matter +%Error_CaseA_ gray_matter + %Error_CaseC_gray_matter

These are the results of all the calculations of the errors for slice 41. The program tocalculate the errors can be found in section V of the appendix.

Error_CaseA_ white_matter = 524 pixels of 65536Error_CaseA_ white_matter = 0.7996%

Error_CaseC_ white_matter = 500 pixels of 65536Error_CaseC_ white_matter = 0.7629%

Error_CaseA_ gray_matter = 1036 pixels of 65536Error_CaseA_ gray_matter = 1.5808%

Error_CaseC_ gray_matter = 764pixels of 65536Error_CaseC_ gray_matter = 1.1658%

Page 21: postprocessing MRI images - Massachusetts Institute of

Total_Error = 4.3091%

Figure 22 Shows the white matter classification error Case A + Case B, Figure 23 Showsthe grey matter classification error Case A + Case B, and Figure 24 Shows the Totalclassification error

Figure 21 Shows the white matter classification error Case A + Case B

Figure 22 Shows the gray matter classification error Case A + Case B

Page 22: postprocessing MRI images - Massachusetts Institute of

Figure 23 Shows the Total classification error (White & Grey matter errors shown indifferent colors)

3._ Rendering

This part of the lab involves an attempt to generate a simple 3D surface rendering of aportion of the white matter structure generated in the brain isolation part. Here I justinclude Three Pictures of the 3D visualization. Figures 25, 26 and 27 show differentviews of the 3d rendering of the white matter.

Figure 24 Side view of the 3D rendering of the white matter

Page 23: postprocessing MRI images - Massachusetts Institute of

Figure 25 Top view of the 3D rendering of the white matter

Page 24: postprocessing MRI images - Massachusetts Institute of

Figure 26 Front view of the 3D rendering of the white matterQuestion 10

What is the most important thing that you learned from this lab exercise?

Now, I feel I have a very strong understanding of how to use Statistical classification andImage processing in biomedical applications. I feel capable of using statisticalclassification in other domains such as computer Vision.

Question 11

What did you like/dislike the most about this lab exercise?

The most difficult part for me was the classification part. The part that I liked the mostwas the 3D rendering of the white matter, it is just amazing!

Page 25: postprocessing MRI images - Massachusetts Institute of

Apendix

Section IMATLAB code for the preprocess.m function% Here we will explore loading and displaying MRI slices,% and experiment with thresholding for separating white% matter from gray matter, and using blurring and% median filtering for noise reduction.

close all;

% read in a sagittal gradient-echo MRI slice into imgimg = mri_read('/mit/6.555/matlab/seg-lab/data/sw/spgr/I.082');

% display the imagefigure;show(img, 'original image');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Question 1.%% TURN IN:%% Print a picture of the slice and put it in your lab report.%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Page 26: postprocessing MRI images - Massachusetts Institute of

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% First we try to separate white matter from gray matter with thhreshoding.% try various thresholds...figure;% white matter thresholdedshow(img > 79, 'thresholded at 60');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Question 2.%% TURN IN:%% Try to find a good threshold for separating white and gray%% and say what it is in your lab report, and put in a picture%% of the result.%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% The segmentations showed the effects of the noise% that is present in the data.% Next we try some lowpass filtering (blurring) to reduce noise...% In these examples we use a dimention of 5 in both dimensions (5x5)

% sigma of 2 gives a segmentation that is pretty smoothed outgf = fspecial('gauss', 5, 1);%filtering the image with the 2D gaussian filterblur_img = filter2(gf, img, 'same');figure;show(blur_img,'blurred Image with sigma = 1');figure;show(blur_img > 80,'thresholded filtered image of sigma=1');

%display('Press a Key to continue');%pause;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Question 3.%% TURN IN:%% Try to find a smoothing standard deviation that is a "reasonable"%% compromise between structural faithfulness and noise reduction...%% say what the setting is and turn in a picture of the result.%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% try some median filtering...

% no noise, but too chunky:mf_img = medfilt2(img, [3 3]);figure;show(mf_img,'Image filtered with the median filter of order = 3');figure;

Page 27: postprocessing MRI images - Massachusetts Institute of

show(mf_img > 80,'thresholded median filtered image with 3x3 filter');

%no effect...%mf_img = medfilt2(img, 1);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Question 4.%% TURN IN:%% Try to find a combination of threshold and median filter neighborhood size%% that is a "reasonable"%% compromise between structural faithfulness and noise reduction...%% say what the setting is and turn in a picture of the result.%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Section IIMATLAB code for the classify.m program for statistical classificationclose all;

%we have 124 MRI images of the head of a person in the oo5 directory named slice.001 thru slice.124MRI_PREFIX = '/mit/6.555/matlab/seg-lab/data/case1/005/slice';%we also have 124 classified images by an expert named output.001 to output.124LABELS_PREFIX = '/mit/6.555/matlab/seg-lab/data/case1/seg_yoh/output';

%choosing the slices that are going to be used as trining data. In this case, just% 8 images 30 32 34 36 38 40 42 44TRAINING_SLICES = [30:2:44];

%choosing 39 slices for testing purposes.TEST_SLICES = [26:64];%defining the name of the files for our classification outputCLASSIFICATION_PREFIX='~/output/classification';

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Read and display an MRI slice and its segmentation%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

SLICE_NUM = 45; %slice number of the image to plot%% create the filename corresponding to the prefix and slice number%creating the name of the file to readmri_fn = sprintf('%s.%0.3d', MRI_PREFIX, SLICE_NUM);img = mri_read(mri_fn); %% read the mri image into img%creating the name of the file labeled by the expert to readlabels_fn = sprintf('%s.%0.3d', LABELS_PREFIX, SLICE_NUM);labels = mri_read(labels_fn); %% read the labelled img into labels

%% Display img using a grayscale colormap%% and labels using the default colormapfigure; imagesc(img); colormap(gray);title(mri_fn); axis off; colorbar;

figure; imagesc(labels); colormap('default');title(labels_fn); axis off; colorbar;

%disp('hit Control-C')%pause;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Next we will take some statistics on the

Page 28: postprocessing MRI images - Massachusetts Institute of

% intensities and build some class-conditional% probability models%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

LABEL_WHITE = 8;LABEL_GRAY = 4;LABEL_CSF = 5;

NUM_LABELS = 3;

colors = {'g', 'r', 'b', 'm'};

%% The following vectors will eventually hold all of the intensity%% values observed in the training data for their respective tissue%% classes.

intensity_white = [];intensity_gray = [];intensity_csf = [];

% The following loops over the training slices and collects% the intensity values that correspond to each tissue class

for i=TRAINING_SLICES %% read mri image mri_fn = sprintf('%s.%0.3d', MRI_PREFIX, i) img = mri_read(mri_fn);

%% read corresponding labelled img labels_fn = sprintf('%s.%0.3d', LABELS_PREFIX, i); labels = mri_read(labels_fn);

%% concatenate in the observed intensity values in this slice intensity_white = [intensity_white; img(find(labels == LABEL_WHITE))]; intensity_gray = [intensity_gray; img(find(labels == LABEL_GRAY))]; intensity_csf = [intensity_csf; img(find(labels == LABEL_CSF))];end

% Here is an example of how to display a histogram of the intensities observed% as white matterfigure;hist(intensity_white); title('White Matter Histogram');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Question 5.%% TURN IN:%%%% Histogramming is one approach to estimating probability density functions (PDFs).%% If you inspect the histogram plotted above, you may notice that%% it is not a legitimage PDF, because, when viewed as a function over%% the real line, it does not integrate to one.%%%% Your task in this problem is to implement a histogram based estimate of%% the PDF for the intensity of white matter in the training data.%%%% Your implementation will probably need to construct Matlab%% function that has two parts,%% one that constructs the state of the histogram from the training data,%% by, among other things, establishing an array of "bins" and%% counting the number of training data points that fall into each bin.%% (You may want to look at the documentation for the Matlab function "hist").%%%% The other part would implement the PDF itself as a function from real-valued%% intensities to probability density. In this situation, each bin will

Page 29: postprocessing MRI images - Massachusetts Institute of

%% corresponds to a range of intensity values. Keep in mind that probability density%% must be non-negative, and the PDF must integrate to one.%%%%%% There is some freedom available in making histograms, for example the%% choice of the number of bins. Plot your histogram-based PDF with%% several choices for bin count. Pick your favorite count,%% say why you think it is a good choice, and turn in%% the corresponding plot.%%%%%% In designing the code for this example, you might find it useful to%% refer to the documentation for the Matlab function "hist".%%%% Write a .m file that implements%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% here is an example of plotting our PDFIntensityValues = [1:.01:100];%range of values that we wish our new pdf function to have in x axisfigure;plot( IntensityValues, HistPDF(IntensityValues, intensity_white, 20));title('White matter histogrampdf');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Next we will estimate Gaussian class conditional models that are meant%% to capture the way the intensities depend on tissue class.%%%% The vectors below, "tissue_means" and "tissue_vars"%% will eventually hold the estimated tissue class mean and variance%% parameters for the estimated Gaussian densities, indexed by tissue%% being white, gray, or csf%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

tissue_means = [ mean(intensity_white) mean(intensity_gray) mean(intensity_csf)];tissue_vars = [ var(intensity_white) var(intensity_gray) var(intensity_csf)];

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Question 6.%% TURN IN:%%%% Your next task is to implement the maximum likelihood method for estimating%% the parameters of Gaussian class conditional densities.%%%% You will need to set the two vectors defined above with three values%% each that are derived from the observed class conditional intensities:%% intensity_white, intensity_gray, and intensity_csf. Turn in your%% lines of code that set values for "tissue_means" and "tissue_vars"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Page 30: postprocessing MRI images - Massachusetts Institute of

%%%%%%%%%%%%% Define the Gaussian density functiongauss = inline('(1/(sqrt(2*pi)*s))*exp(-(x-m).*(x-m)/(2*s*s))', 'x','m','s');%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Question 7.%% TURN IN:%%%% At this point we have estimated tissue class conditional PDFs%% on intensity by the use of Gaussian models.%% This was done by using the ML method%% to estimate the mean and variance parameters for each class, based%% on the training intensities.%%%% These Gaussian models may be visualized by plotting, e.g.%% plot(gauss([0:500], tissue_means(1), sqrt(tissue_vars(1))), 'r');%%%% Previously, we constructed and displayed a histogram estimate of the%% PDF for white matter.%%%% Arrange for a plot that, for white matter, shows the histogram based%% PDF, along with its Gaussian counterpart. Comment on the differences you%% see between the two models.%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%figure;hold;plot(0:100,gauss([0:100], tissue_means(1), sqrt(tissue_vars(1))), 'r',IntensityValues, HistPDF(IntensityValues, intensity_white,20),'b');title('White matter histogrampdf vs Gaussian pdf')legend('Gaussian pdf','Histogram pdf');hold;

%code not necesary, but for visualizing the different pdfs of tissuesfigure;plot(0:100,gauss([0:100], tissue_means(1), sqrt(tissue_vars(1))), 'k',0:100,gauss([0:100], tissue_means(2), sqrt(tissue_vars(2))),'r',0:100,gauss([0:100], tissue_means(3), sqrt(tissue_vars(3))), 'b');title('Gaussian pdfs for all tissue');legend('white pdf','Gray pdf','Csf pdf');%end of visualization code

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Next we will implement ML classification of the image intensities%% using the Gaussian models that we have constructed.%%%% The following code loops over the test slices and performs ML classification.%%%% Each slice is read in%%%% for that slice, 3 images are displayed showing the likelihoods%% for each tissue%%%% (after you supply the missing code) the tissue class is determined for each%% pixel%%%% the resulting classifications are then written out for subsequent processing%% later in the lab.%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Page 31: postprocessing MRI images - Massachusetts Institute of

figure(7); figure(8); %create windows with names 1 and 2set(1, 'nextplot', 'replace') %set the names for figure 1%for all the test slices images dofor i=TEST_SLICES %% read mri image mri_fn = sprintf('%s.%0.3d', MRI_PREFIX, i) img = mri_read(mri_fn);

for k=1:NUM_LABELS w(:,k) = gauss(img(:), tissue_means(k), sqrt(tissue_vars(k))); end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Display the tissue likelihoods for the pixels in the slice %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Change 1 to zero to suppress display of tissue likelihoods if 1 figure(9); imagesc([reshape(w(:,1), size(img));reshape(w(:,2), size(img));reshape(w(:,3), size(img))]); colormap(gray) title('tissue likelihoods'); end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Question 8.%% TURN IN:%%%% At this point, the matrix w (65536x3) contains the tissue likelihoods%% for each pixel in the image img.%% Your task is to fill in the matrix "classification"%% with the ML classification of the image.%% "classification" has the same dimensions as img,%% and should contain the predefined tissue labels%% LABEL_WHITE, LABEL_GRAY, LABEL_CSF%% to indicate the classification of the image.%% Seriously: try to do this the MATLAB way, and%% avoid looping over pixels.%% Turn in your lines of code that go after this comment.%%%% IN ADDITION: As the classifier runs, it displays the tissue likelihoods%% as well as the resulting classification. What different information do%% the likelihoods and classification contain?%% Turn in your answer to this question.%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% put your code hereclassification=zeros(size(img));

% order in w white gray csfclassificationt = (w(:,1)>w(:,2)&w(:,1)>w(:,3))*LABEL_WHITE + ... (w(:,2)>w(:,1)&w(:,2)>w(:,3))*LABEL_GRAY + ... (w(:,3)>w(:,2)&w(:,3)>w(:,1))*LABEL_CSF;

%converting the image from a vector to a 256x256 matrixfor z = 1:256, classification(:,z) = classificationt(256*(z-1)+1:z*256);end

% Display the image and classification

Page 32: postprocessing MRI images - Massachusetts Institute of

figure(7); imagesc(img); colormap(gray); colorbar;title(mri_fn); axis off; figure(8); imagesc(classification); colormap('default'); colorbar; title(mri_fn); axis off;

% Write out the classification for use downstream out_fn = sprintf('%s.%0.3d', CLASSIFICATION_PREFIX, i) mri_write(classification, out_fn);

fprintf(1, 'Hit any Key to Continue\n');%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CHANGE ME BACK%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

pause; %pause in each classification of the imageend

Section IIIMATLAB code for the HistPDF.m program

function Density = HistPDF(Intensity, TrainingData, NumBins)

% TotalCount holds the number of data points in the training data. TotalCount = length(TrainingData);

% BinCounts holds the number of data values that correspond each bin, % while BinCenters hold the coordinate of the center of each bin. % (again, you might look at the matlab function "hist" [BinCounts, BinCenters] = hist(TrainingData,NumBins);

% BinWidth corresponds to the width of the bins. BinWidth = BinCenters(2) - BinCenters(1);

% IntensityLow has a value corresponding to the left edge of the leftmost bin IntensityLow = BinCenters(1) - BinWidth/2;

% Loop over the intensity values that are input to this implementation % of a histogram based PDF. RetrievedCounts(1:length(Intensity)) = 0; for i = 1 : length(Intensity) %for each intensity present in the model index = 1 + floor((Intensity(i) - IntensityLow) / BinWidth); if (index >= 1) & (index <= size(BinCounts,2)) RetrievedCounts(i) = BinCounts(index); end end

% Establish a normalization of the returned PDF values such that % the PDF being implemented integrates to one. Normalization = 1/(TotalCount*BinWidth)

% Return the probability density corresponding to the input intensity Density = Normalization * RetrievedCounts;

Section IVMATLAB code for the morphology.m program for brain isolation

% This file contains an attempt at brain isoloation for MRI.% It expects as input slices that are labelled as% white matter, gray matter, and other stuff.

% It uses the "conditional morphology / largest connected component"% strategy.close all;

Page 33: postprocessing MRI images - Massachusetts Institute of

MRI_PREFIX = '../data/case1/005/slice';LABELS_PREFIX = '../data/case1/seg_yoh/output';CLASSIFICATION_PREFIX='~/output/classification';BRAIN_PREFIX='~/output/brain'; % name of the output files

TEST_SLICES = [26:64];

LABEL_WHITE = 8;LABEL_GRAY = 4;LABEL_CSF = 5;LABEL_AIR = 0;

num_labels = 3;colors = {'g', 'r', 'b', 'm'};

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% post-process using morphology%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

for i=TEST_SLICES out_fn = sprintf('%s.%0.3d', CLASSIFICATION_PREFIX, i) img = mri_read(out_fn); brain = (img == LABEL_WHITE | img == LABEL_GRAY);

figure(1); show(brain, 'initial brain pixels (White and Gray matter)'); %applying erotion to the brain brain_eroded = bwmorph(brain, 'erode', 1);

figure(4); show(brain_eroded, 'eroded brain pixels ');

%creating the mask image CC which contains the labelled connected objects %num contaings the number of connected components found. The function searches for %8 connected components by default [cc, num] = bwlabel(brain_eroded);

figure(5); show(cc*2, 'connected components');

% size_cc may have leftover stuff in it from last time around... size_cc = 0;

%now, for all the connected components, we calculate their size %by counting the number of pixels that have the same label assigned for j=1:num size_cc(j) = length(find(cc==j)); end %sort the sizes so that the last object is the bigger one [Y, I] = sort(size_cc); %% %% This code asssumes that after erosion to disconnect the structures, %% that the brain will be the largest connected component that is %% found (by the MATLAB function bwlabel). %% This assumption may fail under some circumstances... %% %% pick the largest connected component

%CODE ADDED FOR IMPROVED CLASSIFICATION-----------------------------------------------------------------------------------------------------------------------------------------------------------

%brain is equal to the largest connected component brain_cc = (cc==I(num)); %calculating the x,y median position of largest connected component 256 is maximum values [xvalues yvalues] = find(brain_cc==1); xmean = mean(xvalues) ymean = mean(yvalues) %if the largest connected component has a xmean greater than the largest xmean variation %for the correct brain classification, then the brain is the second largest connected

Page 34: postprocessing MRI images - Massachusetts Institute of

%component if xmean > 130.0, brain_cc = (cc==I(num-1)); end

%------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

figure(2); show(brain_cc*2, 'brain connected component emt');colorbar;

%% dilate it conditioned on original image brain_dilated = bwmorph(brain_cc, 'dilate', 2); brain_conditionally_dilated = double(brain_dilated).*brain;

%% put back white and gray labels white_matter = zeros(size(img)); white_matter = brain_conditionally_dilated .* (img == LABEL_WHITE); white_matter(find(white_matter)) = LABEL_WHITE; gray_matter = zeros(size(img)); gray_matter = brain_conditionally_dilated .* (img == LABEL_GRAY); gray_matter(find(gray_matter)) = LABEL_GRAY; out_fn = sprintf('%s.%0.3d', BRAIN_PREFIX, i) mri_write(gray_matter+white_matter, out_fn);

figure(3); imagesc(white_matter+gray_matter); figure(3); show(white_matter+gray_matter, 'classification for isolated brain'); fprintf(1, 'Hit any Key to continue\n'); pauseend

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Question 9.%% TURN IN:%%%% You probably noticed that this brain isolation algorithm failed%% on slice 26. It may also fail on other slices as well...%% Try to figure out a way to improve it so that it handles%% slice 26, as well as 25-64.%% Turn in a summary of how well your improvement works.%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Section VMATLAB code for the Validation.m function to quantify errors

close allMRI_PREFIX = '/mit/6.555/matlab/seg-lab/data/case1/005/slice';LABELS_PREFIX = '/mit/6.555/matlab/seg-lab/data/case1/seg_yoh/output';CLASSIFICATION_PREFIX='~/output/classification';BRAIN_PREFIX='~/output/brain';

LABEL_WHITE = 8;LABEL_GRAY = 4;LABEL_CSF = 5;

Page 35: postprocessing MRI images - Massachusetts Institute of

LABEL_AIR = 0;

num_labels = 3;

TEST_SLICE = 41;

% read and display your result for slice 41.my_result_fn = sprintf('%s.%0.3d', BRAIN_PREFIX, TEST_SLICE);my_result = mri_read(my_result_fn);

% read and display expert's result for slice 41.gold_standard_fn = sprintf('%s.%0.3d', LABELS_PREFIX, TEST_SLICE);gold_standard = mri_read(gold_standard_fn);

figure;show(my_result,'My Classification Result');

figure;show(gold_standard,'Expert Classification Result');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Question 10:%% TURN IN:%%%% You will notice that your result is not the same as the%% "gold standard" that was done by an expert using better%% tools, in particular, he is getting good CSF segmentation,%% where we did not attempt to differentiate CSF from air.%% (But he also was using a T2 weighted scan that has good%% water contrast).%%%% Figure out a way to quantify the agreement of your segmentation and his%% with respect to white matter and gray matter in slice 41, and include that%% in your report.%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%First, lets extract the white matter from the expert classification imageewmatter = gold_standard == LABEL_WHITE;%then, lets extract my_result white matterwmatter = my_result == LABEL_WHITE;%now lets see how many mismatches are therewmismatches = ewmatter - wmatter;%calculate false positive errorwfalsepositive = length(find(wmismatches==1))%false positive in percentwfalsepositivep = wfalsepositive * (100/65536)%calculate false negative errorwfalsenegative = length(find(wmismatches==-1))%false negative in percentwfalsenegativep = wfalsenegative * (100/65536)

%First, lets extract the gray matter from the expert classification imageegmatter = gold_standard == LABEL_GRAY;%then, lets extract my_result gray mattergmatter = my_result == LABEL_GRAY;%now lets see how many mismatches are theregmismatches = egmatter - gmatter;%calculate false positive errorgfalsepositive = length(find(gmismatches==1))%false positive in percentgfalsepositivep = gfalsepositive * (100/65536)%calculate false negative error

Page 36: postprocessing MRI images - Massachusetts Institute of

gfalsenegative = length(find(gmismatches==-1))%false negative in percentgfalsenegativep = gfalsenegative * (100/65536)

%now, calculating the total error in the classificationtotalerror = gfalsepositivep + gfalsenegativep + wfalsepositivep + wfalsenegativep

%graph of white matter errorfigure;show(abs(wmismatches),'White matter error');

%graph of gray matter errorfigure;show(abs(gmismatches),'gray matter error');

%calculate absolute value to eliminate negative signs of the substraction procedure and%be able to graph the error in classificationwmismatches = abs(wmismatches) + abs(gmismatches);figure;show(wmismatches,'Total error: mismatches in the classification');

Section VIMATLAB code for the RenderLeo02lab.m 3D visualization of white matter structure

% This is Leo's code, attempting to create a 3D visualization% of the contour of the white matter

% This file contains a quick hack for doing% a simple 3d surface rendering of% the white matter structure.

% The graph is rendered in 3d with realistic shading, and 3D% interaction is enabled so that the operator can flip% it round with the mouse.

% change the prefix to your own...BRAIN_PREFIX='~/output/brain';

TEST_SLICES = [29:64];

LABEL_WHITE = 8;LABEL_GRAY = 4;LABEL_CSF = 5;LABEL_AIR = 0;

num_labels = 3;colors = {'g', 'r', 'b', 'm'};

volume = - ones (256,256,length(TEST_SLICES));for i=1:length(TEST_SLICES) in_fn = sprintf('%s.%0.3d', BRAIN_PREFIX, TEST_SLICES(i)) img =(mri_read(in_fn)); % first insert the slice as a slice of a matrix volume (:,:,i) = img;endwhite = zeros(size(volume));white(find(volume == LABEL_WHITE)) = LABEL_WHITE;whiteS = smooth3(white);hiso = patch(isosurface(whiteS,5),... 'FaceColor',[1,.75,.65],... 'EdgeColor','none');axis tightlightangle(180,180);set(gcf,'Renderer','zbuffer'); lighting phong

Page 37: postprocessing MRI images - Massachusetts Institute of

isonormals(whiteS,hiso)set(hiso,'SpecularColorReflectance',0,'SpecularExponent',50)rotate3dview(0,-55)