Image Processing with MATLAB Applications in Medicine and Biology Sourse

download Image Processing with MATLAB Applications in Medicine and Biology Sourse

If you can't read please download the document

Transcript of Image Processing with MATLAB Applications in Medicine and Biology Sourse

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/hgrad.mfunction gf = hgrad(dI,k)% HGRAD Diffusivity functions%% gf = HGRAD(K,DI)%% Favors high gradients% K: Noise threshold, DI: image gradient%% See also WEICKERT WREGION TUKEYBIWEIGHT

% Omer Demirkaya, Musa Asyali, Prasana Shaoo, ... 9/1/06% Medical Image Processing Toolbox

gf = exp(-(dI/k).^2);

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/Image Processing With Matlab.pdfPage 1 Image Processing With Matlab

06/07/2009 10:13:40http://biomedimaging.org/BookMFiles.aspx

I m a g e P r o c e s s i n g w i t h M A T L A B

A p p l i c a t i o n s in M e d i c i n e a n d B i o l o g y

ImageProcessing

BookHome

BookImages

Book MFiles

Aboutthe Book

AbouttheAuthors

Table ofContents

Contact

Errata

ReaderComments

Book M Files

Function Description

hgrad.m

kfun.m

ksw_method.m

mipadfoned.m Performs 1-D PeronaMalik diffusion.

mipaffinecurvaturemove.m Performs affine curvature motion diffusion.

miparcshapeindex.m Computes both the eigenvalues and the shape index for an arc consisting ofset of points.

mipbackwarddiff.m Compute forward, backward and central differencesof an image.

mipbcv.m Computes the between-class variance, the optimal threshold based on itsmaximization.

mipbcviterative.m This is the iterative version of the mipbcv for three regions; thus it returnstwo thresholds.

mipboundingbox3d.m

mipbrink_thresh.m This function returns the optimal threshold value using the 2-D Shannonentropy method.

mipcentraldiff.m Compute forward, backward and central differences of an image.

mipcircconv.m Performs circular convolution on closed boundaries.

mipcircularity.m Calculates the circularity.

mipcmean.m Computes the mean from a histogram for a range of intensities.

mipconstants.m Provides/returns the commonly used constants in the basic sciences.

mipcorrcoef3d.m Computes the 3-D correlation coefficient.

mipcorrimage.m Simulates an image with correlated pixels.

mipcurvature.m Computes the curvature of boundary points.

mipcvar.m Computes the variance from a histogram for a range of intensities.

mipdisclaimer.m

mipdiskimage.m Creates a disk image of a given radius.

Page 2 Image Processing With Matlab

06/07/2009 10:13:40http://biomedimaging.org/BookMFiles.aspx

mipdog.m Computes and returns the derivative of a 1-D Gaussian.

mipentropy_th.m This function computes an optimal threshold using the entropy-basedcriterion function.

mipfcmSegmentation.m Segments the input image by fuzzy C-means algorithm and returns themultilevel image at the output. It requires number of regions as the input.

mipfitellipse.m This is Fitzgibbons algorithm that fits ellipse to a set of boundary points.The algorithm is provided as it is in his Web site except that it is renamed .

mipforwarddiff.m Compute forward, backward and central differences of an image.

mipgauss.m Creates 1-, 2-D and 3-D Gaussian functions of a given size sigma.

mipgibbs2d2r.m

mipgibbs2dmr.m

mipgray2multilevel.m Converts a gray-level image to multilevel images of n regions, which take onvalues from 1 to n, using the thresholds t1,...,tn-1.

miphexagon.m mipstructuretensor Computes the structure tensor of an image. Simulates ahexagon image.

miphisto2d.m Computes 2-D histograms

mipicm2d2r.m The ICM algorithm for 2-D images with two regions (2r)

mipicm2dmr.m The ICM algorithm for 2-D images with multiple regions (mr)

mipicm3d.m

mipicmvectorized2dmr.m This is the vectorized version of the ICM algorithm that updates every pixelin parallel.

mipimbin.m Bins (by summing) image pixels rowwise or columnwise to create a smallerimage

mipimgauss.m Adds Gaussian noise to an existing image.

mipimhist.m Computes the histogram.

mipimoverlay.m Overlays a binary image on a gray-level image and returns the overlaidimage.

mipisodiffusion2d.m Performs 2-D nonlinear scalar diffusion, in which the

mipisodiffusion3d.m Performs 3-D nonlinear scalar diffusion. It is the 3-D version of the functionmipisodiffusion2d.

mipjhist.m Computes 2-D histogram of the joint distribution of two images.

mipkittler.m

mipkmeansSegmentation.m Segments the input image by K-means clustering algorithm and returns themultilevel image at the output. It requires number of regions as the input.

mipkurita.m Computes the Kuritas criterion function and the optimal thresholds basedon its maximization.

Page 3 Image Processing With Matlab

06/07/2009 10:13:40http://biomedimaging.org/BookMFiles.aspx

miplinearoned.m

miplinoned.m Performs 1-D linear filtering using the Laplacian.

mipmapCTwindow.m Performs windowing on CT images.

mipmetropolis2d2r.m

mipmetropolis2dmr.m

mipminerror.m Computes the minimum error function criterion and the optimal thresholdsbased on its minimization.

mipneighborhood2d.m Gets the intensities of the 2-D neighborhood 4-pixel or 8-pixel.

mipneighborhood3d.m The 3-D version of mipneighborhood2d

mipnormscattermat.m Computes the scatter matrix.

miporthogonal.m Creates orthogonal views from a 3-D image

mippermaliktwod.m

mipregionstats.m Computes the statistics of regions given a gray-level and a binary image inwhich each region is labeled with a different label.

mipresolutionLineProfile.m

miprmdebrisn.m Removes small objects from a binary 2-D or 3-Dimage.

mipsahoo_thresh.m This function returns the optimal threshold value using the 2-D Tsallisentropy method.

mipsample_discretedist.m

mipsdog.m Computes and returns the second derivative of a 1-D Gaussian.

mipsecondderiv.m Computes the second derivative Ixx or Iyy of an image I.

mipsecondpartialderiv.m Compute the second partial derivative Ixy or Iyx

mipsigmoid2d.m Creates a 2-D sigmoid function.

mipsigmoidoned.m Creates a 1-D sigmoid function.

mipsphereimage.m Creates a sphere of known size.

mipsphereshell.m

mipstructuretensor.m Computes the structure tensor of an image. miphexagon Simulates ahexagon image.

mipTotalEnergy.m Computes the total energy.

miptvdiffusion.m Performs total-variationbased diffusion.

mipvolprop.m Calculates the volume properties.

Page 4 Image Processing With Matlab

06/07/2009 10:13:40http://biomedimaging.org/BookMFiles.aspx

removeundefinedNums.m mip Removes undefined numbers such infs and nans

sa_method.m

tukeybiwieght.m

UnivarGMixFit_Segment.m mip Segments images via Gaussian/normal mixture modeling.

weickert.m

wregion.m

Hosted by NIOBEWEB.NET

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/kfun.mfunction k = kfun(pdf,th)% KFUN Determining noise threshold%% k = KFUN(PDF,TH)%% % TH: threshold, PDF: image probability distribution function%% See also

% Omer Demirkaya, Musa Asyali, Prasana Shaoo, ... 9/1/06% Medical Image Processing Toolbox

flag = 1;temp_var = pdf(1);psize = size(pdf,2);for i = 2:psize; if (temp_var >= th & flag) k = i; flag = 0; break; end; temp_var = temp_var + pdf(i); end;

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/ksw_method.m% Matlab Script: ksw_method.m%% This Matlab scipt computes an optimal threshold value using% the concept of Shannon's entropy and then using the optimal % value binarizes an image.% The binarized image is displayed along with the original % image, its gray level histogram, and the plot of the % objective function, TotalEnt.%% To run this scipt, you have to input the name of an % image such as rice.tif or tire.tif. %% This script runs only for tif or gif images. clear allclcNBINS = 256;%% Read the user supplied image file%IMAGE = input('Please enter the name of the tif image: ', 's');I = imread(IMAGE);I3 = double(I);numgray = NBINS;I2 = I;%% Function mipentropy_th.m is used here%[graylevel, nco, h] = mipentropy_th(I3, NBINS);threshold = graylevel/numgray;BW2 = im2bw(I2, threshold);%disp(' ')fprintf('The optimal threshold value is %3.0f \n', graylevel)disp(' ')%% Display the original, binarized images and other% information relevent to this thresholding method.subplot(2,2,1), imshow(I2) title('original image') subplot(2,2,2), plot(ii,h),title('gray level histogram') axis('square');subplot(2,2,3), imshow(BW2); title('thresholded image') subplot(2,2,4), plot(ii,0.5*nco)title('normalized \psi (s) function'); axis('square');%% To print the figure into a file type from the command % window print myfigure.ps. The figure will be save in % postscript format in a file called "myfigure.ps"%print myfigure.ps

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/mipadfoned.mfunction diffux = mippermalikoned(x,n,k,Lambda) % MIPADFONED 1-D Ansitropic diffusion: Perona-Malik Scheme%% DIFFUX = MIPPERMALIKONED(X,N,K,LAMDA)%% X: Original signal, N: number of iterations% K: Noise threshold, Lamda: stability constant%% See also MIPPERMALIKTWOD MIPLINONED

% Omer Demirkaya, Musa Asyali, Prasana Shaoo, ... 9/1/06% Medical Image Processing Toolbox

% zero paddingdiffux = padarray(x,[0 1],'symmetric','both');deltaE = zeros(size(diffux));deltaW = diffux;for i = 1:n % Derivatives in East and West directions deltaE(2:end-1) = diffux(3:end) - diffux(2:end-1); deltaW(2:end) = diffux(1:end-1) - diffux(2:end); % Diffusivity cE = exp(-(deltaE/k).^2); cW = exp(-(deltaW/k).^2); % Fluxes fluxE = cE.*deltaE; fluxW = cW.*deltaW; % Update the diffusion process diffux = diffux + Lambda*(fluxE + fluxW);end% Unpadding signaldiffux = diffux(2:end-1);

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/mipaffinecurvaturemove.mfunction dimg = mipaffinecurvaturemove(img,NofI,lambda);% MIPAFFINECURVATUREMOVE PDE based image diffusion%% DIMG = MIPAFFINECURVATUREMOVE(IMG,NOFI, LAMBDA)%% Diffuses images using Sapiro's affine invariant evolution equation% img : input image% lambda : (diffusion speed) assumes values in the range [0, 0.25]%% dimg : output image%% See also MIPISODIFFUSION2D MIPMIPTVDIFFUSION

% Omer Demirkaya, Musa Asyali, Prasana Shaoo, ... 9/1/06% Medical Image Processing Toolbox

[row,col]= size(img);% zero padding around the imagedimg = padarray(img,[1 1 1],'symmetric','both');dx = zeros(size(dimg));dy = dx;dxy = dx;dx2 = dx;dy2 = dx;epsilon = 0.01;for i=1:NofI nimg = dimg; dx(:,2:col+1) = nimg(:,3:col+2)-nimg(:,1:col); dx = dx./2; dy(2:row+1,:) = nimg(3:row+2,:)-nimg(1:row,:); dy = dy./2; dxy(2:row+1,2:col+1) = nimg(3:row+2,3:col+2)+nimg(1:row,1:col)-nimg(3:row+2,1:col)-nimg(1:row,3:col+2); dxy = dxy./4; dx2(2:row+1,2:col+1) = nimg(2:row+1,3:col+2)+nimg(2:row+1,1:col)-2*nimg(2:row+1,2:col+1); dy2(2:row+1,2:col+1) = nimg(3:row+2,2:col+1)+nimg(1:row,2:col+1)-2*nimg(2:row+1,2:col+1); curv = dy2.*(dx.*dx) + dx2.*(dy.*dy) - 2*dx.*dy.*dxy;% curv = curv./((dx.*dx) + (dy.*dy)+ epsilon); curv(isnan(curv)) = 0; abs_curv = abs(curv); abs_curv = lambda*(abs_curv).^(1/3); flag_neg = curv < 0; flag_pos = curv >= 0; flag = flag_pos - flag_neg; abs_curv = flag.*abs_curv; dimg = dimg + abs_curv;end;dimg = dimg(2:row+1,2:col+1);

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/miparcshapeindex.mfunction [d, lamda] = miparcshapeindex(nsmat)% MIPARCSHAPEINDEX %% [D,LAMDA] = MIPARCSHAPEINDEX(NSMAT)%% This function calculates the eigenvalues (lamda) and the shape index d% from the norm. scatter matrix% See also

% Omer Demirkaya, Musa Asyali, Prasana Shaoo, ... 9/1/06% Medical Image Processing Toolbox

lamda = eig(nsmat);d = sqrt(1-4*det(nsmat));

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/mipbackwarddiff.mfunction dimg = mipbackwarddiff(img,direction)% MIPFORWARDDIFF Finite difference calculations %% DIMG = MIPBACWARDKDIFF(IMG,DIRECTION)%% Calculates the central-difference for a given direction% IMG : input image% DIRECTION : 'dx' or 'dy'% DIMG : resultant image%% See also MIPCENTRALDIFF MIPFORWARDDIFF MIPSECONDDERIV% MIPSECONDPARTIALDERIV

% Omer Demirkaya, Musa Asyali, Prasana Shaoo, ... 9/1/06% Medical Image Processing Toolbox

img = padarray(img,[1 1],'symmetric','both');[row,col]=size(img);dimg = zeros(row,col);switch (direction) case 'dx', dimg(:,2:col) = img(:,2:col)-img(:,1:col-1); case 'dy', dimg(2:row,:) = img(2:row,:)-img(1:row-1,:); otherwise, disp('Direction is unknown');end;dimg = dimg(2:end-1,2:end-1);

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/mipbcv.mfunction [th,bmax,cf,cbin] = mipbcv(x,nbins) % MIPBCV Threshold computation based on between-class variance%% [TH,BMAX,CF,CBIN] = MIPBCV(X,NBINS)%% This function will compute the threshold based on the bcv's criterion % for the image given in X. NBINS represents the number of bins. The % default value for NBINS is 64. It returns threshold TH, the maximum % of the criterion function CMAX and the criterion function CF.%% See also MIPBCVITERATIVE, MIPKURITA MIPMINERROR

% Omer Demirkaya, Musa Asyali, Prasana Shaoo, ... 9/1/06% Medical Image Processing Toolbox

warning off all

if nargin == 1 nbins = 64;end

% compute histogram[h,cbin] = mipimhist(x,nbins);% find the indices for max&min gray levels max_indx = max(find(h));min_indx = min(find(h));% initilize variablestotalMean = mipcmean(h,1,max_indx);prevProb1 = 0;mean1 = 0;cf = zeros(1,nbins);for i = min_indx:max_indx prob1 = prevProb1 + h(i); prob2 = 1-prob1; mean1 = (prevProb1*mean1 + h(i)*i)/prob1; mean2 = mipcmean(h,i+1,max_indx); t1 = mean1-mean2; cf(i) = prob1*prob2*t1*t1; prevProb1 = prob1;end;

totalvar= mipcvar(h,totalMean,min_indx,max_indx);

if totalvar > 0 cf = cf/totalvar;end;

[bmax,cmax_indx] = max(cf);th = cbin(cmax_indx);

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/mipbcviterative.mfunction [t1,t2] = mipbcviterative(x,nbins)% MIPBCV Threshold computation based on between-class variance for% trimodal images%% [T1,T2] = MIPBCVITERATIVE(X,NBINS)%% This function will compute the thresholds based on the between-class % variance for the image given in X. NBINS represents the number of bins. % The default value for NBINS is 64. It returns thresholds T1 and T2.%% See also MIPBCV MIPKURITA

% Omer Demirkaya, Musa Asyali, Prasana Shaoo, ... 9/1/06% Medical Image Processing Toolbox

warning off all

if nargin == 1 nbins = 64;end

[h,cbin] = mipimhist(x,nbins); % find the indices for max&min gray levels max_indx = max(find(h));min_indx = min(find(h)); hstep = median(diff(cbin));kmax = max_indx - min_indx;t1 = fix(min_indx + kmax/3.0);t2 = fix(min_indx + kmax*2.0/3.0);pe1 = 0;pe2 = 0;FLAG = 1;min_indx = fix(min_indx);while (FLAG) e1 = (mipcmean(h, min_indx,t1) + mipcmean(h,t1 + 1,t2))/2.0 - t1; e2 = (mipcmean(h,t1 + 1,t2) + mipcmean(h,t2 + 1, max_indx))/2.0 - t2; if pe1 == e1 & pe2 == e2 FLAG = 0; end; pe1 = e1; pe2 = e2; t1 = t1 + fix(e1); t2 = t2 + fix(e2);end;

t1 = cbin(t1);t2 = cbin(t2);

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/mipboundingbox3d.mfunction Ldatao = mipboundingbox3d(Ldata,ImSize)% MIPBOUNDINGBOX3D%% DIMG = MIPBOUNDINGBOX3D(LDATA,IMSIZE,CNST)% This function calculates the bounding box around a 3D object % in a 3D image% Inputs: % Ldata is the structure, the output of regionprops, with at least,% PixelList field. The function uses the pixel list to calculate the% bounding box.% ImSize is the size of the 3D image e.g., size(img)% Output:% Ldata.boundBox% Example: % Ldata = mipboundingbox3d(Ldata,size(img))% Ldata.boundBox =[xmin xmax ymin ymax zmin zmax] % One can extract this volume using MATLAB's subvolume function%% See also %

% Omer Demirkaya, Musa Asyali, Prasana Shaoo, ... 9/1/06% Medical Image Processing Toolbox

aborder = [1 ImSize(2) 1 ImSize(1) 1 ImSize(3)]; % [1 x 1 y 1 z]ido = [1,3,5];ide = [2,4,6];bbox = zeros(1,6);nObjects = length(Ldata);Ldatao = Ldata;constant = 1;for i=1:nObjects p = Ldata(i).PixelList; minp = min(p,[],1); maxp = max(p,[],1); bbx = [minp(1)-constant, maxp(1)+constant,... minp(2)-constant,maxp(2)+ constant,... minp(3)-constant maxp(3)+constant]; % checks for the borders of the image since we add and subtract 1 from % the minima and maxima, respectively. bbox(1,ido) = max(bbx(1,ido),aborder(1,ido)); bbox(1,ide) = min(bbx(1,ide),aborder(1,ide)); Ldatao(i).BoundBox = bbox;end

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/mipbrink_thresh.m% This function returns the optimal threshold value using the% two-dimensional Shannon entropy method. %function newmaxgray = mipbrink_thresh(I, numgray);[nrow, ncol] = size(I);%% Compute the averaged image I3 using a 3-by-3 sliding window% This is accomplished using colfilt command. This command works% for 'tif' image only. For other format images like jpeg, this% the command colfilt has to be appropriaely modified. %I3 = uint8(floor(colfilt(I,[3 3],'sliding','mean')));%% Compute the co-occurence matrix.%I = double(I) + 1;I3 = double(I3) + 1;for k = 1:numgrayfor l = 1:numgrayN(k,l) = 0;endendfor i = 1:nrowfor j = 1:ncolm = I(i,j);n = I3(i,j);N(m,n) = N(m,n) + 1;endend%% Computation of two-dimensional cumulative sum.% The cumsum command of the matlab has been used% appropriately for this purpose.%P = N/sum(sum(N));Pcumsum = cumsum(cumsum(P),2);for i = 1:numgrayfor j = 1:numgrayif Pcumsum(i,j) == 0 | Pcumsum(i,j) == 1Pcumsum1(i,j) = 50000;elsePcumsum1(i,j) = Pcumsum(i,j);endendend%% Computation of AAa matrix.%Pcumsumal = Pcumsum1;Pal = P;PalcumsumA = cumsum(cumsum(Pal),2);norPalcumsumA = PalcumsumA./Pcumsumal;AAa = norPalcumsumA;%% Computation of BBb matrix. %Pnew = fliplr(flipud(Pal));PalcumsumB = cumsum(cumsum(Pnew),2);I4 = PalcumsumB;I4(numgray, :) = [];I4(:, numgray) = [];I5 = fliplr(flipud(I4));u = zeros(numgray-1, 1);v = zeros(1, numgray);I6 = [I5 u];I7 = [I6; v];norPalcumsumB = I7./abs((1 - Pcumsum1)); BBb = norPalcumsumB;%% Replace the zero or undefined entries of matrices% AAa and BBb by one so that log(1) will be 0.%for i = 1:numgrayfor j = 1:numgrayif BBb(i,j) < 0.000001BBb(i,j) = 1;endif AAa(i,j) < 0.000001AAa(i,j) = 1;endendend%% Compute object, background and total entropies % in the sense of Shannon. Then compute the optimal % threshold.%Entb = - AAa.*log(AAa);Entw = - BBb.*log(BBb);TotalEnt = Entb + Entw;%% Maximize the total entropy to calculate the optimal% threshold value and then threshold the image in BW.%[maximum, rowindex] = max(TotalEnt);[maximax, colindex] = max(maximum);maxgray = rowindex(colindex);newmaxgray = maxgray - 1;newmaxgray;

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/mipcentraldiff.mfunction dimg = mipcentraldiff(img,direction)% MIPCENTRALDIFF Finite difference calculations %% DIMG = MIPCENTRALDIFF(IMG,DIRECTION)%% Calculates the central-difference for a given direction% IMG : input image% DIRECTION : 'dx' or 'dy'% DIMG : resultant image%% See also MIPFORWARDDIFF MIPBACKWARDDIFF MIPSECONDDERIV% MIPSECONDPARTIALDERIV

% Omer Demirkaya, Musa Asyali, Prasana Shaoo, ... 9/1/06% Medical Image Processing Toolbox

img = padarray(img,[1 1],'symmetric','both');[row,col] = size(img);dimg = zeros(row,col);switch (direction) case 'dx', dimg(:,2:col-1) = (img(:,3:col)-img(:,1:col-2))/2; case 'dy', dimg(2:row-1,:) = (img(3:row,:)-img(1:row-2,:))/2; otherwise, disp('Direction is unknown');enddimg = dimg(2:end-1,2:end-1);

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/mipcircconv.mfunction y = mipcircconv(x,h)m = (length(h)-1)/2;xnew = padarray(x,[0 m],'circular','both');y = conv(xnew,h);y = y(2*m+1:end-2*m);

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/mipcircularity.mfunction c = mipcircularity(p)% MIPCIRCULARITY Computes perimeter length%% C = MIPCIRCULARITY(P)%% P is the ordered boundary pixels% % This function calculates circularity of a region% %% See also

% Omer Demirkaya, Musa Asyali, Prasana Shaoo, ... 9/1/06% Medical Image Processing Toolbox

xmean = mean(p(:,1));ymean = mean(p(:,2));npoints = size(p,1)for i=1:npoints d(i) = pdist([p(i,1) p(i,2) ;xmean ymean]);endmur = sum(d)/npoints;sgmr = 0;for i=1:npoints sgmr = sgmr + (d(i) - mur)^2;endsgmr = sgmr/npoints;c = mur/sqrt(sgmr);

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/mipcmean.mfunction cm = mipcmean(h, I1, I2) % MIPCMEAN Computes the class mean%% CM = MIPCMEAN(X,I1,I2)%% This function will compute the class mean, whose intensity range is% [I1, I2], from the histogram. The default range is [1, length(h)]%% See also MIPCVAR

% Omer Demirkaya, Musa Asyali, Prasana Shaoo, ... 9/1/06% Medical Image Processing Toolbox

if nargin == 1 n1 = 1; n2 = length(h);end

p = 0;sm = 0;for i = I1:I2sm = sm + i*h(i);p = p + h(i);end;if p == 0cm = 0;elsecm = sm/p;end;

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/mipconstants.mfunction fc = mipconstants(name,unit)% MIPCONSTANTS Fundamental constants in Physics% From the refence Intermediate Physics for Medicine and Biology% Hobbie, Russell K., Roth, Bradley J., 1997, Springer-Verlag, New York, 3rd% Edition]% case 'plank'% if unit == 'ev'% fc = 4.136e-15; % eV (electron volt)% elseif 'joule'% fc = 6.626074e-34; % Js% end% case 'light speed'% fc = 2.997925e8; % m/s% case 'graviation'% fc = 6.672e-11 % N-m^2/kg^2% case 'electron mass'% fc = 9.1019390e-31 % Kg% case 'electron energy'% fc = 8.187114e-14 % Joule (J)% case 'Avagadro'% fc = 6.022137e23 % 1/mol% case 'Boltzman'% fc = 1.380658e-23 % J/Kelvin% case 'Electron charge'% fc = 1.602177e-19 % Coulomb (C)% case 'Proton mass'% fc = 1.672623e-27 % Kg

%% FC = MIPCONSTANTS(NAME,UNIT)%% This function provides some of the fundamental constants in Physics %% See also

% Omer Demirkaya, Musa Asyali, Prasana Shaoo, ... 9/1/06% Medical Image Processing Toolbox

switch name case 'plank' if unit == 'ev' fc = 4.136e-15; % eV (electron volt) elseif 'joule' fc = 6.626074e-34; % Js end case 'light speed' fc = 2.997925e8; % m/s case 'graviation' fc = 6.672e-11 % N-m^2/kg^2 case 'electron mass' fc = 9.1019390e-31 % Kg case 'electron energy' fc = 8.187114e-14 % Joule (J) case 'Avagadro' fc = 6.022137e23 % 1/mol case 'Boltzman' fc = 1.380658e-23 % J/Kelvin case 'Electron charge' fc = 1.602177e-19 % Coulomb (C) case 'Proton mass' fc = 1.672623e-27 % Kgend

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/mipcorrcoef3d.mfunction ccf= mipcorrcoef3d(img,h)% MIPCORRCOEF3D Correlation coefficient in 3D%% CCF = MIPCORRCOEF3D(IMG,H)%% This function computes the correlation coefficient in 3D% given the input image IMG and the kernel h%% See also

% Omer Demirkaya, Musa Asyali, Prasana Shaoo, ... 9/1/06% Medical Image Processing Toolbox

[hr,hc,hz] = size(h);ksize = hr*hc*hz;h1 = ones(hr,hc,hz);th = h(:);th = th-mean(th);hh = sum(sum(th.*th));avgimg = imfilter(img,h1/ksize);imgsq = img.*img;imgsq = imfilter(imgsq,h1);imgsq = imgsq-ksize*avgimg;cor = imfilter(img,h);cor = cor - ksize*avgimg*mean(th);ccf = cor./sqrt(imgsq*hh);

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/mipcorrimage.mfunction [nImg,uImg] = mipcorrimage (ImSize,rho,sigma,muImg)% MIPCORRIMAGE Image with correlated pixels%% [NIMG, UIMG] = MIPCORRIMAGE(IMSIZE,RHO,SIGMA,MUIMG)%% This function generates images with spatially correlated pixels.% It regards an image as a discerete random field where each pixel is a% random variable. The pixels can be correlated or completely % independent,white noise field.% Using UIMG one can generate images with such as Beta, gamma, Weibull, % Poisson distribution by simply using inverse pdf function; for example % PIMG = poissinv(UIMG)% Inputs:% IMSIZE:[row col]% RHO :A number between 0 and 1.0 ( 0 no correlation and 1 maximum correlation% The covariance function is defined as covmatrix= sigma*rho.^(d) where d % is the euclidean distance between pixels% SIGMA : sigma of the normal distribution% MUIMG : This is the mean image specifying the mean value for each pixel% Output: % NIMG,UIMG: Output images% Example : [nImg,uImg] = mipcorrimage([32, 32],0.95,5,zeros(32,32));%% See also MIPDISKIMAGE MIPSPHEREIMAGE MIPSIGMOIDIMAGE

% Omer Demirkaya, Musa Asyali, Prasana Shaoo, ... 9/1/06% Medical Image Processing Toolbox

if prod(size(muImg)) ~= prod(ImSize) printf(1,'Mean image (muImg) has to have the same dimensions'); return;end;[r,c] = find(ones(ImSize));d = squareform(pdist([r c],'euclidean'));muvec = muImg(:);covmat = sigma*rho.^(d/2);nImg = reshape(mvnrnd(muvec,covmat,1),ImSize);uImg = normcdf(nImg);

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/mipcurvature.mfunction cvt = mipcurvature (v,sigma)% MIPCURVATURE1D Curvature Function%% CVT = MIPCURVATURE(V,SIGMA)%-----------------------------------------------------------------------% This function computes the curvature of a boundary based on % the formula % c = ( x'*y" - y'*x")/(x'^2 + y'^2)^(3/2) % % where y' and y" are 1st and 2nd derivative of y(t) and % similarly x' and x" are 1st and 2nd derivatives of x(t). %-----------------------------------------------------------------------%% See also MIPCURVEPARAM MIPDOG MIPSDOG MIPCIRCCONV

% Omer Demirkaya, Musa Asyali, Prasana Shaoo, ... 9/1/06% Medical Image Processing Toolbox

x = v(:,1)';y = v(:,2)';epsilon = 0.01;DOG = mipdog(sigma);SDOG = mipsdog(sigma);DOG = DOG./sum(abs(DOG));SDOG = SDOG./sum(abs(SDOG));dx = mipcircconv(x,DOG);dy = mipcircconv(y,DOG);dxx = mipcircconv(x,SDOG);dyy = mipcircconv(y,SDOG);grdsq = dx.*dx + dy.*dy;grdsq(grdsq == 0) = epsilon;cvt = (dx.*dyy - dy.*dxx)./(grdsq).^1.5;

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/mipcvar.mfunction cv = mipcvar(h,mu,I1,I2)% MIPCVAR Computes class variance%% CV = MIPCVAR(X,MU,I1,I2)%% This function will compute the class variance, whose mean is MU and % intensity range is [I1, I2], from the histogram H. % The default range is [1, length(H)]%% See also MIPCMEAN

% Omer Demirkaya, Musa Asyali, Prasana Shaoo, ... 9/1/06% Medical Image Processing Toolbox

if nargin == 1 n1 = 1; n2 = length(h);endp = 0;sm = 0;for i = I1:I2temp = (i-mu);sm = sm + h(i)*temp*temp;p = p+h(i);end;if p == 0cv = 0;elsecv = sm/p;end;

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/mipdisclaimer.m% To display the Disclaimer in MATLAB environment% execute the script below from the command line:Disclaimer = {'The MATLAB algorithms, scripts and image','data in this book and on its website are provided','"AS IS" without any warrenty of any sort. The authors','and the publisher make no warranties, express or','implied that the algorithms and scripts are error-free','nor guarantee the accuracy,completeness,usefulness,','or adequacy available at or through these algorithms','and scripts.',' ','They should not be relied on for solving a problem','whose incorrect solution may result in damage to a','person. You can use these algorithms in such a manner','at your own risk. The authors and the publisher of','the book disclaim all the liability for consequential','damages resulting from the use of the algorithms and','scripts in this book and on its website.'};msgbox(Disclaimer,'Disclaimer','modal');

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/mipdiskimage.mfunction imDisk = mipdiskimage(imSize,Radius,Center); % MIPDISKIMAGE DISK IMAGE%% IMDISK = MIPDISKIMAGE(IMSIZE,RADIUS,CENTER)%% This function generates a disk, which was defined by % RADIUS and CENTER, image IMDISK%% See also

% Omer Demirkaya, Musa Asyali, Prasana Shaoo, ... 9/1/06% Medical Image Processing Toolbox [x, y] = meshgrid(1:imSize(1), 1:imSize(2));imCircle = sqrt((x-Center(1)).^2 + (y-Center(2)).^2);imDisk = double(imCircle= th(1)) = 2;end

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/miphexagon.mfunction im = miphexagon(I1,I2,imSize); % MIPHEXAGON Syntehtic image creation%% IMDISK = MIPHEXAGON(I1,I2,IMSIZE)%% I1 and I2 are the background and hexagon levels% imSize: M%% This function generates a hexagon % %% See also

% Omer Demirkaya, Musa Asyali, Prasana Shaoo, ... 9/1/06% Medical Image Processing Toolbox tmp = zeros(imSize);r =[14 26 38 50 50 38 26 14]/(64/imSize);c =[26 14 14 26 38 50 50 38]/(64/imSize); hx = double(roipoly(tmp,c,r));im = (hx+I1).*(hx ==0)+(hx+I2-1).*(hx~=0);

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/miphisto2d.mfunction H = miphisto2d(Img,D)% MIPHISTO2D % Calculates the co-occurence matrix at different degrees(D)%% H = MIPHISTO2D(IMG,D)% % IMG is the input iamge. The output is the two-dimensional histogram H.% % % See also MIPIMHIST

% Omer Demirkaya, Musa Asyali, Prasana Shaoo, ... 9/1/06 % The Medical Image Processing Toolbox

maxI = max(Img(:));minI = min(Img(:));levels = maxI+1;H = zeros(levels,levels);[r c] = size(Img);Img = padarray(Img,[1 1],'replicate','both');% 0 degreesswitch D case 0 for i=2:r for j=2:c m=Img(i,j)+1; n=Img(i,j-1)+1; H(m,n)=H(m,n)+1; n=Img(i,j+1)+1; H(m,n)=H(m,n)+1; end end case 90 % 90 degrees for i=2:r for j=2:c m=Img(i,j)+1; n=Img(i-1,j)+1; H(m,n)=H(m,n)+1; n=Img(i+1,j)+1; H(m,n)=H(m,n)+1; end end case 45 % 45 degrees for i=2:r for j=2:c m=Img(i,j)+1; n=Img(i-1,j+1)+1; H(m,n)=H(m,n)+1; n=Img(i+1,j-1)+1; H(m,n)=H(m,n)+1; end end case 135 % 135 degrees for i=2:r for j=2:c m=Img(i,j)+1; n=Img(i-1,j-1)+1; H(m,n)=H(m,n)+1; n=Img(i+1,j+1)+1; H(m,n)=H(m,n)+1; end end otherwise disp('unknown degree');end

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/mipicm2d2r.mfunction simg = mipicm2d2r(gimg,simg,beta,numOfIteration);% MIPICM2D2R MRF based segmentation%% SIMG = MIPICM2D2R(IMG,SIMG,BETA,NOOFITERATION)%% img : input image% simg : initial segmentation% beta : Beta% noOfIteration : number of iteration%% simg : output image%% See also MIPICM2DMR MIPMETROPOLIS2D2R MIPMETROPOLIS2DMR% MIPGIBBS2D2R MIPGIBBS2DMR%% Omer Demirkaya, Musa Asyali, Prasana Shaoo, ... 9/1/06% Medical Image Processing Toolbox

% Replicate the images edgesgimg = padarray(gimg,[1 1],'replicate','both');simg = padarray(simg,[1 1],'replicate','both');%initialize the variables[row,col] = size(gimg); k = 1;while k 0)/b2) + (((im1 < mx1) - mn1 > 0)/b1)end;h = h+1; % to handle the intensity level zero h(1) = p(0), probability of zero;h1d = hist(double(h(:)),1:m1*m2); %Get the 1D histogram% reform the histogram to produce 2D histogramh2d = reshape(h1d,m1,m2);% h2d = h2d';% h2d = h2d/sum(sum(h2d));

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/mipkittler.mfunction [th,bcvf] = mipkurita(x,nbins) % MIPBCV Threshold computation based on the joint density function%% [TH,CF] = MIPKURITA(X,NBINS)%% This function will compute the threshold based on cumulative dis % image given in X. NBINS represents the number of bins. The default% value for NBINS is 64. It returns threshold TH, the maximum of the% criterion function CMAX and the criterion function CF.%% See also MIPBCV MIPBCV_ITERATIVE MIPKITILLING

% Omer Demirkaya, Musa Asyali, Prasana Shaoo, ... 9/1/06% Medical Image Processing Toolbox

warning off all

% compute histogram, pdf[h,cbin] = mipimhist(x,nbins); % find the indices for max&min gray levels max_indx = max(find(h));min_indx = min(find(h));% initilize variablestotalMean = mipcmean(h,min_indx,max_indx);totalvar = mipcvar(h,totalMean,min_indx,max_indx);prevProb1 = 0;mean1 = 0;bcvf = zeros(1,nbins);for i = min_indx:max_indx prob1 = prevProb1 + h(i); prob2 = 1-prob1; mean1 = (prevProb1*mean1 + h(i)*i)/prob1; mean2 = mipcmean(h,i+1,max_indx); t1 = mean1-mean2; bcvf(i) = log(totalvar-prob1*prob2*t1*t1)-prob1*log(prob1)+prob2*log(prob2); prevProb1 = prob1;end;bcvf = bcvf/totalvar;bcvf(isnan(bcvf)) = 0;bcvf(isinf(bcvf)) = 0;[tm,threshold] = min(bcvf(1:end-1));th = cbin(threshold);

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/mipkmeansSegmentation.mfunction [simg,thresholds] = mipkmeansSegmentation(img,nRegions)% MIPKMEANSSEGMENTATION Image segmentation by kmeans% clustering%% [SIMG,THRESHOLDS] = MIPKMEANSSEGMENTATION(IMG,NREGIONS)%% This function will segment the image using kmeans% clustering%% See also MIPFCMSEGMENTATION

% Omer Demirkaya, Musa Asyali, Prasana Shaoo, ... 23/11/08% Medical Image Processing Toolbox

H = single(img(:));[C_IDX C_CENTER] = kmeans(H,nRegions,'distance',... 'sqEuclidean','Replicates', nRegions+1);NID = (1:nRegions)';CIDX = sortrows([C_CENTER,NID],1);for i=1:nRegions-1; thresholds(i) = max(H(C_IDX==CIDX(i,2)));end[r,c] = size(img);simg = reshape(C_IDX,r,c);

simg = mipgray2multilevel(img,thresholds);

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/mipkurita.mfunction [th,cf,cbin] = mipkurita(x,nbins) % MIPKURITA Threshold computation based on the joint density function%% [TH,CF] = MIPKURITA(X,NBINS)%% This function will compute the threshold based on cumulative dis % image given in X. NBINS represents the number of bins. The default% value for NBINS is 64. It returns threshold TH, the criterion function % bin centers.%% See also MIPBCV MIPBCV_ITERATIVE MIPMINERROR

% Omer Demirkaya, Musa Asyali, Prasana Shaoo, ... 9/1/06% Medical Image Processing Toolbox

warning off all% compute histogram, pdf[h,cbin] = mipimhist(x,nbins); % find the indices for max&min gray levels max_indx = max(find(h));min_indx = min(find(h));% initilize variablestotalMean = mipcmean(h,min_indx,max_indx);totalvar = mipcvar(h,totalMean,min_indx,max_indx);prevProb1 = 0;mean1 = 0;cf = zeros(1,nbins);for i = min_indx:max_indx prob1 = prevProb1 + h(i); prob2 = 1-prob1; mean1 = (prevProb1*mean1 + h(i)*i)/prob1; mean2 = mipcmean(h,i+1,max_indx); t1 = mean1-mean2; cf(i) = log(totalvar-prob1*prob2*t1*t1)-prob1*log(prob1)+prob2*log(prob2); prevProb1 = prob1;end;cf = cf/totalvar;[tm,thindx] = min(cf(1:end-1));th = cbin(thindx);

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/miplinearoned.mfunction diffux = mipadfoned(x,n,k,Lambda) % MIPADFONED 1-D Ansitropic diffusion: Perona-Malik Scheme%% DIFFUX = MIPADFONED(X,N,K,LAMDA)%% X: Original signal, N: number of iterations% K: Noise threshold, Lamda: stability constant%% See also

% Omer Demirkaya, Musa Asyali, Prasana Shaoo, ... 9/1/06% Medical Image Processing Toolbox

% zero paddingdiffux = padarray(x,[0 1],'symmetric','both');deltaE = zeros(size(diffux));deltaW = diffux;for i = 1:n % Derivatives in East and West directions deltaE(2:end-1) = diffux(3:end) - diffux(2:end-1); deltaW(2:end) = diffux(1:end-1) - diffux(2:end); % Diffusivity cE = exp(-(deltaE/k).^2); cW = exp(-(deltaW/k).^2); % Fluxes fluxE = cE.*deltaE; fluxW = cW.*deltaW; % Update the diffusion process diffux = diffux + Lambda*(fluxE + fluxW); %------------------------------------------ % For linear diffusion process % Second derivative using Laplacian function % Ixx=2*del2(diffux); % Update linear diffusion process % diffux = diffux + Lambda*Ixx; %------------------------------------------end% Unpadding signaldiffux = diffux(2:end-1);

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/miplinoned.mfunction diffux = miplinoned(x,n,Lambda) % MIPLINONED 1-D Linear diffusion%% DIFFUX = MIPLINONED(X,N,LAMBDA)%% X: Original signal, N: number of iterations% Lamda: stability factor%% See also MIPADFONED

% Omer Demirkaya, Musa Asyali, Prasana Shaoo, ... 9/1/06% Medical Image Processing Toolbox

% zero paddingdiffux = padarray(x,[0 3],'symmetric','both');deltaE = zeros(size(diffux));deltaW = diffux;for i = 1:n % For linear diffusion process % Second derivative using Laplacian function Ixx = 2*del2(diffux); % Update linear diffusion process diffux = diffux + Lambda*Ixx;end% Unpadding signaldiffux = diffux(4:end-3);

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/mipmapCTwindow.mfunction oimg = mipmapCTwindow(img,wl,ww)% MIPMAPCTWINDOW%% DIMG = MIPMAPCTWINDOW(IMG,WL,WW)% This function adjusts the CT intensity window% Inputs: % IMG: CT image.% WL: center of the window% WW: window width% Output:% OIMG: output image%% See also % % Omer Demirkaya ... 9/1/06% Medical Image Processing Toolbox

% Calculate the CT number limitsL = wl - ww/2;U = wl + ww/2;img = double(img);% Assign the display limits to the intensities % outside the display range.img(img < L) = 0;img(img > U) = 255;minL = -min(img(:));img = img + minL;mxL = max(img(:));% Calculate the slopeslope = 255/mxL;% Carry out the mapping % and convert to 8-bit unsigned integeroimg = uint8(slope*img);

Image_Processing_with_MATLAB_Applications_in_Medicine_and_Biology Sourse/Image Processing with MATLAB Applications in Medicine and Biology/m-files/mipmetropolis2d2r.mfunction simg = mipmetropolis2d2r(gimg,simg,beta,numOfIteration)% MIPMETROPOLIS2D2R MRF based segmentation%% SIMG = MIPMETROPOLIS2D2R(GIMG,SIMG,BETA,NOOFITERATION)%% gimg : input image% simg : initial segmentation% nClass : number of classes% beta : Beta% noOfIteration : number of iteration

%% simg : output image%% See also MIPICM2DMR MIPICM2D2R MIPMETROPOLIS2DMR% MIPGIBBS2D2R MIPGIBBS2DMR%% Omer Demirkaya, Musa Asyali, Prasana Shaoo, ... 9/1/06% Medical Image Processing Toolbox

% Replicate the images edgesgimg = padarray(gimg,[1 1],'replicate','both');simg = padarray(simg,[1 1],'replicate','both');[row, col] = size(gimg);% Initilize the parametersT = 4; C = 0.97; k = 0;% Caculate region statistics[mus, sigs] = mipregionstats(gimg(2:end-1,2:end-1),... simg(2:end-1,2:end-1),2);vars = (sigs + 0.01).^2;while (k =0 & model_data