plateform
stringclasses
1 value
repo_name
stringlengths
13
113
name
stringlengths
3
74
ext
stringclasses
1 value
path
stringlengths
12
229
size
int64
23
843k
source_encoding
stringclasses
9 values
md5
stringlengths
32
32
text
stringlengths
23
843k
github
jacksky64/imageProcessing-master
lse_bfe.m
.m
imageProcessing-master/segmentation/levelset_segmentation_biasCorrection_v1/levelset_segmentation_biasCorrection_v1/lse_bfe.m
3,246
utf_8
f5fa95fc0201c04b6a285f465145b25a
function [u, b, C]= lse_bfe(u0,Img, b, Ksigma,KONE, nu,timestep,mu,epsilon, iter_lse) % This code implements the level set evolution (LSE) and bias field estimation % proposed in the following paper: % C. Li, R. Huang, Z. Ding, C. Gatenby, D. N. Metaxas, and J. C. Gore, % "A Level Set Method for Image Segmentation in the Presence of Intensity % Inhomogeneities with Application to MRI", IEEE Trans. Image Processing, 2011 % % Note: % This code implements the two-phase formulation of the model in the above paper. % The two-phase formulation uses the signs of a level set function to represent % two disjoint regions, and therefore can be used to segment an image into two regions, % which are represented by (u>0) and (u<0), where u is the level set function. % % All rights researved by Chunming Li, who formulated the model, designed and % implemented the algorithm in the above paper. % % E-mail: [email protected] % URL: http://www.engr.uconn.edu/~cmli/ % Copyright (c) by Chunming Li % Author: Chunming Li u=u0; KB1 = conv2(b,Ksigma,'same'); KB2 = conv2(b.^2,Ksigma,'same'); C =updateC(Img, u, KB1, KB2, epsilon); KONE_Img = Img.^2.*KONE; u = updateLSF(Img,u, C, KONE_Img, KB1, KB2, mu, nu, timestep, epsilon, iter_lse); Hu=Heaviside(u,epsilon); M(:,:,1)=Hu; M(:,:,2)=1-Hu; b =updateB(Img, C, M, Ksigma); % update level set function function u = updateLSF(Img, u0, C, KONE_Img, KB1, KB2, mu, nu, timestep, epsilon, iter_lse) u=u0; Hu=Heaviside(u,epsilon); M(:,:,1)=Hu; M(:,:,2)=1-Hu; N_class=size(M,3); e=zeros(size(M)); u=u0; for kk=1:N_class e(:,:,kk) = KONE_Img - 2*Img.*C(kk).*KB1 + C(kk)^2*KB2; end for kk=1:iter_lse u=NeumannBoundCond(u); K=curvature_central(u); % div() DiracU=Dirac(u,epsilon); ImageTerm=-DiracU.*(e(:,:,1)-e(:,:,2)); penalizeTerm=mu*(4*del2(u)-K); lengthTerm=nu.*DiracU.*K; u=u+timestep*(lengthTerm+penalizeTerm+ImageTerm); end % update b function b =updateB(Img, C, M, Ksigma) PC1=zeros(size(Img)); PC2=PC1; N_class=size(M,3); for kk=1:N_class PC1=PC1+C(kk)*M(:,:,kk); PC2=PC2+C(kk)^2*M(:,:,kk); end KNm1 = conv2(PC1.*Img,Ksigma,'same'); KDn1 = conv2(PC2,Ksigma,'same'); b = KNm1./KDn1; % Update C function C_new =updateC(Img, u, Kb1, Kb2, epsilon) Hu=Heaviside(u,epsilon); M(:,:,1)=Hu; M(:,:,2)=1-Hu; N_class=size(M,3); for kk=1:N_class Nm2 = Kb1.*Img.*M(:,:,kk); Dn2 = Kb2.*M(:,:,kk); C_new(kk) = sum(Nm2(:))/sum(Dn2(:)); end % Make a function satisfy Neumann boundary condition function g = NeumannBoundCond(f) [nrow,ncol] = size(f); g = f; g([1 nrow],[1 ncol]) = g([3 nrow-2],[3 ncol-2]); g([1 nrow],2:end-1) = g([3 nrow-2],2:end-1); g(2:end-1,[1 ncol]) = g(2:end-1,[3 ncol-2]); function k = curvature_central(u) % compute curvature for u with central difference scheme [ux,uy] = gradient(u); normDu = sqrt(ux.^2+uy.^2+1e-10); Nx = ux./normDu; Ny = uy./normDu; [nxx,junk] = gradient(Nx); [junk,nyy] = gradient(Ny); k = nxx+nyy; function h = Heaviside(x,epsilon) h=0.5*(1+(2/pi)*atan(x./epsilon)); function f = Dirac(x, epsilon) f=(epsilon/pi)./(epsilon^2.+x.^2);
github
jacksky64/imageProcessing-master
drlse_edge.m
.m
imageProcessing-master/segmentation/DRLSE_v0/drlse_edge.m
3,599
utf_8
ee52d75877b9ca4db832b038f27fd28e
function phi = drlse_edge(phi_0, g, lambda,mu, alfa, epsilon, timestep, iter, potentialFunction) % This Matlab code implements an edge-based active contour model as an % application of the Distance Regularized Level Set Evolution (DRLSE) formulation in Li et al's paper: % % C. Li, C. Xu, C. Gui, M. D. Fox, "Distance Regularized Level Set Evolution and Its Application to Image Segmentation", % IEEE Trans. Image Processing, vol. 19 (12), pp.3243-3254, 2010. % % Input: % phi_0: level set function to be updated by level set evolution % g: edge indicator function % mu: weight of distance regularization term % timestep: time step % lambda: weight of the weighted length term % alfa: weight of the weighted area term % epsilon: width of Dirac Delta function % iter: number of iterations % potentialFunction: choice of potential function in distance regularization term. % As mentioned in the above paper, two choices are provided: potentialFunction='single-well' or % potentialFunction='double-well', which correspond to the potential functions p1 (single-well) % and p2 (double-well), respectively.% % Output: % phi: updated level set function after level set evolution % % Author: Chunming Li, all rights reserved % E-mail: [email protected] % [email protected] % URL: http://www.imagecomputing.org/~cmli/ phi=phi_0; [vx, vy]=gradient(g); for k=1:iter phi=NeumannBoundCond(phi); [phi_x,phi_y]=gradient(phi); s=sqrt(phi_x.^2 + phi_y.^2); smallNumber=1e-10; Nx=phi_x./(s+smallNumber); % add a small positive number to avoid division by zero Ny=phi_y./(s+smallNumber); curvature=div(Nx,Ny); if strcmp(potentialFunction,'single-well') distRegTerm = 4*del2(phi)-curvature; % compute distance regularization term in equation (13) with the single-well potential p1. elseif strcmp(potentialFunction,'double-well'); distRegTerm=distReg_p2(phi); % compute the distance regularization term in eqaution (13) with the double-well potential p2. else disp('Error: Wrong choice of potential function. Please input the string "single-well" or "double-well" in the drlse_edge function.'); end diracPhi=Dirac(phi,epsilon); areaTerm=diracPhi.*g; % balloon/pressure force edgeTerm=diracPhi.*(vx.*Nx+vy.*Ny) + diracPhi.*g.*curvature; phi=phi + timestep*(mu*distRegTerm + lambda*edgeTerm + alfa*areaTerm); end function f = distReg_p2(phi) % compute the distance regularization term with the double-well potential p2 in eqaution (16) [phi_x,phi_y]=gradient(phi); s=sqrt(phi_x.^2 + phi_y.^2); a=(s>=0) & (s<=1); b=(s>1); ps=a.*sin(2*pi*s)/(2*pi)+b.*(s-1); % compute first order derivative of the double-well potential p2 in eqaution (16) dps=((ps~=0).*ps+(ps==0))./((s~=0).*s+(s==0)); % compute d_p(s)=p'(s)/s in equation (10). As s-->0, we have d_p(s)-->1 according to equation (18) f = div(dps.*phi_x - phi_x, dps.*phi_y - phi_y) + 4*del2(phi); function f = div(nx,ny) [nxx,junk]=gradient(nx); [junk,nyy]=gradient(ny); f=nxx+nyy; function f = Dirac(x, sigma) f=(1/2/sigma)*(1+cos(pi*x/sigma)); b = (x<=sigma) & (x>=-sigma); f = f.*b; function g = NeumannBoundCond(f) % Make a function satisfy Neumann boundary condition [nrow,ncol] = size(f); g = f; g([1 nrow],[1 ncol]) = g([3 nrow-2],[3 ncol-2]); g([1 nrow],2:end-1) = g([3 nrow-2],2:end-1); g(2:end-1,[1 ncol]) = g(2:end-1,[3 ncol-2]);
github
jacksky64/imageProcessing-master
SegmentRefine.m
.m
imageProcessing-master/segmentation/SegTool/SegmentRefine.m
7,789
utf_8
efd3606b9a14570a8983aa2dbfc38097
function [] = SegmentRefine(ImName) % SEGMENTREFINE - Main graph cuts segmentation function % SEGMENTREFINE(IMNAME) - ImName - Image to segment % Authors - Mohit Gupta, Krishnan Ramnath % Affiliation - Robotics Institute, CMU, Pittsburgh % 2006-05-15 % Global Variables global sopt ih_img fgpixels bgpixels fgflag segImageHandle; % GUI specific flag fgflag = 2; % Data from GC(AutoCut) or prev GC+LZ(AutoCutRefine) load('iter_data'); % Stop unnecessary warnings warning('off','all'); % Read input image I = imread(ImName); I1 = I(:,:,1); I2 = I(:,:,2); I3 = I(:,:,3); %%%% Final Segmented Image SegImage = zeros(size(I)); % LZ % Get Foreground and Background Pixels for Smart Refine if(~isempty(fgpixels)) FY = fgpixels(:,1); FX = fgpixels(:,2); end if(~isempty(bgpixels)) BY = bgpixels(:,1); BX = bgpixels(:,2); end % GC - fp bounding rectangle load rectpts; %% Width of Strip StripWidth = sopt.StripWidth_AC_ACR; [fxi,fyi] = meshgrid(min(fp(:,1)):max(fp(:,1)),min(fp(:,2)):max(fp(:,2))); InsideFindices = sub2ind(size(I1),fyi, fxi); InsideFindices = InsideFindices(:); %Form the Outside rectangular bounding box -- add StripWidth on all 4 sides [fxo,fyo] = meshgrid( max((min(fp(:,1)) - StripWidth),1) : min((max(fp(:,1)) + StripWidth), size(I1,2)) , max((min(fp(:,2)) - StripWidth),1) : min((max(fp(:,2)) + StripWidth), size(I1,1)) ); OutsideFindices = sub2ind(size(I1),fyo, fxo); OutsideFindices = OutsideFindices(:); Bindices = setdiff(OutsideFindices, InsideFindices); Allindices = [1:size(I1,1)*size(I1,2)]'; Findices = InsideFindices; numLabels = max(L(:)); PI = regionprops(L,'PixelIdxList'); %%%% BLabels remain fixed -- no change %%%% ULabels -- Uncertain labels -- on which optimization done... ULabels = FLabels; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% Finding Foreground and Background Labels from pixel seeds%% try if(~isempty(fgpixels)) FindicesStr = sub2ind(size(I1),FX,FY); FLabelsStr = L(int32(FindicesStr)); FLabelsStr = union(FLabelsStr,[]); %% Set-ifying the set of labels (Sorting?) if(FLabelsStr(1)==0) %% Removing Boundary Labels FLabelsStr = FLabelsStr(2:end); end % Get Common label indices to index into fdist and bdist [FLabelsCom FIndCom] = intersect(ULabels, FLabelsStr); end if(~isempty(bgpixels)) BindicesStr = sub2ind(size(I1),BX,BY); BLabelsStr = L(int32(BindicesStr)); BLabelsStr = union(BLabelsStr,[]); %% Set-ifying the set of labels if(BLabelsStr(1)==0) %% Removing Boundary Labels BLabelsStr = BLabelsStr(2:end); end [BLabelsCom BIndCom] = intersect(ULabels, BLabelsStr); end catch beep disp('Error: Seeds are outside Image limits ...Please restart'); return; end FColors = MeanColors(FLabels,:); BColors = MeanColors(BLabels,:); %%%%%%%%%%%% GMM's Initialized %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%% The iterative Loop %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% lambda = sopt.lambda_ACR; numIter = sopt.numIter_ACR; for i = 1:numIter disp(['Iteration - ', num2str(i)]); % Foreground and Background edge weights [FDist, FInd] = ClustDistMembership(MeanColors(ULabels,:), FCClusters, FCovs, FWeights); [BDist, BInd] = ClustDistMembership(MeanColors(ULabels,:), BCClusters, BCovs, BWeights); % Hard Seeds if(~isempty(fgpixels)) FDist(FIndCom) = 0; BDist(FIndCom) = 1000; end if(~isempty(bgpixels)) FDist(BIndCom) = 1000; BDist(BIndCom) = 0; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Segments labeled from 0 now -- -1 is for boundary pixels L = L-1; FLabels = FLabels-1; BLabels = BLabels-1; ULabels = ULabels-1; %%%%%%%%%%%%% The Mex Function for GraphCutSegment %%%%%%%%%%%% %%% SegImage is the segmented image, %%% LLabels is the binary label %%% for each watershed label [SegImage LLabels] = GraphCutSegment(L, MeanColors, ULabels, BLabels, FDist, BDist, lambda); %%% SegImage is the segmented image, %%% LLabels is the binary label for each watershed label %% Again Labeled from 1... L = L+1; FLabels = FLabels+1; BLabels = BLabels+1; ULabels = ULabels+1; if(i < numIter) %%%%%% Do NOT do this if final iteration -- just display the segmented image %%%%%% Making new FLabels and BLabels based on the segmentation %%%%%% newFLabels = ULabels(find(LLabels==1.0)); newBLabels = ULabels(find(LLabels==0.0)); %%%%%% Whether new background labels will contain the old ones? % newBLabels = union(newBLabels,BLabels); FColors = MeanColors(newFLabels,:); BColors = MeanColors(newBLabels,:); %%%%%%%% Calculating FG and BG distances based on new segmentation %%%%%%%% %%%%%%%%%%%%%%%%%% [newFDists newFInd] = ClustDistMembership(FColors, FCClusters, FCovs, FWeights); [newBDists newBInd] = ClustDistMembership(BColors, BCClusters, BCovs, BWeights); for k=1:NumFClusters relColors = FColors(find(newFInd==k),:); %% Colors belonging to cluster k FCClusters(:,k) = mean(relColors,1)'; FCovs(:,:,k) = cov(relColors); FWeights(1,k) = length(find(newFInd==k)) / length(newFInd); end for k=1:NumBClusters relColors = BColors(find(newBInd==k),:); %% Colors belonging to cluster k BCClusters(:,k) = mean(relColors,1)'; BCovs(:,:,k) = cov(relColors); BWeights(1,k) = length(find(newBInd==k)) / length(newBInd); end end end %%%%%%%%%%%%%%%%%%%%% Display the segmented image %%%%%%%%%%%%%%%%%%% edge_img = edge(SegImage,'canny'); % Put image on black background SegImage = repmat(SegImage,[1,1,3]); SegNewImage = uint8(SegImage) .* uint8(I); % Mark a segmentation boundary on original image % Set the image [IInd,JInd] = ind2sub(size(I1),find(edge_img)); boundImage1 = I(:,:,2); boundImage1(find(edge_img)) = 255; boundImage = I; boundImage(:,:,2) = boundImage1; set(ih_img, 'Cdata', uint8(boundImage)); axis('image');axis('ij');axis('off'); drawnow; figure(segImageHandle); imshow(uint8(SegNewImage)); SegMask = SegImage; SegResult = SegNewImage; % Save Segmentation Result save('SegResult', 'SegMask', 'SegResult'); % Required for AutoRefine save('iter_data','L', 'MeanColors', 'FLabels', 'BLabels', 'FCClusters',... 'FCovs', 'FWeights', 'BCClusters', 'BCovs', 'BWeights'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%% Helper Functions declarations %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [FDist, FInd] = ClustDistMembership(MeanColors, FCClusters, FCovs, FWeights) % CLUSTDISTMEMBERSHIP - Calcuates FG and BG Distances % Authors - Mohit Gupta, Krishnan Ramnath % Affiliation - Robotics Institute, CMU, Pittsburgh % 2006-05-15 NumFClusters = size(FCClusters,2); numULabels = size(MeanColors,1); FDist = zeros(numULabels,1); FInd = zeros(numULabels,1); Ftmp = zeros(numULabels, NumFClusters); for k=1:NumFClusters M = FCClusters(:,k); CovM = FCovs(:,:,k); W = FWeights(1,k); V = MeanColors - repmat(M',numULabels,1); Ftmp(:,k) = -log((W / sqrt(det(CovM))) * exp(-( sum( ((V * inv(CovM)) .* V),2) /2))); end [FDist, FInd] = min(Ftmp,[],2);
github
jacksky64/imageProcessing-master
SegmentBoth.m
.m
imageProcessing-master/segmentation/SegTool/SegmentBoth.m
9,046
utf_8
7075544eb046a7ff90fa6c51d76c43da
function [] = SegmentGC(ImName); %%%Main Grab Cuts segmentation function global ih_img fgpixels bgpixels; load segimage; BiImage = SegImage; figure; imagesc(BiImage); SegImage = []; I = imread(ImName); I1 = I(:,:,1); I2 = I(:,:,2); I3 = I(:,:,3); %%%% Final Segmented Image SegImage = zeros(size(I)); Findices = find(BiImage); Bindices = find(BiImage == 0); % Get Foreground and Background Pixels for Smart Refine FY = fgpixels(:,1); FX = fgpixels(:,2); BY = bgpixels(:,1); BX = bgpixels(:,2); % LZ FindicesStr = sub2ind(size(I1),FX,FY); BindicesStr = sub2ind(size(I1),BX,BY); size(FindicesStr) size(BindicesStr) 'indices' Findices = union(Findices,FindicesStr); [WrongB WrIndB] = intersect(Bindices,FindicesStr); size(WrIndB) 'Wrindb' Bindices(WrIndB) = []; Bindices = union(Bindices,BindicesStr); [WrongF WrIndF] = intersect(Findices,BindicesStr); size(WrIndF) 'Wrinf' Findices(WrIndF) = []; L = watershed(I(:,:,1)); %%%% Doing watershed on the red channel -- SEE if you can do it on the color image %%%%%%%%% Finding Mean colors of the regions %%%%%%%%%%%%%%%%%% %%%%% SEE if this can be vectorised %%%%%%%%%%%%%%%%%%%%%%%%%%% numLabels = max(L(:)); PI = regionprops(L,'PixelIdxList'); MeanColors = zeros(numLabels,3); for i=1:numLabels MeanColors(i,1) = mean(I1(PI(i).PixelIdxList)); MeanColors(i,2) = mean(I2(PI(i).PixelIdxList)); MeanColors(i,3) = mean(I3(PI(i).PixelIdxList)); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% Finding Foreground and Background Labels from pixels%% FLabels = L(int32(Findices)); FLabels = union(FLabels,[]); %% Set-ifying the set of labels (Sorting?) if(FLabels(1)==0) %% Removing Boundary Labels FLabels = FLabels(2:end); end BLabels = L(int32(Bindices)); BLabels = union(BLabels,[]); %% Set-ifying the set of labels if(BLabels(1)==0) %% Removing Boundary Labels BLabels = BLabels(2:end); end % Common labels and indices among GC and LZ [FIndCom] = intersect(Findices, FindicesStr); [BIndCom] = intersect(Bindices, BindicesStr); size(FIndCom) size(BIndCom) %%%% BLabels remain fixed -- no change %%%% ULabels -- Uncertain labels -- on which optimization done... ULabels = FLabels; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Finding Initial Estimate of foregound and background color clusters %%%%%%%%%%%% NumFClusters = 5; NumBClusters = 5; FColors = MeanColors(FLabels,:); BColors = MeanColors(BLabels,:); %%%%%%%%%%% Initializing the GMM's %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%% Using EM_GM %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % [FWeights,FCClusters,FCovs,FLikelihood] = EM_GM(FColors,NumFClusters); % [BWeights,BCClusters,BCovs,BLikelihood] = EM_GM(BColors,NumBClusters); %%%%%%%%%%% Using Just kmeans %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% [FId FCClusters] = vgg_kmeans(FColors, NumFClusters); Fdim = size(FColors,2); FCClusters = zeros(Fdim, NumFClusters); FWeights = zeros(1,NumFClusters); FCovs = zeros(Fdim, Fdim, NumFClusters); for k=1:NumFClusters relColors = FColors(find(FId==k),:); %% Colors belonging to cluster k FCClusters(:,k) = mean(relColors,1)'; FCovs(:,:,k) = cov(relColors); FWeights(1,k) = length(find(FId==k)) / length(FId); end [BId BCClusters] = vgg_kmeans(BColors, NumBClusters); Bdim = size(BColors,2); BCClusters = zeros(Bdim, NumBClusters); BWeights = zeros(1,NumBClusters); BCovs = zeros(Bdim, Bdim, NumBClusters); for k=1:NumBClusters relColors = BColors(find(BId==k),:); %% Colors belonging to cluster k BCClusters(:,k) = mean(relColors,1)'; BCovs(:,:,k) = cov(relColors); BWeights(1,k) = length(find(BId==k)) / length(BId); end %%%%%%%%%%%% GMM's Initialized %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%% The iterative Loop %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Initialize FDist and BDist with LZ values % FDist = zeros(length(FLabels),1); % BDist = zeros(length(BLabels),1); numIter = 6; for i=1:numIter i [FDist, FInd] = ClustDistMembership(MeanColors(ULabels,:), FCClusters, FCovs, FWeights); [BDist, BInd] = ClustDistMembership(MeanColors(ULabels,:), BCClusters, BCovs, BWeights); % Lets hope somebody doesnt choose the same thing as FG and BG, BG will % prevail FDist(FIndCom) = 0; BDist(FIndCom) = 10000; FDist(BIndCom) = 10000; BDist(BIndCom) = 0; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%% The Mex Function for GraphCutSegment %%%%%%%%%%%% L = L-1; %% Segments labeled from 0 now -- -1 is for boundary pixels FLabels = FLabels-1; BLabels = BLabels-1; ULabels = ULabels-1; [SegImage LLabels] = GraphCutSegment(L, MeanColors, ULabels, BLabels, FDist, BDist); %%% SegImage is the segmented image, %%% LLabels is the binary label for each watershed label L = L+1; %% Again Labeled from 1... FLabels = FLabels+1; BLabels = BLabels+1; ULabels = ULabels+1; %%%%%%%%%% Showing the intermediate segmentation %%%%%%%%%%%%%%%%%%%%% % edge_img = edge(SegImage,'canny'); % % % figure; % imshow(I); % [IInd,JInd] = ind2sub(size(I1),find(edge_img)); % hold on;plot(JInd,IInd,'b.'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if(i<numIter) %%%%%% Do NOT do this if final iteration -- just display the segmented image %%%%%% Making new FLabels and BLabels based on the segmentation %%%%%% newFLabels = ULabels(find(LLabels==1.0)); newBLabels = ULabels(find(LLabels==0.0)); % newBLabels = union(newBLabels,BLabels); %%%%%% Whether new background labels will contain the old ones? FColors = MeanColors(newFLabels,:); BColors = MeanColors(newBLabels,:); %%%%%%%% Making new GMM's based on new segmentation %%%%%%%%%%%%%%%%%% %%%%%%%% Used for defining distances in the next iterative step %%%%%% % [FWeights,FCClusters,FCovs,FLikelihood] = EM_GM(FColors,NumFClusters); % [BWeights,BCClusters,BCovs,BLikelihood] = EM_GM(BColors,NumBClusters); [newFDists newFInd] = ClustDistMembership(FColors, FCClusters, FCovs, FWeights); [newBDists newBInd] = ClustDistMembership(BColors, BCClusters, BCovs, BWeights); for k=1:NumFClusters relColors = FColors(find(newFInd==k),:); %% Colors belonging to cluster k FCClusters(:,k) = mean(relColors,1)'; FCovs(:,:,k) = cov(relColors); FWeights(1,k) = length(find(newFInd==k)) / length(newFInd); end for k=1:NumBClusters relColors = BColors(find(newBInd==k),:); %% Colors belonging to cluster k BCClusters(:,k) = mean(relColors,1)'; BCovs(:,:,k) = cov(relColors); BWeights(1,k) = length(find(newBInd==k)) / length(newBInd); end end end %%%%%%%%%%%%%%%%%%%%% Display the segmented image %%%%%%%%%%%%%%%%%%% %set position % data.ui.ah_img = axes('Position',[0.5 0.2 .603 .604]);%,'drawmode','fast'); % data.ui.ih_img = imagesc; % %set image data % set(data.ui.ih_img, 'Cdata', SegImage); % axis('image');axis('ij');axis('off'); % drawnow; edge_img = edge(SegImage,'canny'); % Put image on black background SegNewImage1 = zeros(size(SegImage)); SegNewImage2 = zeros(size(SegImage)); SegNewImage3 = zeros(size(SegImage)); idx = find(SegImage); length(idx) for(i = 1:length(idx)) SegNewImage1(int32(idx(i))) = I1(int32(idx(i))); SegNewImage2(int32(idx(i))) = I2(int32(idx(i))); SegNewImage3(int32(idx(i))) = I3(int32(idx(i))); end SegNewImage(:,:,1) = SegNewImage1; SegNewImage(:,:,2) = SegNewImage2; SegNewImage(:,:,3) = SegNewImage3; set(ih_img, 'Cdata', uint8(SegNewImage)); axis('image');axis('ij');axis('off'); drawnow; figure; imshow(uint8(SegNewImage)); save segnewimage SegNewImage; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%% Helper Functions declarations %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [FDist, FInd] = ClustDistMembership(MeanColors, FCClusters, FCovs, FWeights) NumFClusters = size(FCClusters,2); numULabels = size(MeanColors,1); FDist = zeros(numULabels,1); FInd = zeros(numULabels,1); Ftmp = zeros(numULabels, NumFClusters); for k=1:NumFClusters M = FCClusters(:,k); CovM = FCovs(:,:,k); W = FWeights(1,k); V = MeanColors - repmat(M',numULabels,1); Ftmp(:,k) = -log((W / sqrt(det(CovM))) * exp(-( sum( ((V * inv(CovM)) .* V),2) /2))); % keyboard end [FDist, FInd] = min(Ftmp,[],2);
github
jacksky64/imageProcessing-master
SmartSelectSeg.m
.m
imageProcessing-master/segmentation/SegTool/SmartSelectSeg.m
2,669
utf_8
b0d3edf879d53194cac94ed20fd13b29
function SmartSelectSeg % SMARTSELECTSEG - This function displays chosen image and creates buttons % for marking seeds and calling Segment function % Authors - Mohit Gupta, Krishnan Ramnath % Affiliation - Robotics Institute, CMU, Pittsburgh % 2006-05-15 % Global Variables % Req by radio button RadioButtonFn global hfig longfilename; % Get handle to current figure; hfig = gcf; % Call built-in file dialog to select image file [filename,pathname] = uigetfile('images/*.*','Select image file'); if ~ischar(filename); return; end %%%%%%%%%%%%%%%%%%%Radio Buttons%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% h = uibuttongroup('visible','off','Position',[0.7 0.7 0.15 0.18]); u0 = uicontrol('Style','Radio','String','SmartRectangle',... 'pos',[10 20 120 30],'parent',h,'HandleVisibility','off'); u1 = uicontrol('Style','Radio','String','SmartRefine',... 'pos',[10 60 120 30],'parent',h,'HandleVisibility','off'); set(h,'SelectionChangeFcn',@RadioButtonFn); set(h,'SelectedObject',[]); set(h,'Visible','on'); %%%%%%%%%%%%%%%%%%%Draw Image%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Load Image file longfilename = strcat(pathname,filename); Im = imread(longfilename); % Get the position of the image data.ui.ah_img = axes('Position',[0.01 0.2 .603 .604]); data.ui.ih_img = image; % Set the image set(data.ui.ih_img, 'Cdata', Im); axis('image');axis('ij');axis('off'); drawnow; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function RadioButtonFn(source, eventdata) % RADIOBUTTONFUNCTION - This function is called whenever there is change in % choice of radio button % Global Variables global hfig longfilename; % Pass string value to seed selection function strg = get(eventdata.NewValue,'String'); %%%%%%%%%%%%%%%%Seed Selection Buttons%%%%%%%%%%%%%%%%%%% % Calls fginput - gets foreground pixels from the user data.ui.push_fg = uicontrol(hfig, 'Style','pushbutton', 'Units', 'Normalized','Position',[.7 .6 .1 .05], ... 'String','Foreground','Callback', ['fginput ',strg]); % Calls bginput - gets background pixels from the user data.ui.push_bg = uicontrol(hfig, 'Style','pushbutton', 'Units', 'Normalized','Position',[.7 .5 .1 .05], ... 'String','Background','Callback', ['bginput ',strg]); % Calls Segment - graph-cuts on the image data.ui.push_bg = uicontrol(hfig, 'Style','pushbutton', 'Units', 'Normalized','Position',[.7 .4 .1 .05], ... 'String','Graph Cuts','Callback', ['Segment ',longfilename]); drawnow;
github
jacksky64/imageProcessing-master
bginput.m
.m
imageProcessing-master/segmentation/SegTool/bginput.m
1,327
utf_8
40555c86d5e0244acebf33c28803bb1f
%-------------------------------------------------------------------------- function bginput(strg) % BGINPUT - This function gets the background pixels from user input % BGINPUT(STRG) - strg - Smart Refine or Smart Rectangle % Authors - Mohit Gupta, Krishnan Ramnath % Affiliation - Robotics Institute, CMU, Pittsburgh % 2006-05-15 % Global variables referenced in this funciton global fgflag fgbc bgbc fgpixels bgpixels; if(strcmp(strg,'SmartRectangle')) % Gui related flag fgflag = 2; % Get two points from the user bp = ginput(2); bp = round(bp); % Form the rectangular bounding box from the two points [bx,by] = meshgrid(min(bp(:,1)):max(bp(:,1)),min(bp(:,2)):max(bp(:,2))); bpixelsx =[]; bpixelsy =[]; for(i = 1:size(bx,2)) bpixelsx = [bpixelsx bx(:,i)']; bpixelsy = [bpixelsy by(:,i)']; end bpixels = [bpixelsx' bpixelsy']; % Concatenate bgpixels = vertcat(bgpixels,bpixels); % Plot the Rectangle hfig = gcf; axis('image');axis('ij');axis('off'); hold on; plot(bgpixels(:,1),bgpixels(:,2),'b.'); else hfig = gcf; hold on; % Gui related flag fgflag = 0; % Call track function on button press set(hfig,'windowbuttondownfcn',{@track}); end
github
jacksky64/imageProcessing-master
SegmentGC.m
.m
imageProcessing-master/segmentation/SegTool/SegmentGC.m
8,578
utf_8
f39aab15bbf3c9ece14572e50f90061e
function [] = SegmentGC(ImName, ih, alg) % SEGMENTGC - Main GrabCut segmentation function % SEGMENTGC(IMNAME, IH, ALG) - ImName - Image to segment % IH - Image Handle % ALG - AutoCut or AutoRefine (0 or 1) % Authors - Mohit Gupta, Krishnan Ramnath % Affiliation - Robotics Institute, CMU, Pittsburgh % 2006-05-15 % Global Variables global sopt segImageHandle; % Read input image I = imread(ImName); I1 = I(:,:,1); I2 = I(:,:,2); I3 = I(:,:,3); % Final Segmented Image SegImage = zeros(size(I)); % Stop unnecessary warnings warning('off','all'); %%%%%%% Marking the Inner Rectangle around the foreground object %%%%%%% Get two points from the user % Set the image set(ih, 'Cdata', I); axis('image');axis('ij');axis('off'); drawnow; fp = ginput(2); fp = round(fp); % Save the points for future use save rectpts fp; % Width of Strip StripWidth = sopt.StripWidth_AC_ACR; % Get inner indices [fxi,fyi] = meshgrid(min(fp(:,1)):max(fp(:,1)),min(fp(:,2)):max(fp(:,2))); InsideFindices = sub2ind(size(I1),fyi, fxi); InsideFindices = InsideFindices(:); % Form the Outside rectangular bounding box -- add StripWidth on all 4 sides [fxo,fyo] = meshgrid( max((min(fp(:,1)) - StripWidth),1) : min((max(fp(:,1)) + StripWidth), size(I1,2)) , max((min(fp(:,2)) - StripWidth),1) : min((max(fp(:,2)) + StripWidth), size(I1,1)) ); OutsideFindices = sub2ind(size(I1),fyo, fxo); OutsideFindices = OutsideFindices(:); Bindices = setdiff(OutsideFindices, InsideFindices); Allindices = [1:size(I1,1)*size(I1,2)]'; Findices = InsideFindices; % Water shed pixels L = watershed(I(:,:,1)); %%%%%%%%% Finding Mean colors of the regions %%%%%%%%%%%%%%%%%% numLabels = max(L(:)); PI = regionprops(L,'PixelIdxList'); MeanColors = zeros(numLabels,3); for i=1:numLabels MeanColors(i,1) = mean(I1(PI(i).PixelIdxList)); MeanColors(i,2) = mean(I2(PI(i).PixelIdxList)); MeanColors(i,3) = mean(I3(PI(i).PixelIdxList)); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%% Finding Foreground and Background Labels from pixels%% FLabels = L(int32(Findices)); FLabels = union(FLabels,[]); %% Set-ifying the set of labels (Sorting) if(FLabels(1)==0) %% Removing Boundary Labels FLabels = FLabels(2:end); end BLabels = L(int32(Bindices)); BLabels = union(BLabels,[]); %% Set-ifying the set of labels if(BLabels(1)==0) %% Removing Boundary Labels BLabels = BLabels(2:end); end %%%% BLabels remain fixed -- no change %%%% ULabels -- Uncertain labels -- on which optimization done... ULabels = FLabels; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% Finding Initial Estimate of foregound and background color clusters %%%%%%%%%%%% NumFClusters = sopt.NumFClusters_AC; NumBClusters = sopt.NumBClusters_AC; FColors = MeanColors(FLabels,:); BColors = MeanColors(BLabels,:); %%%%%%%%%%% Initializing the GMM's %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%% Using Just kmeans %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% [FId FCClusters] = kmeans(FColors, NumFClusters); Fdim = size(FColors,2); FCClusters = zeros(Fdim, NumFClusters); FWeights = zeros(1,NumFClusters); FCovs = zeros(Fdim, Fdim, NumFClusters); for k=1:NumFClusters relColors = FColors(find(FId==k),:); %% Colors belonging to cluster k FCClusters(:,k) = mean(relColors,1)'; FCovs(:,:,k) = cov(relColors); FWeights(1,k) = length(find(FId==k)) / length(FId); end [BId BCClusters] = kmeans(BColors, NumBClusters); Bdim = size(BColors,2); BCClusters = zeros(Bdim, NumBClusters); BWeights = zeros(1,NumBClusters); BCovs = zeros(Bdim, Bdim, NumBClusters); for k=1:NumBClusters relColors = BColors(find(BId==k),:); %% Colors belonging to cluster k BCClusters(:,k) = mean(relColors,1)'; BCovs(:,:,k) = cov(relColors); BWeights(1,k) = length(find(BId==k)) / length(BId); end %%%%%%%%%%%% GMM's Initialized %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%% The iterative Loop %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% lambda = sopt.lambda_AC; numIter = sopt.numIter_AC; for i = 1:numIter disp(['Iteration - ', num2str(i)]); % Foreground and Background edge weights [FDist, FInd] = ClustDistMembership(MeanColors(ULabels,:), FCClusters, FCovs, FWeights); [BDist, BInd] = ClustDistMembership(MeanColors(ULabels,:), BCClusters, BCovs, BWeights); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Segments labeled from 0 now -- -1 is for boundary pixels L = L-1; FLabels = FLabels-1; BLabels = BLabels-1; ULabels = ULabels-1; %%%%%%%%%%%%% The Mex Function for GraphCutSegment %%%%%%%%%%%% %%% SegImage is the segmented image, %%% LLabels is the binary label %%% for each watershed label [SegImage LLabels] = GraphCutSegment(L, MeanColors, ULabels, BLabels,... FDist, BDist, lambda); %% Again Labeled from 1... L = L+1; FLabels = FLabels+1; BLabels = BLabels+1; ULabels = ULabels+1; if(i < numIter) %%%%%% Do NOT do this if final iteration -- just display the segmented image %%%%%% Making new FLabels and BLabels based on the segmentation %%%%%% newFLabels = ULabels(find(LLabels==1.0)); newBLabels = ULabels(find(LLabels==0.0)); %%%%%% Whether new background labels will contain the old ones? % newBLabels = union(newBLabels,BLabels); FColors = MeanColors(newFLabels,:); BColors = MeanColors(newBLabels,:); %%%%%%%% Calculating FG and BG distances based on new segmentation %%%%%%%%%%%%%%%%%% [newFDists newFInd] = ClustDistMembership(FColors, FCClusters, FCovs, FWeights); [newBDists newBInd] = ClustDistMembership(BColors, BCClusters, BCovs, BWeights); for k = 1:NumFClusters relColors = FColors(find(newFInd==k),:); %% Colors belonging to cluster k FCClusters(:,k) = mean(relColors,1)'; FCovs(:,:,k) = cov(relColors); FWeights(1,k) = length(find(newFInd==k)) / length(newFInd); end for k=1:NumBClusters relColors = BColors(find(newBInd==k),:); %% Colors belonging to cluster k BCClusters(:,k) = mean(relColors,1)'; BCovs(:,:,k) = cov(relColors); BWeights(1,k) = length(find(newBInd==k)) / length(newBInd); end end end %%%%%%%%%%%%%%%%%%%%% Display the segmented image %%%%%%%%%%%%%%%%%%% edge_img = edge(SegImage,'canny'); % Put image on black background SegImage = repmat(SegImage,[1,1,3]); SegNewImage = uint8(SegImage) .* uint8(I); % If AutoCut, just show the image if(~alg) figure; imshow(uint8(SegNewImage)); else % If AutoRefine mark a segmentation boundary on original image [IInd,JInd] = ind2sub(size(I1),find(edge_img)); boundImage1 = I(:,:,2); boundImage1(find(edge_img)) = 255; boundImage = I; boundImage(:,:,2) = boundImage1; % Set the image set(ih, 'Cdata', uint8(boundImage)); axis('image');axis('ij');axis('off'); drawnow; segImageHandle = figure; imshow(uint8(SegNewImage)); end SegMask = SegImage; SegResult = SegNewImage; % Save Segmentation Result save('SegResult', 'SegMask', 'SegResult'); % Required for AutoCutRefine save('iter_data','L', 'MeanColors', 'FLabels', 'BLabels', 'FCClusters',... 'FCovs', 'FWeights', 'BCClusters', 'BCovs', 'BWeights'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%% Helper Functions declarations %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [FDist, FInd] = ClustDistMembership(MeanColors, FCClusters, FCovs, FWeights) % CLUSTDISTMEMBERSHIP - Calcuates FG and BG Distances % Authors - Mohit Gupta, Krishnan Ramnath % Affiliation - Robotics Institute, CMU, Pittsburgh % 2006-05-15 NumFClusters = size(FCClusters,2); numULabels = size(MeanColors,1); FDist = zeros(numULabels,1); FInd = zeros(numULabels,1); Ftmp = zeros(numULabels, NumFClusters); for k = 1:NumFClusters M = FCClusters(:,k); CovM = FCovs(:,:,k); W = FWeights(1,k); V = MeanColors - repmat(M',numULabels,1); Ftmp(:,k) = -log((W / sqrt(det(CovM))) * exp(-( sum( ((V * inv(CovM)) .* V),2) /2))); end [FDist, FInd] = min(Ftmp,[],2);
github
jacksky64/imageProcessing-master
creaseg.m
.m
imageProcessing-master/segmentation/creaseg/creaseg/creaseg/creaseg.m
4,537
utf_8
c7fe3231ee32b19b499802aa425d316a
% Copyright or © or Copr. CREATIS laboratory, Lyon, France. % % Contributor: Olivier Bernard, Associate Professor at the french % engineering university INSA (Institut National des Sciences Appliquees) % and a member of the CREATIS-LRMN laboratory (CNRS 5220, INSERM U630, % INSA, Claude Bernard Lyon 1 University) in France (Lyon). % % Date of creation: 8th of October 2009 % % E-mail of the author: [email protected] % % This software is a computer program whose purpose is to evaluate the % performance of different level-set based segmentation algorithms in the % context of image processing (and more particularly on biomedical % images). % % The software has been designed for two main purposes. % - firstly, CREASEG allows you to use six different level-set methods. % These methods have been chosen in order to work with a wide range of % level-sets. You can select for instance classical methods such as % Caselles or Chan & Vese level-set, or more recent approaches such as the % one developped by Lankton or Bernard. % - finally, the software allows you to compare the performance of the six % level-set methods on different images. The performance can be evaluated % either visually, or from measurements (either using the Dice coefficient % or the PSNR value) between a reference and the results of the % segmentation. % % The level-set segmentation platform is citationware. If you are % publishing any work, where this program has been used, or which used one % of the proposed level-set algorithms, please remember that it was % obtained free of charge. You must reference the papers shown below and % the name of the CREASEG software must be mentioned in the publication. % % CREASEG software % "T. Dietenbeck, M. Alessandrini, D. Friboulet, O. Bernard. CREASEG: a % free software for the evaluation of image segmentation algorithms based % on level-set. In IEEE International Conference On Image Processing. % Hong Kong, China, 2010." % % Bernard method % "O. Bernard, D. Friboulet, P. Thevenaz, M. Unser. Variational B-Spline % Level-Set: A Linear Filtering Approach for Fast Deformable Model % Evolution. In IEEE Transactions on Image Processing. volume 18, no. 06, % pp. 1179-1191, 2009." % % Caselles method % "V. Caselles, R. Kimmel, and G. Sapiro. Geodesic active contours. % International Journal of Computer Vision, volume 22, pp. 61-79, 1997." % % Chan & Vese method % "T. Chan and L. Vese. Active contours without edges. IEEE Transactions on % Image Processing. volume10, pp. 266-277, February 2001." % % Lankton method % "S. Lankton, A. Tannenbaum. Localizing Region-Based Active Contours. In % IEEE Transactions on Image Processing. volume 17, no. 11, pp. 2029-2039, % 2008." % % Li method % "C. Li, C.Y. Kao, J.C. Gore, Z. Ding. Minimization of Region-Scalable % Fitting Energy for Image Segmentation. In IEEE Transactions on Image % Processing. volume 17, no. 10, pp. 1940-1949, 2008." % % Shi method % "Yonggang Shi, William Clem Karl. A Real-Time Algorithm for the % Approximation of Level-Set-Based Curve Evolution. In IEEE Transactions % on Image Processing. volume 17, no. 05, pp. 645-656, 2008." % % This software is governed by the BSD license and % abiding by the rules of distribution of free software. % % As a counterpart to the access to the source code and rights to copy, % modify and redistribute granted by the license, users are provided only % with a limited warranty and the software's author, the holder of the % economic rights, and the successive licensors have only limited % liability. % % In this respect, the user's attention is drawn to the risks associated % with loading, using, modifying and/or developing or reproducing the % software by the user in light of its specific status of free software, % that may mean that it is complicated to manipulate, and that also % therefore means that it is reserved for developers and experienced % professionals having in-depth computer knowledge. Users are therefore % encouraged to load and test the software's suitability as regards their % requirements in conditions enabling the security of their systems and/or % data to be ensured and, more generally, to use and operate it in the % same conditions as regards security. % %------------------------------------------------------------------------ function creaseg() clear all; close all hidden; clc; addpath src; warning('off'); %-- create interface gui creaseg_gui();
github
jacksky64/imageProcessing-master
creaseg_createreference.m
.m
imageProcessing-master/segmentation/creaseg/creaseg/creaseg/src/creaseg_createreference.m
6,343
utf_8
8b8ed702092f714ebf41dce7f98e013b
% Copyright or © or Copr. CREATIS laboratory, Lyon, France. % % Contributor: Olivier Bernard, Associate Professor at the french % engineering university INSA (Institut National des Sciences Appliquees) % and a member of the CREATIS-LRMN laboratory (CNRS 5220, INSERM U630, % INSA, Claude Bernard Lyon 1 University) in France (Lyon). % % Date of creation: 8th of October 2009 % % E-mail of the author: [email protected] % % This software is a computer program whose purpose is to evaluate the % performance of different level-set based segmentation algorithms in the % context of image processing (and more particularly on biomedical % images). % % The software has been designed for two main purposes. % - firstly, CREASEG allows you to use six different level-set methods. % These methods have been chosen in order to work with a wide range of % level-sets. You can select for instance classical methods such as % Caselles or Chan & Vese level-set, or more recent approaches such as the % one developped by Lankton or Bernard. % - finally, the software allows you to compare the performance of the six % level-set methods on different images. The performance can be evaluated % either visually, or from measurements (either using the Dice coefficient % or the PSNR value) between a reference and the results of the % segmentation. % % The level-set segmentation platform is citationware. If you are % publishing any work, where this program has been used, or which used one % of the proposed level-set algorithms, please remember that it was % obtained free of charge. You must reference the papers shown below and % the name of the CREASEG software must be mentioned in the publication. % % CREASEG software % "T. Dietenbeck, M. Alessandrini, D. Friboulet, O. Bernard. CREASEG: a % free software for the evaluation of image segmentation algorithms based % on level-set. In IEEE International Conference On Image Processing. % Honk Kong, China, 2010." % % Bernard method % "O. Bernard, D. Friboulet, P. Thevenaz, M. Unser. Variational B-Spline % Level-Set: A Linear Filtering Approach for Fast Deformable Model % Evolution. In IEEE Transactions on Image Processing. volume 18, no. 06, % pp. 1179-1191, 2009." % % Caselles method % "V. Caselles, R. Kimmel, and G. Sapiro. Geodesic active contours. % International Journal of Computer Vision, volume 22, pp. 61-79, 1997." % % Chan & Vese method % "T. Chan and L. Vese. Active contours without edges. IEEE Transactions on % Image Processing. volume10, pp. 266-277, February 2001." % % Lankton method % "S. Lankton, A. Tannenbaum. Localizing Region-Based Active Contours. In % IEEE Transactions on Image Processing. volume 17, no. 11, pp. 2029-2039, % 2008." % % Li method % "C. Li, C.Y. Kao, J.C. Gore, Z. Ding. Minimization of Region-Scalable % Fitting Energy for Image Segmentation. In IEEE Transactions on Image % Processing. volume 17, no. 10, pp. 1940-1949, 2008." % % Shi method % "Yonggang Shi, William Clem Karl. A Real-Time Algorithm for the % Approximation of Level-Set-Based Curve Evolution. In IEEE Transactions % on Image Processing. volume 17, no. 05, pp. 645-656, 2008." % % This software is governed by the BSD license and % abiding by the rules of distribution of free software. % % As a counterpart to the access to the source code and rights to copy, % modify and redistribute granted by the license, users are provided only % with a limited warranty and the software's author, the holder of the % economic rights, and the successive licensors have only limited % liability. % % In this respect, the user's attention is drawn to the risks associated % with loading, using, modifying and/or developing or reproducing the % software by the user in light of its specific status of free software, % that may mean that it is complicated to manipulate, and that also % therefore means that it is reserved for developers and experienced % professionals having in-depth computer knowledge. Users are therefore % encouraged to load and test the software's suitability as regards their % requirements in conditions enabling the security of their systems and/or % data to be ensured and, more generally, to use and operate it in the % same conditions as regards security. % %------------------------------------------------------------------------ function creaseg_createreference() %-- parameters fig = findobj(0,'tag','creaseg'); ud = get(fig,'userdata'); fd = get(ud.imageId,'userdata'); %-- do nothing if no image is loaded if ( isempty(fd.data) ) return; end %-- clean up overlay display keepLS = 1; creaseg_cleanOverlays(keepLS); fd = get(ud.imageId,'userdata'); %-- flush previous reference if any if ( ~isempty(fd.reference) ) fd.reference = zeros(size(fd.data)); end %-- Display information messages set(ud.txtInfo1,'string','Left click to add a point','color','y'); set(ud.txtInfo2,'string','Right click stop drawing contour','color','y'); set(ud.txtInfo3,'string','Middle click to save reference contour','color','y'); set(ud.txtInfo4,'string',''); set(ud.txtInfo5,'string',''); %-- "Unchecking" the figure buttons for i=1:1:3 set(ud.buttonAction(i),'BackgroundColor',[240/255 173/255 105/255]); end for i=6:size(ud.buttonAction) set(ud.buttonAction(i),'BackgroundColor',[240/255 173/255 105/255]); end %-- Put the "Create" button in darker set(ud.handleAlgoComparison(17),'BackgroundColor',[160/255 130/255 95/255]); %-- put see result to disable, just in case set(ud.handleAlgoComparison(24),'enable','off'); %-- cancel initialization drawing mode for k=3:size(ud.handleInit,1) set(ud.handleInit(k),'BackgroundColor',[240/255 173/255 105/255]); end pan off; %-- keep in minf reference mode ud.LastPlot = 'reference'; fd.method = 'Reference'; %-- Set the reference drawing Callbacks set(ud.gcf,'WindowButtonDownFcn',{@creaseg_drawMultiReferenceContours}); set(ud.gcf,'WindowButtonUpFcn',''); %-- UPDATE FD AND UD STRUCTURES ATTACHED TO IMAGEID AND FIG HANDLES set(ud.imageId,'userdata',fd); set(fig,'userdata',ud);
github
jacksky64/imageProcessing-master
creaseg_spline.m
.m
imageProcessing-master/segmentation/creaseg/creaseg/creaseg/src/creaseg_spline.m
5,098
utf_8
fbbdc22b0913e532c31a5e2f2cff495f
% Copyright or © or Copr. CREATIS laboratory, Lyon, France. % % Contributor: Olivier Bernard, Associate Professor at the french % engineering university INSA (Institut National des Sciences Appliquees) % and a member of the CREATIS-LRMN laboratory (CNRS 5220, INSERM U630, % INSA, Claude Bernard Lyon 1 University) in France (Lyon). % % Date of creation: 8th of October 2009 % % E-mail of the author: [email protected] % % This software is a computer program whose purpose is to evaluate the % performance of different level-set based segmentation algorithms in the % context of image processing (and more particularly on biomedical % images). % % The software has been designed for two main purposes. % - firstly, CREASEG allows you to use six different level-set methods. % These methods have been chosen in order to work with a wide range of % level-sets. You can select for instance classical methods such as % Caselles or Chan & Vese level-set, or more recent approaches such as the % one developped by Lankton or Bernard. % - finally, the software allows you to compare the performance of the six % level-set methods on different images. The performance can be evaluated % either visually, or from measurements (either using the Dice coefficient % or the PSNR value) between a reference and the results of the % segmentation. % % The level-set segmentation platform is citationware. If you are % publishing any work, where this program has been used, or which used one % of the proposed level-set algorithms, please remember that it was % obtained free of charge. You must reference the papers shown below and % the name of the CREASEG software must be mentioned in the publication. % % CREASEG software % "T. Dietenbeck, M. Alessandrini, D. Friboulet, O. Bernard. CREASEG: a % free software for the evaluation of image segmentation algorithms based % on level-set. In IEEE International Conference On Image Processing. % Hong Kong, China, 2010." % % Bernard method % "O. Bernard, D. Friboulet, P. Thevenaz, M. Unser. Variational B-Spline % Level-Set: A Linear Filtering Approach for Fast Deformable Model % Evolution. In IEEE Transactions on Image Processing. volume 18, no. 06, % pp. 1179-1191, 2009." % % Caselles method % "V. Caselles, R. Kimmel, and G. Sapiro. Geodesic active contours. % International Journal of Computer Vision, volume 22, pp. 61-79, 1997." % % Chan & Vese method % "T. Chan and L. Vese. Active contours without edges. IEEE Transactions on % Image Processing. volume10, pp. 266-277, February 2001." % % Lankton method % "S. Lankton, A. Tannenbaum. Localizing Region-Based Active Contours. In % IEEE Transactions on Image Processing. volume 17, no. 11, pp. 2029-2039, % 2008." % % Li method % "C. Li, C.Y. Kao, J.C. Gore, Z. Ding. Minimization of Region-Scalable % Fitting Energy for Image Segmentation. In IEEE Transactions on Image % Processing. volume 17, no. 10, pp. 1940-1949, 2008." % % Shi method % "Yonggang Shi, William Clem Karl. A Real-Time Algorithm for the % Approximation of Level-Set-Based Curve Evolution. In IEEE Transactions % on Image Processing. volume 17, no. 05, pp. 645-656, 2008." % % This software is governed by the BSD license and % abiding by the rules of distribution of free software. % % As a counterpart to the access to the source code and rights to copy, % modify and redistribute granted by the license, users are provided only % with a limited warranty and the software's author, the holder of the % economic rights, and the successive licensors have only limited % liability. % % In this respect, the user's attention is drawn to the risks associated % with loading, using, modifying and/or developing or reproducing the % software by the user in light of its specific status of free software, % that may mean that it is complicated to manipulate, and that also % therefore means that it is reserved for developers and experienced % professionals having in-depth computer knowledge. Users are therefore % encouraged to load and test the software's suitability as regards their % requirements in conditions enabling the security of their systems and/or % data to be ensured and, more generally, to use and operate it in the % same conditions as regards security. % %------------------------------------------------------------------------ function [xs, ys] = creaseg_spline(x, y) %-- "Looping" the points to have a nice closed contour i = 7; %-- Number of extra points added if length(x) > i %-- Check if the number of point is sufficient x = [x x(1:i)]; y = [y y(1:i)]; else i2 = i-length(x); x = [x x]; y = [y y]; x = [x x(1:i2)]; y = [y y(1:i2)]; end s_div = 1/10; t = 1:length(x); ts = 1:s_div:length(x); xs = spline(t,x,ts); ys = spline(t,y,ts); %-- Deleting the extra segment (at the begining and at the end) xs = xs(ceil(i/2)/s_div:(length(x)-floor(i/2))/s_div); ys = ys(ceil(i/2)/s_div:(length(x)-floor(i/2))/s_div);
github
jacksky64/imageProcessing-master
creaseg_lankton.m
.m
imageProcessing-master/segmentation/creaseg/creaseg/creaseg/src/creaseg_lankton.m
15,575
utf_8
9d8d19987c200b1ba9e64a4ee5adc544
% Copyright or © or Copr. CREATIS laboratory, Lyon, France. % % Contributor: Olivier Bernard, Associate Professor at the french % engineering university INSA (Institut National des Sciences Appliquees) % and a member of the CREATIS-LRMN laboratory (CNRS 5220, INSERM U630, % INSA, Claude Bernard Lyon 1 University) in France (Lyon). % % Date of creation: 8th of October 2009 % % E-mail of the author: [email protected] % % This software is a computer program whose purpose is to evaluate the % performance of different level-set based segmentation algorithms in the % context of image processing (and more particularly on biomedical % images). % % The software has been designed for two main purposes. % - firstly, CREASEG allows you to use six different level-set methods. % These methods have been chosen in order to work with a wide range of % level-sets. You can select for instance classical methods such as % Caselles or Chan & Vese level-set, or more recent approaches such as the % one developped by Lankton or Bernard. % - finally, the software allows you to compare the performance of the six % level-set methods on different images. The performance can be evaluated % either visually, or from measurements (either using the Dice coefficient % or the PSNR value) between a reference and the results of the % segmentation. % % The level-set segmentation platform is citationware. If you are % publishing any work, where this program has been used, or which used one % of the proposed level-set algorithms, please remember that it was % obtained free of charge. You must reference the papers shown below and % the name of the CREASEG software must be mentioned in the publication. % % CREASEG software % "T. Dietenbeck, M. Alessandrini, D. Friboulet, O. Bernard. CREASEG: a % free software for the evaluation of image segmentation algorithms based % on level-set. In IEEE International Conference On Image Processing. % Hong Kong, China, 2010." % % Bernard method % "O. Bernard, D. Friboulet, P. Thevenaz, M. Unser. Variational B-Spline % Level-Set: A Linear Filtering Approach for Fast Deformable Model % Evolution. In IEEE Transactions on Image Processing. volume 18, no. 06, % pp. 1179-1191, 2009." % % Caselles method % "V. Caselles, R. Kimmel, and G. Sapiro. Geodesic active contours. % International Journal of Computer Vision, volume 22, pp. 61-79, 1997." % % Chan & Vese method % "T. Chan and L. Vese. Active contours without edges. IEEE Transactions on % Image Processing. volume10, pp. 266-277, February 2001." % % Lankton method % "S. Lankton, A. Tannenbaum. Localizing Region-Based Active Contours. In % IEEE Transactions on Image Processing. volume 17, no. 11, pp. 2029-2039, % 2008." % % Li method % "C. Li, C.Y. Kao, J.C. Gore, Z. Ding. Minimization of Region-Scalable % Fitting Energy for Image Segmentation. In IEEE Transactions on Image % Processing. volume 17, no. 10, pp. 1940-1949, 2008." % % Shi method % "Yonggang Shi, William Clem Karl. A Real-Time Algorithm for the % Approximation of Level-Set-Based Curve Evolution. In IEEE Transactions % on Image Processing. volume 17, no. 05, pp. 645-656, 2008." % % This software is governed by the BSD license and % abiding by the rules of distribution of free software. % % As a counterpart to the access to the source code and rights to copy, % modify and redistribute granted by the license, users are provided only % with a limited warranty and the software's author, the holder of the % economic rights, and the successive licensors have only limited % liability. % % In this respect, the user's attention is drawn to the risks associated % with loading, using, modifying and/or developing or reproducing the % software by the user in light of its specific status of free software, % that may mean that it is complicated to manipulate, and that also % therefore means that it is reserved for developers and experienced % professionals having in-depth computer knowledge. Users are therefore % encouraged to load and test the software's suitability as regards their % requirements in conditions enabling the security of their systems and/or % data to be ensured and, more generally, to use and operate it in the % same conditions as regards security. % %------------------------------------------------------------------------ %------------------------------------------------------------------------ % Localized Region Based Active Contour Segmentation: % % seg = localized_seg(I,init_mask,max_its,rad,alpha,method) % % Inputs: I 2D image % init_mask Initialization (1 = foreground, 0 = bg) % max_its Number of iterations to run segmentation for % rad (optional) Localization Radius (in pixels) % smaller = more local, bigger = more global % alpha (optional) Weight of smoothing term % higer = smoother % method (optional) selects localized energy % 1 = Yezzi Energy (usually works better) % 2 = Chan-Vese Energy % % Outputs: seg Final segmentation mask (1=fg, 0=bg) % % Example: % img = imread('tire.tif'); %-- load the image % m = false(size(img)); %-- create initial mask % m(28:157,37:176) = true; % seg = localized_seg(img,m,150); % % Description: This code implements the paper: "Localizing Region Based % Active Contours" By Lankton and Tannenbaum. In this work, typical % region-based active contour energies are localized in order to handle % images with non-homogeneous foregrounds and backgrounds. % % Coded by: Shawn Lankton (www.shawnlankton.com) %------------------------------------------------------------------------ function [seg,phi,its] = creaseg_lankton(I,init_mask,max_its,rad,alpha,thresh,method,neigh,color,display) %-- default value for parameter alpha is .1 if(~exist('alpha','var')) alpha = .2; end if(~exist('thresh','var')) thresh = 0; end %-- default value for parameter color is 'r' if(~exist('color','var')) color = 'r'; end %-- default value for parameter method is 2 if(~exist('method','var')) method = 1; end %-- default behavior is to display intermediate outputs if(~exist('display','var')) display = true; end %-- Ensures image is 2D double matrix I = im2graydouble(I); %-- Default localization radius is 1/10 of average length [dimy dimx] = size(I); if(~exist('rad','var')) rad = round((dimy+dimx)/(2*8)); end % init_mask = init_mask<=0; %-- Create a signed distance map (SDF) from mask phi = mask2phi(init_mask); %-- Create disk disk = getnhood(strel('disk', rad)); %-- fig = findobj(0,'tag','creaseg'); ud = get(fig,'userdata'); %--main loop its = 0; stop = 0; prev_mask = init_mask; c = 0; while ((its < max_its) && ~stop) %-- get the curve's narrow band idx = find(phi <= 1.2 & phi >= -1.2)'; [y x] = ind2sub(size(phi),idx); if ~isempty(idx) switch neigh case 2 % Square NHood %-- get windows for localized statistics xneg = x-rad; xpos = x+rad; %get subscripts for local regions yneg = y-rad; ypos = y+rad; xneg(xneg<1)=1; yneg(yneg<1)=1; %check bounds xpos(xpos>dimx)=dimx; ypos(ypos>dimy)=dimy; %-- re-initialize u,v,Ain,Aout u=zeros(size(idx)); v=zeros(size(idx)); Ain=zeros(size(idx)); Aout=zeros(size(idx)); for i = 1:numel(idx) % for every point in the narrow band img = I(yneg(i):ypos(i),xneg(i):xpos(i)); %sub image P = phi(yneg(i):ypos(i),xneg(i):xpos(i)); %sub phi upts = find(P<=0); %local interior Ain(i) = length(upts)+eps; u(i) = sum(img(upts))/Ain(i); vpts = find(P>0); %local exterior Aout(i) = length(vpts)+eps; v(i) = sum(img(vpts))/Aout(i); end %-- get image-based forces switch method %-choose which energy is localized case 1, %-- YEZZI F = -((u-v).*((I(idx)-u)./Ain+(I(idx)-v)./Aout)); otherwise, %-- CHAN VESE F = -(u-v).*(2.*I(idx)-u-v); end case 1 % Circle NHood %-- compute local stats and get image-based forces F = zeros(1,length(idx)); for i = 1:numel(idx) % for every point in the narrow band F(1,i) = local_nhood(I,phi,y(i),x(i),disk,method); end end %-- get forces from curvature penalty curvature = get_curvature(phi,idx,x,y); %-- gradient descent to minimize energy dphidt = F./max(abs(F)) + alpha*curvature; %-- maintain the CFL condition dt = .45/(max(abs(dphidt))+eps); %-- evolve the curve phi(idx) = phi(idx) + dt.*dphidt; %-- Keep SDF smooth phi = sussman(phi, .5); new_mask = phi<=0; c = convergence(prev_mask,new_mask,thresh,c); if c <= 5 its = its + 1; prev_mask = new_mask; else stop = 1; end %-- intermediate output if (display>0) if ( mod(its,50)==0 ) set(ud.txtInfo1,'string',sprintf('iteration: %d',its),'color',[1 1 0]); showCurveAndPhi(phi,ud,color); drawnow; end else if ( mod(its,10)==0 ) set(ud.txtInfo1,'string',sprintf('iteration: %d',its),'color',[1 1 0]); drawnow; end end else break; end end %-- final output showCurveAndPhi(phi,ud,color); %-- make mask from SDF seg = phi<=0; %-- Get mask from levelset %--------------------------------------------------------------------- %--------------------------------------------------------------------- %-- AUXILIARY FUNCTIONS ---------------------------------------------- %--------------------------------------------------------------------- %--------------------------------------------------------------------- %-- Displays the image with curve superimposed function showCurveAndPhi(phi,ud,cl) axes(get(ud.imageId,'parent')); delete(findobj(get(ud.imageId,'parent'),'type','line')); hold on; [c,h] = contour(phi,[0 0],cl{1},'Linewidth',3); hold off; delete(h); test = isequal(size(c,2),0); while (test==false) s = c(2,1); if ( s == (size(c,2)-1) ) t = c; hold on; plot(t(1,2:end)',t(2,2:end)',cl{1},'Linewidth',3); test = true; else t = c(:,2:s+1); hold on; plot(t(1,1:end)',t(2,1:end)',cl{1},'Linewidth',3); c = c(:,s+2:end); end end %-- converts a mask to a SDF function phi = mask2phi(init_a) phi = bwdist(init_a)-bwdist(1-init_a)+im2double(init_a)-.5; %-- compute curvature along SDF function curvature = get_curvature(phi,idx,x,y) [dimy, dimx] = size(phi); %-- get subscripts of neighbors ym1 = y-1; xm1 = x-1; yp1 = y+1; xp1 = x+1; %-- bounds checking ym1(ym1<1) = 1; xm1(xm1<1) = 1; yp1(yp1>dimy)=dimy; xp1(xp1>dimx) = dimx; %-- get indexes for 8 neighbors idup = sub2ind(size(phi),yp1,x); iddn = sub2ind(size(phi),ym1,x); idlt = sub2ind(size(phi),y,xm1); idrt = sub2ind(size(phi),y,xp1); idul = sub2ind(size(phi),yp1,xm1); idur = sub2ind(size(phi),yp1,xp1); iddl = sub2ind(size(phi),ym1,xm1); iddr = sub2ind(size(phi),ym1,xp1); %-- get central derivatives of SDF at x,y phi_x = -phi(idlt)+phi(idrt); phi_y = -phi(iddn)+phi(idup); phi_xx = phi(idlt)-2*phi(idx)+phi(idrt); phi_yy = phi(iddn)-2*phi(idx)+phi(idup); phi_xy = -0.25*phi(iddl)-0.25*phi(idur)... +0.25*phi(iddr)+0.25*phi(idul); phi_x2 = phi_x.^2; phi_y2 = phi_y.^2; %-- compute curvature (Kappa) curvature = ((phi_x2.*phi_yy + phi_y2.*phi_xx - 2*phi_x.*phi_y.*phi_xy)./... (phi_x2 + phi_y2 +eps).^(3/2)).*(phi_x2 + phi_y2).^(1/2); %-- Converts image to one channel (grayscale) double function img = im2graydouble(img) [dimy, dimx, c] = size(img); if(isfloat(img)) % image is a double if(c==3) img = rgb2gray(uint8(img)); end else % image is a int if(c==3) img = rgb2gray(img); end img = double(img); end %-- level set re-initialization by the sussman method function D = sussman(D, dt) % forward/backward differences a = D - shiftR(D); % backward b = shiftL(D) - D; % forward c = D - shiftD(D); % backward d = shiftU(D) - D; % forward a_p = a; a_n = a; % a+ and a- b_p = b; b_n = b; c_p = c; c_n = c; d_p = d; d_n = d; a_p(a < 0) = 0; a_n(a > 0) = 0; b_p(b < 0) = 0; b_n(b > 0) = 0; c_p(c < 0) = 0; c_n(c > 0) = 0; d_p(d < 0) = 0; d_n(d > 0) = 0; dD = zeros(size(D)); D_neg_ind = find(D < 0); D_pos_ind = find(D > 0); dD(D_pos_ind) = sqrt(max(a_p(D_pos_ind).^2, b_n(D_pos_ind).^2) ... + max(c_p(D_pos_ind).^2, d_n(D_pos_ind).^2)) - 1; dD(D_neg_ind) = sqrt(max(a_n(D_neg_ind).^2, b_p(D_neg_ind).^2) ... + max(c_n(D_neg_ind).^2, d_p(D_neg_ind).^2)) - 1; D = D - dt .* sussman_sign(D) .* dD; %-- whole matrix derivatives function shift = shiftD(M) shift = shiftR(M')'; function shift = shiftL(M) shift = [ M(:,2:size(M,2)) M(:,size(M,2)) ]; function shift = shiftR(M) shift = [ M(:,1) M(:,1:size(M,2)-1) ]; function shift = shiftU(M) shift = shiftL(M')'; function S = sussman_sign(D) S = D ./ sqrt(D.^2 + 1); % Convergence Test function c = convergence(p_mask,n_mask,thresh,c) diff = p_mask - n_mask; n_diff = sum(abs(diff(:))); if n_diff < thresh c = c + 1; else c = 0; end function feature = local_nhood(img, phi, xref, yref, disk, m) [dimx, dimy] = size(img); rad = (size(disk,1)+1)/2; u = 0; v = 0; Au = 0; Av = 0; [X, Y] = find(disk == 1); % X(i) E [1; 2rad-1] X = xref + X - rad; Y = yref + Y - rad; X(X < 1) = 1; X(X > dimx) = dimx; % check bounds Y(Y < 1) = 1; Y(Y > dimy) = dimy; for i = 1:1:length(X) if phi(X(i), Y(i)) <= 0 u = u + img(X(i), Y(i)); Au = Au + 1; else v = v + img(X(i), Y(i)); Av = Av + 1; end end u = u/(Au+eps); v = v/(Av+eps); switch m %-choose which energy is localized case 1, %-- YEZZI feature = -(u-v)*((img(xref, yref)-u)/Au+(img(xref, yref)-v)/Av); % YEZZI otherwise, %-- CHAN VESE feature = -(u-v)*(2*img(xref, yref)-u-v); % CHAN VESE end
github
jacksky64/imageProcessing-master
creaseg_drawManualContour.m
.m
imageProcessing-master/segmentation/creaseg/creaseg/creaseg/src/creaseg_drawManualContour.m
8,753
utf_8
4eb1e62aae8e74976a72ba4b072f54a0
% Copyright or © or Copr. CREATIS laboratory, Lyon, France. % % Contributor: Olivier Bernard, Associate Professor at the french % engineering university INSA (Institut National des Sciences Appliquees) % and a member of the CREATIS-LRMN laboratory (CNRS 5220, INSERM U630, % INSA, Claude Bernard Lyon 1 University) in France (Lyon). % % Date of creation: 8th of October 2009 % % E-mail of the author: [email protected] % % This software is a computer program whose purpose is to evaluate the % performance of different level-set based segmentation algorithms in the % context of image processing (and more particularly on biomedical % images). % % The software has been designed for two main purposes. % - firstly, CREASEG allows you to use six different level-set methods. % These methods have been chosen in order to work with a wide range of % level-sets. You can select for instance classical methods such as % Caselles or Chan & Vese level-set, or more recent approaches such as the % one developped by Lankton or Bernard. % - finally, the software allows you to compare the performance of the six % level-set methods on different images. The performance can be evaluated % either visually, or from measurements (either using the Dice coefficient % or the PSNR value) between a reference and the results of the % segmentation. % % The level-set segmentation platform is citationware. If you are % publishing any work, where this program has been used, or which used one % of the proposed level-set algorithms, please remember that it was % obtained free of charge. You must reference the papers shown below and % the name of the CREASEG software must be mentioned in the publication. % % CREASEG software % "T. Dietenbeck, M. Alessandrini, D. Friboulet, O. Bernard. CREASEG: a % free software for the evaluation of image segmentation algorithms based % on level-set. In IEEE International Conference On Image Processing. % Hong Kong, China, 2010." % % Bernard method % "O. Bernard, D. Friboulet, P. Thevenaz, M. Unser. Variational B-Spline % Level-Set: A Linear Filtering Approach for Fast Deformable Model % Evolution. In IEEE Transactions on Image Processing. volume 18, no. 06, % pp. 1179-1191, 2009." % % Caselles method % "V. Caselles, R. Kimmel, and G. Sapiro. Geodesic active contours. % International Journal of Computer Vision, volume 22, pp. 61-79, 1997." % % Chan & Vese method % "T. Chan and L. Vese. Active contours without edges. IEEE Transactions on % Image Processing. volume10, pp. 266-277, February 2001." % % Lankton method % "S. Lankton, A. Tannenbaum. Localizing Region-Based Active Contours. In % IEEE Transactions on Image Processing. volume 17, no. 11, pp. 2029-2039, % 2008." % % Li method % "C. Li, C.Y. Kao, J.C. Gore, Z. Ding. Minimization of Region-Scalable % Fitting Energy for Image Segmentation. In IEEE Transactions on Image % Processing. volume 17, no. 10, pp. 1940-1949, 2008." % % Shi method % "Yonggang Shi, William Clem Karl. A Real-Time Algorithm for the % Approximation of Level-Set-Based Curve Evolution. In IEEE Transactions % on Image Processing. volume 17, no. 05, pp. 645-656, 2008." % % This software is governed by the BSD license and % abiding by the rules of distribution of free software. % % As a counterpart to the access to the source code and rights to copy, % modify and redistribute granted by the license, users are provided only % with a limited warranty and the software's author, the holder of the % economic rights, and the successive licensors have only limited % liability. % % In this respect, the user's attention is drawn to the risks associated % with loading, using, modifying and/or developing or reproducing the % software by the user in light of its specific status of free software, % that may mean that it is complicated to manipulate, and that also % therefore means that it is reserved for developers and experienced % professionals having in-depth computer knowledge. Users are therefore % encouraged to load and test the software's suitability as regards their % requirements in conditions enabling the security of their systems and/or % data to be ensured and, more generally, to use and operate it in the % same conditions as regards security. % %------------------------------------------------------------------------ function creaseg_drawManualContour(src,evt) %-- get structures fig = findobj(0,'tag','creaseg'); ud = get(fig,'userdata'); fd = get(ud.imageId,'userdata'); pos = floor(get(ud.gca(1),'CurrentPoint')); %-- Clic outside the image => do nothing if ~( pos(1,1) < size(fd.data,2) && pos(1,1) > 1 && pos(1,2) < size(fd.data,1) && pos(1,2) >1 ) return; end if ( strcmp(get(ud.gcf,'SelectionType'),'normal') ) %-- Set drawingManualFlag flag to 1 fd.drawingManualFlag = 1; %-- delete any overlay lines if ( size(fd.handleManual,2)>0 ) for k=1:size(fd.handleManual{1},1) delete(fd.handleManual{1}(k)); end fd.handleManual(1)=[]; end %-- Get point coordinates pt = get(ud.gca,'CurrentPoint'); pt = pt(1,1:2); if (isempty(fd.points)) fd.points = [pt(1),pt(2)]; hold on; h = plot(pt(1), pt(2), 'oy', 'linewidth', 2); fd.handleManual{1} = h; else fd.points(end+1,:) = [pt(1),pt(2)]; color = ud.colorSpec(get(ud.handleContourColor,'userdata')); if length(fd.points(:,1)) < 3 % If there's only 2 points, display a line instead of spline hold on; h1 = plot(fd.points(:,1),fd.points(:,2),'--','color',color{1},'Linewidth',2); tmp = fd.points(1,:); tmp(end+1,:) = fd.points(end,:); h2 = plot(tmp(:,1), tmp(:,2), 'y--', 'linewidth', 2); else [xs, ys] = creaseg_spline(fd.points(:,1)',fd.points(:,2)'); % Find the position of the last (fin) and first (deb) points of fd.points in xs and ys fin = find((xs == fd.points(end,1)) & (ys == fd.points(end,2)) ); deb = find((xs == fd.points(1,1)) & (ys == fd.points(1,2)) ); % Change the point order to have deb->fin->deb xs = xs([deb:end, 1:deb]); ys = ys([deb:end, 1:deb]); if deb > fin % And compute the new position of the last point idx = length(xs) + fin - deb; else idx = fin - deb; end clear deb fin; hold on; h1 = plot(xs(1:idx),ys(1:idx),'--','color',color{1},'Linewidth',2); hold on; h2 = plot(xs(idx:end),ys(idx:end),'y--','Linewidth',2); end h3 = plot(fd.points(:,1), fd.points(:,2), 'oy', 'linewidth', 2); hold off; fd.handleManual{1} = [h1;h2;h3]; end else %-- create final contour %-- Set drawingManualFlag flag to 0 fd.drawingManualFlag = 0; %-- display final contour if ( size(fd.points,1)>2 ) %-- delete any overlay lines if ( size(fd.handleManual,2)>0 ) for k=1:size(fd.handleManual{1},1) delete(fd.handleManual{1}(k)); end fd.handleManual(1)=[]; end %-- color = ud.colorSpec(get(ud.handleContourColor,'userdata')); if length(fd.points(:,1)) < 3 tmp = fd.points; tmp(end+1,:) = tmp(1,:); hold on; h = plot(tmp(:,1),tmp(:,2),'--','color',color{1},'Linewidth',2); else [xs, ys] = creaseg_spline(fd.points(:,1)',fd.points(:,2)'); hold on; h = plot(xs,ys,'--','color',color{1},'Linewidth',2); end fd.handleManual{1} = h; %-- create manual mask X = get(fd.handleManual{1},'X'); Y = get(fd.handleManual{1},'Y'); fd.levelset = roipoly(fd.data,X,Y); %-- save initialization info ud.LastPlot = 'levelset'; fd.method = 'Initial region'; %-- enable run and pointer buttons set(ud.buttonAction(2),'enable','on'); set(ud.buttonAction(3),'enable','on'); end fd.points = []; end %-- save structure set(ud.imageId,'userdata',fd); set(ud.gcf,'userdata',ud);
github
jacksky64/imageProcessing-master
creaseg_shi.m
.m
imageProcessing-master/segmentation/creaseg/creaseg/creaseg/src/creaseg_shi.m
17,807
utf_8
6f8e7899e227bafa2afc8bbfe60644a9
% Copyright or © or Copr. CREATIS laboratory, Lyon, France. % % Contributor: Olivier Bernard, Associate Professor at the french % engineering university INSA (Institut National des Sciences Appliquees) % and a member of the CREATIS-LRMN laboratory (CNRS 5220, INSERM U630, % INSA, Claude Bernard Lyon 1 University) in France (Lyon). % % Date of creation: 8th of October 2009 % % E-mail of the author: [email protected] % % This software is a computer program whose purpose is to evaluate the % performance of different level-set based segmentation algorithms in the % context of image processing (and more particularly on biomedical % images). % % The software has been designed for two main purposes. % - firstly, CREASEG allows you to use six different level-set methods. % These methods have been chosen in order to work with a wide range of % level-sets. You can select for instance classical methods such as % Caselles or Chan & Vese level-set, or more recent approaches such as the % one developped by Lankton or Bernard. % - finally, the software allows you to compare the performance of the six % level-set methods on different images. The performance can be evaluated % either visually, or from measurements (either using the Dice coefficient % or the PSNR value) between a reference and the results of the % segmentation. % % The level-set segmentation platform is citationware. If you are % publishing any work, where this program has been used, or which used one % of the proposed level-set algorithms, please remember that it was % obtained free of charge. You must reference the papers shown below and % the name of the CREASEG software must be mentioned in the publication. % % CREASEG software % "T. Dietenbeck, M. Alessandrini, D. Friboulet, O. Bernard. CREASEG: a % free software for the evaluation of image segmentation algorithms based % on level-set. In IEEE International Conference On Image Processing. % Hong Kong, China, 2010." % % Bernard method % "O. Bernard, D. Friboulet, P. Thevenaz, M. Unser. Variational B-Spline % Level-Set: A Linear Filtering Approach for Fast Deformable Model % Evolution. In IEEE Transactions on Image Processing. volume 18, no. 06, % pp. 1179-1191, 2009." % % Caselles method % "V. Caselles, R. Kimmel, and G. Sapiro. Geodesic active contours. % International Journal of Computer Vision, volume 22, pp. 61-79, 1997." % % Chan & Vese method % "T. Chan and L. Vese. Active contours without edges. IEEE Transactions on % Image Processing. volume10, pp. 266-277, February 2001." % % Lankton method % "S. Lankton, A. Tannenbaum. Localizing Region-Based Active Contours. In % IEEE Transactions on Image Processing. volume 17, no. 11, pp. 2029-2039, % 2008." % % Li method % "C. Li, C.Y. Kao, J.C. Gore, Z. Ding. Minimization of Region-Scalable % Fitting Energy for Image Segmentation. In IEEE Transactions on Image % Processing. volume 17, no. 10, pp. 1940-1949, 2008." % % Shi method % "Yonggang Shi, William Clem Karl. A Real-Time Algorithm for the % Approximation of Level-Set-Based Curve Evolution. In IEEE Transactions % on Image Processing. volume 17, no. 05, pp. 645-656, 2008." % % This software is governed by the BSD license and % abiding by the rules of distribution of free software. % % As a counterpart to the access to the source code and rights to copy, % modify and redistribute granted by the license, users are provided only % with a limited warranty and the software's author, the holder of the % economic rights, and the successive licensors have only limited % liability. % % In this respect, the user's attention is drawn to the risks associated % with loading, using, modifying and/or developing or reproducing the % software by the user in light of its specific status of free software, % that may mean that it is complicated to manipulate, and that also % therefore means that it is reserved for developers and experienced % professionals having in-depth computer knowledge. Users are therefore % encouraged to load and test the software's suitability as regards their % requirements in conditions enabling the security of their systems and/or % data to be ensured and, more generally, to use and operate it in the % same conditions as regards security. % %------------------------------------------------------------------------ %------------------------------------------------------------------------ % Description: This code implements the paper: "A Real-Time Algorithm for % the Approximation of Level-Set-Based Curve Evolution." By Yonggang Shi. % % Coded by: Olivier Bernard (www.creatis.insa-lyon.fr/~bernard) %------------------------------------------------------------------------ function [seg,phi,n] = creaseg_shi(img,init_mask,max_its,Na,Ns,Sigma,Ng,color,display) %-- default value for parameter max_its is 100 if(~exist('max_its','var')) max_its = 100; end %-- default value for parameter na is 30 if(~exist('Na','var')) Na = 30; end %-- default value for parameter ns is 3 if(~exist('Ns','var')) Ns = 3; end %-- default value for parameter sigma is 9 if(~exist('Sigma','var')) Sigma = 3; end %-- default value for parameter ng is 7 if(~exist('Ng','var')) Ng = 1; end %-- default value for parameter color is 'r' if(~exist('color','var')) color = 'r'; end %-- default behavior is to display intermediate outputs if(~exist('display','var')) display = true; end % init_mask = init_mask<=0; %-- fig = findobj(0,'tag','creaseg'); ud = get(fig,'userdata'); %-- Create the initial level-set [phi,Lin,Lout,size_in,size_out] = createInitialLevelSet(init_mask); %-- Create feature image [feature,u,v,Ain,Aout] = createFeatureImage(phi,img); %-- main looop stop_cond = 0; % Stopping condition n = 1; while ( (n<=max_its) && (stop_cond==0) ) % Data dependent evolution na = 0; while ( (na<Na) && (n<=max_its) && (stop_cond==0) ) [Lin,Lout,phi,u,v,Ain,Aout,size_in,size_out] = ... shi_evolution_subCV(img,Lin,Lout,phi,feature,u,v,Ain,Aout,size_in,size_out); %-- intermediate output if (display>0) if ( mod(na,50)==0 ) set(ud.txtInfo1,'string',sprintf('iteration: %d',n),'color',[1 1 0]); showCurveAndPhi(phi,ud,color); drawnow; end else if ( mod(na,10)==0 ) set(ud.txtInfo1,'string',sprintf('iteration: %d',n),'color',[1 1 0]); drawnow; end end stop_cond = stopping_condition(feature,Lin,Lout,size_in,size_out); if ( stop_cond==0 ) % Mise à jour de la feature image feature = zeros(size(phi)); [x,y] = find(abs(phi) < 2); feature(x,y) = -(img(x,y) - u).^2 + (img(x,y) - v).^2; feature = feature./max(abs(feature(:))); end na = na+1; n = n+1; end % smoothing evolution for ns=1:1:Ns Fint = smoothing(phi,Lin,Lout,size_in,size_out,Ng,Sigma); [Lin,Lout,phi,u,v,Ain,Aout,size_in,size_out] = ... shi_evolution_subCV(img,Lin,Lout,phi,Fint,u,v,Ain,Aout,size_in,size_out); n = n+1; end if (stop_cond==0) feature = zeros(size(phi)); [x,y] = find(abs(phi) < 2); feature(x,y) = -(img(x,y) - u).^2 + (img(x,y) - v).^2; % Chan & Vese feature = feature./max(abs(feature(:))); end end %-- final output showCurveAndPhi(phi,ud,color); %-- make mask from SDF seg = phi<=0; %-- Get mask from levelset %--------------------------------------------------------------------- %--------------------------------------------------------------------- %-- AUXILIARY FUNCTIONS ---------------------------------------------- %--------------------------------------------------------------------- %--------------------------------------------------------------------- %-- Displays the image with curve superimposed function showCurveAndPhi(phi,ud,cl) axes(get(ud.imageId,'parent')); delete(findobj(get(ud.imageId,'parent'),'type','line')); hold on; [c,h] = contour(phi,[0 0],cl{1},'Linewidth',3); hold off; delete(h); test = isequal(size(c,2),0); while (test==false) s = c(2,1); if ( s == (size(c,2)-1) ) t = c; hold on; plot(t(1,2:end)',t(2,2:end)',cl{1},'Linewidth',3); test = true; else t = c(:,2:s+1); hold on; plot(t(1,1:end)',t(2,1:end)',cl{1},'Linewidth',3); c = c(:,s+2:end); end end %-- Create the initial discrete level-set from mask function [u,Lin,Lout,size_in,size_out] = createInitialLevelSet(mask) tmp = ones(size(mask))*3; tmp(mask>0) = -3; u = tmp; [nrow,ncol] = size(u); [x,y] = find(tmp==-3); for j=1:size(x,1) neigh = voisinage([x(j);y(j)],nrow,ncol); k = 1; stop = 0; while ( ( k<5 ) && ( stop==0 ) ) if ( tmp(neigh(1,k),neigh(2,k)) > -3 ) u(x(j),y(j)) = 1; stop = 1; end k = k + 1; end end tmp(u>-3) = 3; [x,y] = find(tmp==-3); for j=1:size(x,1) neigh = voisinage([x(j);y(j)],nrow,ncol); k = 1; stop = 0; while ( ( k<5 ) && ( stop==0 ) ) if ( tmp(neigh(1,k),neigh(2,k)) > -3 ) u(x(j),y(j)) = -1; stop = 1; end k = k + 1; end end Lin = zeros(2,round(size(u,1)*size(u,2)/6)); Lout = zeros(2,round(size(u,1)*size(u,2)/6)); size_in = 0; size_out = 0; for i=1:1:size(u,1) for j=1:1:size(u,2) if ( u(i,j) == 1 ) size_out = size_out + 1; Lout(:,size_out) = [i;j]; end if ( u(i,j) == -1 ) size_in = size_in + 1; Lin(:,size_in) = [i;j]; end end end %-- Find the neighborhood of one pixel function N = voisinage(x,nrow,ncol) i = x(1); j = x(2); I1 = i+1; if (I1 > nrow) I1 = nrow; end I2 = i-1; if (I2 < 1) I2 = 1; end J1 = j+1; if (J1 > ncol) J1 = ncol; end J2 = j-1; if (J2 < 1) J2 = 1; end N = [I1, I2, i, i; j, j, J1, J2]; %-- Create feature image for data dependent cycle function [feature, u, v, Ain, Aout] = createFeatureImage(phi, im) upts = find(phi<=0); % interior points vpts = find(phi>0); % exterior points Ain = length(upts); % interior area Aout = length(vpts); % exterior area u = sum(im(upts))/(Ain+eps); % interior mean v = sum(im(vpts))/(Aout+eps); % exterior mean feature = zeros(size(phi)); [x,y] = find(abs(phi) < 2); feature(x,y) = -(im(x,y) - u).^2 + (im(x,y) - v).^2; feature = feature./max(abs(feature(:))); %-- Testing convergence function sc = stopping_condition(F, Li, Lo,size_in,size_out) sc = 1; i = 1; while( i<size_out && sc ) x = Lo(1,i); y = Lo(2,i); if F(x,y)>0 sc = 0; end i = i+1; end i = 1; while( i<size_in && sc ) x = Li(1,i); y = Li(2,i); if F(x,y)<0 sc = 0; end i = i + 1; end %-- Create feature image for smoothing cycle function Fi = smoothing(phi, Li, Lo,size_in,size_out, sg, sigma) [nr, nc] = size(phi); Fi = zeros(nr, nc); Gaussian = fspecial('gaussian', [sg, sg], sigma); H = zeros(size(phi)); H(phi<0) = 1; HG = imfilter(H, Gaussian); for i = 1:1:size_out x = Lo(1,i); y = Lo(2,i); if ( HG(x,y)>1/2 ) Fi(x,y) = 1; end end for i = 1:1:size_in x = Li(1,i); y = Li(2,i); if ( HG(x,y)<1/2 ) Fi(x,y) = -1; end end %-- shi_evolution_subCV function [Linmod, Loutmod, Phimod, umod, vmod, Ai, Ao,s_i,s_o] = ... shi_evolution_subCV(img, Lin, Lout, phi, feature, u, v, Ain, Aout,size_in,size_out) [nrow,ncol] = size(phi); Linmod = Lin; Loutmod = Lout; Phimod = phi; s_i = size_in; s_o = size_out; umod = u; Ai = Ain; vmod = v; Ao = Aout; % Step 1: Outward evolution c = 1; N = s_o; while ( c <= N ) i = Loutmod(1, c); j = Loutmod(2, c); if ( feature(i, j) > 0 ) [Linmod, Loutmod, Phimod,s_i,s_o] = ... switch_in(c, Linmod, Loutmod, Phimod, s_i, s_o, nrow, ncol); umod = (umod*Ai + img(i, j))/(Ai + 1); vmod = (vmod*Ao - img(i, j))/(Ao - 1); Ai = Ai + 1; Ao = Ao - 1; c = c-1; N = N-1; end c = c+1; end % Step 2: Eliminate redundant point in Lin [Linmod, Phimod, s_i] = suppr_Lin(Linmod, Phimod, s_i, nrow, ncol); % Step 3: Inward evolution c = 1; N = s_i; while (c <= N) i = Linmod(1, c); j = Linmod(2, c); if ( feature(i, j) < 0 ) [Linmod, Loutmod, Phimod,s_i,s_o] = ... switch_out(c, Linmod, Loutmod, Phimod,s_i,s_o, nrow, ncol); umod = (umod*Ai - img(i, j))/(Ai - 1); vmod = (vmod*Ao + img(i, j))/(Ao + 1); Ai = Ai - 1; Ao = Ao + 1; c = c-1; N = N-1; end c = c+1; end % Step 4: Eliminate redundant point in Lout [Loutmod, Phimod,s_o] = suppr_Lout(Loutmod, Phimod,s_o,nrow, ncol); function [Linmod, Loutmod, Phimod,s_i,s_o] = ... switch_in(c, Lin, Lout, phi,size_in,size_out, nrow, ncol) x = [Lout(1, c); Lout(2, c)]; Phimod = phi; Linmod = Lin; Loutmod = Lout; % on ajoute x a Lin Linmod(:,size_in+1) = x; Phimod(x(1, 1), x(2, 1)) = -1; s_i = size_in + 1; % Suppression de x de Lout if (c == 1) Loutmod(:,1:size_out-1) = Lout(:, 2:size_out); elseif (c == size_out) Loutmod(:,1:size_out-1) = Lout(:, 1:size_out-1); else Loutmod(:,1:size_out-1) = [Lout(:, 1:c-1),Lout(:, c+1:size_out)]; end s_o = size_out - 1; % Mise a jour du voisinage N = voisinage(x, nrow, ncol); for k=1:1:4 y = [N(1, k); N(2, k)]; i = N(1, k); j = N(2, k); if phi(i, j) == 3 % y est un point exterieur Phimod(i, j) = 1; % Mise a jour de phi(j) Loutmod(:,s_o+1) = y; % Mise a jour de Lout s_o = s_o + 1; end end function [Linmod, Loutmod, Phimod,s_i,s_o] = ... switch_out(c, Lin, Lout, phi,size_in,size_out, nrow, ncol) x = [Lin(1, c); Lin(2, c)]; Phimod = phi; Linmod = Lin; Loutmod = Lout; % on ajoute x a Lout Loutmod(:,size_out+1) = x; Phimod(x(1, 1), x(2, 1)) = 1; s_o = size_out + 1; % Suppression de x de Lin if (c == 1) Linmod(:,1:size_in-1) = Lin(:, 2:size_in); elseif (c == size_in) Linmod(:,1:size_in-1) = Lin(:, 1:size_in-1); else Linmod(:,1:size_in-1) = [Lin(:, 1:c-1), Lin(:, c+1:size_in)]; end s_i = size_in-1; N = voisinage(x, nrow, ncol); for k=1:1:4 y = [N(1, k); N(2, k)]; i = N(1, k); j = N(2, k); if (phi(i, j) == -3) % y est un point interieur Phimod(i, j) = -1; % Mise a jour de phi(j) Linmod(:,s_i+1) = y; % Mise a jour de Lin s_i = s_i + 1; end end function [Linmod, Phimod,s_i] = suppr_Lin(Lin, phi,size_in, nrow, ncol) Linmod = Lin; Phimod = phi; s_i = size_in; k=1; while (k <= s_i) x = [Lin(1, k); Lin(2, k)]; N = voisinage(x, nrow, ncol); i = x(1, 1); j = x(2, 1); b = 0; for c=1:1:4 if (phi(N(1, c), N(2, c)) < 0) b = b+1; end end if (b == 4) % Suppression de x de Lin if (k == 1) Linmod(:,1:s_i-1) = Lin(:,2:s_i); elseif (k == s_i) Linmod(:,1:s_i-1) = Lin(:,1:s_i-1); else Linmod(:,1:s_i-1) = [Lin(:,1:k-1),Lin(:,k+1:s_i)]; end k = k-1; s_i = s_i-1; Phimod(i,j) = -3; Lin = Linmod; end k = k+1; end function [Loutmod, Phimod,s_o] = suppr_Lout(Lout, phi,size_out, nrow, ncol) Loutmod = Lout; Phimod = phi; s_o = size_out; k = 1; while (k <= s_o) x = [Lout(1, k); Lout(2, k)]; N = voisinage(x, nrow, ncol); i = x(1, 1); j = x(2, 1); b = 0; for c = 1:1:4 if (phi(N(1, c), N(2, c)) > 0) b = b+1; end end if (b == 4) % Suppression de x de Lout if (k == 1) Loutmod(:,1:s_o-1) = Lout(:, 2:s_o); elseif (k == s_o) Loutmod(:,1:s_o-1) = Lout(:, 1:s_o-1); else Loutmod(:,1:s_o-1) = [Lout(:, 1:k-1),Lout(:, k+1:s_o)]; end k = k-1; s_o = s_o-1; Phimod(i, j) = 3; Lout = Loutmod; end k = k+1; end
github
jacksky64/imageProcessing-master
creaseg_chunmingli.m
.m
imageProcessing-master/segmentation/creaseg/creaseg/creaseg/src/creaseg_chunmingli.m
12,415
utf_8
e5611a1a5cab20cb2692380b71eef4a4
% Copyright or © or Copr. CREATIS laboratory, Lyon, France. % % Contributor: Olivier Bernard, Associate Professor at the french % engineering university INSA (Institut National des Sciences Appliquees) % and a member of the CREATIS-LRMN laboratory (CNRS 5220, INSERM U630, % INSA, Claude Bernard Lyon 1 University) in France (Lyon). % % Date of creation: 8th of October 2009 % % E-mail of the author: [email protected] % % This software is a computer program whose purpose is to evaluate the % performance of different level-set based segmentation algorithms in the % context of image processing (and more particularly on biomedical % images). % % The software has been designed for two main purposes. % - firstly, CREASEG allows you to use six different level-set methods. % These methods have been chosen in order to work with a wide range of % level-sets. You can select for instance classical methods such as % Caselles or Chan & Vese level-set, or more recent approaches such as the % one developped by Lankton or Bernard. % - finally, the software allows you to compare the performance of the six % level-set methods on different images. The performance can be evaluated % either visually, or from measurements (either using the Dice coefficient % or the PSNR value) between a reference and the results of the % segmentation. % % The level-set segmentation platform is citationware. If you are % publishing any work, where this program has been used, or which used one % of the proposed level-set algorithms, please remember that it was % obtained free of charge. You must reference the papers shown below and % the name of the CREASEG software must be mentioned in the publication. % % CREASEG software % "T. Dietenbeck, M. Alessandrini, D. Friboulet, O. Bernard. CREASEG: a % free software for the evaluation of image segmentation algorithms based % on level-set. In IEEE International Conference On Image Processing. % Hong Kong, China, 2010." % % Bernard method % "O. Bernard, D. Friboulet, P. Thevenaz, M. Unser. Variational B-Spline % Level-Set: A Linear Filtering Approach for Fast Deformable Model % Evolution. In IEEE Transactions on Image Processing. volume 18, no. 06, % pp. 1179-1191, 2009." % % Caselles method % "V. Caselles, R. Kimmel, and G. Sapiro. Geodesic active contours. % International Journal of Computer Vision, volume 22, pp. 61-79, 1997." % % Chan & Vese method % "T. Chan and L. Vese. Active contours without edges. IEEE Transactions on % Image Processing. volume10, pp. 266-277, February 2001." % % Lankton method % "S. Lankton, A. Tannenbaum. Localizing Region-Based Active Contours. In % IEEE Transactions on Image Processing. volume 17, no. 11, pp. 2029-2039, % 2008." % % Li method % "C. Li, C.Y. Kao, J.C. Gore, Z. Ding. Minimization of Region-Scalable % Fitting Energy for Image Segmentation. In IEEE Transactions on Image % Processing. volume 17, no. 10, pp. 1940-1949, 2008." % % Shi method % "Yonggang Shi, William Clem Karl. A Real-Time Algorithm for the % Approximation of Level-Set-Based Curve Evolution. In IEEE Transactions % on Image Processing. volume 17, no. 05, pp. 645-656, 2008." % % This software is governed by the BSD license and % abiding by the rules of distribution of free software. % % As a counterpart to the access to the source code and rights to copy, % modify and redistribute granted by the license, users are provided only % with a limited warranty and the software's author, the holder of the % economic rights, and the successive licensors have only limited % liability. % % In this respect, the user's attention is drawn to the risks associated % with loading, using, modifying and/or developing or reproducing the % software by the user in light of its specific status of free software, % that may mean that it is complicated to manipulate, and that also % therefore means that it is reserved for developers and experienced % professionals having in-depth computer knowledge. Users are therefore % encouraged to load and test the software's suitability as regards their % requirements in conditions enabling the security of their systems and/or % data to be ensured and, more generally, to use and operate it in the % same conditions as regards security. % %------------------------------------------------------------------------ %------------------------------------------------------------------------ % Description: This code implements the paper: "Minimization of % Region-Scalable Fitting Energy for Image Segmentation." By Chunming Li. % % Coded by: Chunming Li % E-mail: [email protected] % URL: http://www.engr.uconn.edu/~cmli/ %------------------------------------------------------------------------ function [seg,phi,its] = creaseg_chunmingli(img,init_mask,max_its,length,regularization,scale,thresh,color,display) %-- default value for parameter max_its is 100 if(~exist('max_its','var')) max_its = 100; end %-- default value for parameter length is 1 if(~exist('length','var')) length = 1; end %-- default value for parameter penalizing is 1 if(~exist('regularization','var')) regularization = 1; end %-- default value for parameter scale is 1 if(~exist('scale','var')) scale = 1; end %-- default value for parameter thresh is 0 if(~exist('thresh','var')) thresh = 0; end %-- default value for parameter color is 'r' if(~exist('color','var')) color = 'r'; end %-- default behavior is to display intermediate outputs if(~exist('display','var')) display = true; end % init_mask = init_mask<=0; %-- lambda1 = 1.0; lambda2 = 1.0; nu = length*255*255; % coefficient of the length term %-- initialLSF = -init_mask.*4 + (1 - init_mask).*4; phi = initialLSF; %-- timestep = .1; % time step mu = regularization; % coefficient of the level set (distance) regularization term P(\phi) epsilon = 1.0; % the paramater in the definition of smoothed Dirac function sigma = scale; % scale parameter in Gaussian kernel % Note: A larger scale parameter sigma, such as sigma=10, would make the LBF algorithm more robust % to initialization, but the segmentation result may not be as accurate as using % a small sigma when there is severe intensity inhomogeneity in the image. If the intensity % inhomogeneity is not severe, a relatively larger sigma can be used to increase the robustness of the LBF % algorithm. K = fspecial('gaussian',round(2*sigma)*2+1,sigma); % the Gaussian kernel KI = conv2(img,K,'same'); % compute the convolution of the image with the Gaussian kernel outside the iteration % See Section IV-A in the above IEEE TIP paper for implementation. KONE = conv2(ones(size(img)),K,'same'); % compute the convolution of Gaussian kernel and constant 1 outside the iteration % See Section IV-A in the above IEEE TIP paper for implementation. %-- fig = findobj(0,'tag','creaseg'); ud = get(fig,'userdata'); %--main loop its = 0; stop = 0; prev_mask = init_mask; c = 0; while ((its < max_its) && ~stop) %-- phi = LSE_LBF(phi,img,K,KI,KONE,nu,timestep,mu,lambda1,lambda2,epsilon,1); new_mask = phi<=0; c = convergence(prev_mask,new_mask,thresh,c); if c <= 5 its = its + 1; prev_mask = new_mask; else stop = 1; end %-- intermediate output if (display>0) if ( mod(its,15)==0 ) set(ud.txtInfo1,'string',sprintf('iteration: %d',its),'color',[1 1 0]); showCurveAndPhi(phi,ud,color); drawnow; end else if ( mod(its,10)==0 ) set(ud.txtInfo1,'string',sprintf('iteration: %d',its),'color',[1 1 0]); drawnow; end end end %-- final output showCurveAndPhi(phi,ud,color); %-- make mask from SDF seg = phi<=0; %-- Get mask from levelset %--------------------------------------------------------------------- %--------------------------------------------------------------------- %-- AUXILIARY FUNCTIONS ---------------------------------------------- %--------------------------------------------------------------------- %--------------------------------------------------------------------- %-- Displays the image with curve superimposed function showCurveAndPhi(phi,ud,cl) axes(get(ud.imageId,'parent')); delete(findobj(get(ud.imageId,'parent'),'type','line')); hold on; [c,h] = contour(phi,[0 0],cl{1},'Linewidth',3); hold off; delete(h); test = isequal(size(c,2),0); while (test==false) s = c(2,1); if ( s == (size(c,2)-1) ) t = c; hold on; plot(t(1,2:end)',t(2,2:end)',cl{1},'Linewidth',3); test = true; else t = c(:,2:s+1); hold on; plot(t(1,1:end)',t(2,1:end)',cl{1},'Linewidth',3); c = c(:,s+2:end); end end % LSE_LBF implements the level set evolution (LSE) for the method in Chunming Li et al's paper: % "Minimization of Region-Scalable Fitting Energy for Image Segmentation", % IEEE Trans. Image Processing(TIP), vol. 17 (10), pp.1940-1949, 2008. % % Author: Chunming Li, all rights reserved % E-mail: [email protected] % URL: http://www.engr.uconn.edu/~cmli/ % For easy understanding of my code, please read the comments in the code that refer % to the corresponding equations in the above IEEE TIP paper. % (Comments added by Ren Zhao at Univ. of Waterloo) function phi = LSE_LBF(phi0,img,Ksigma,KI,KONE,nu,timestep,mu,lambda1,lambda2,epsilon,numIter) phi = phi0; for k1=1:numIter phi = NeumannBoundCond(phi); K = curvature_central(phi); DrcU = (epsilon/pi)./(epsilon^2.+phi.^2); % eq.(9) [f1,f2] = localBinaryFit(img,phi,KI,KONE,Ksigma,epsilon); %-- compute lambda1*e1-lambda2*e2 s1 = lambda1.*f1.^2-lambda2.*f2.^2; % compute lambda1*e1-lambda2*e2 in the 1st term in eq. (15) in IEEE TIP 08 s2 = lambda1.*f1-lambda2.*f2; dataForce = (lambda1-lambda2)*KONE.*img.*img+conv2(s1,Ksigma,'same')-2.*img.*conv2(s2,Ksigma,'same'); % eq.(15) A = -DrcU.*dataForce; % 1st term in eq. (15) P = mu*(4*del2(phi)-K); % 3rd term in eq. (15), where 4*del2(u) computes the laplacian (d^2u/dx^2 + d^2u/dy^2) L = nu.*DrcU.*K; % 2nd term in eq. (15) phi = phi+timestep*(L+P+A); % eq.(15) end %-- compute f1 and f2 function [f1,f2] = localBinaryFit(img,u,KI,KONE,Ksigma,epsilon) Hu = 0.5*(1+(2/pi)*atan(u./epsilon)); % eq.(8) I = img.*Hu; c1 = conv2(Hu,Ksigma,'same'); c2 = conv2(I,Ksigma,'same'); % the numerator of eq.(14) for i = 1 f1 = c2./(c1); % compute f1 according to eq.(14) for i = 1 f2 = (KI-c2)./(KONE-c1); % compute f2 according to the formula in Section IV-A, % which is an equivalent expression of eq.(14) for i = 2. %-- Neumann boundary condition function g = NeumannBoundCond(f) [nrow,ncol] = size(f); g = f; g([1 nrow],[1 ncol]) = g([3 nrow-2],[3 ncol-2]); g([1 nrow],2:end-1) = g([3 nrow-2],2:end-1); g(2:end-1,[1 ncol]) = g(2:end-1,[3 ncol-2]); %-- compute curvature function k = curvature_central(u) [ux,uy] = gradient(u); normDu = sqrt(ux.^2+uy.^2+1e-10); % the norm of the gradient plus a small possitive number % to avoid division by zero in the following computation. Nx = ux./normDu; Ny = uy./normDu; nxx = gradient(Nx); [junk,nyy] = gradient(Ny); k = nxx+nyy; % compute divergence % Convergence Test function c = convergence(p_mask,n_mask,thresh,c) diff = p_mask - n_mask; n_diff = sum(abs(diff(:))); if n_diff < thresh c = c + 1; else c = 0; end
github
jacksky64/imageProcessing-master
creaseg_mouseMove.m
.m
imageProcessing-master/segmentation/creaseg/creaseg/creaseg/src/creaseg_mouseMove.m
9,921
utf_8
dd456413178c29ef801a415ebf0b4a12
% Copyright or © or Copr. CREATIS laboratory, Lyon, France. % % Contributor: Olivier Bernard, Associate Professor at the french % engineering university INSA (Institut National des Sciences Appliquees) % and a member of the CREATIS-LRMN laboratory (CNRS 5220, INSERM U630, % INSA, Claude Bernard Lyon 1 University) in France (Lyon). % % Date of creation: 8th of October 2009 % % E-mail of the author: [email protected] % % This software is a computer program whose purpose is to evaluate the % performance of different level-set based segmentation algorithms in the % context of image processing (and more particularly on biomedical % images). % % The software has been designed for two main purposes. % - firstly, CREASEG allows you to use six different level-set methods. % These methods have been chosen in order to work with a wide range of % level-sets. You can select for instance classical methods such as % Caselles or Chan & Vese level-set, or more recent approaches such as the % one developped by Lankton or Bernard. % - finally, the software allows you to compare the performance of the six % level-set methods on different images. The performance can be evaluated % either visually, or from measurements (either using the Dice coefficient % or the PSNR value) between a reference and the results of the % segmentation. % % The level-set segmentation platform is citationware. If you are % publishing any work, where this program has been used, or which used one % of the proposed level-set algorithms, please remember that it was % obtained free of charge. You must reference the papers shown below and % the name of the CREASEG software must be mentioned in the publication. % % CREASEG software % "T. Dietenbeck, M. Alessandrini, D. Friboulet, O. Bernard. CREASEG: a % free software for the evaluation of image segmentation algorithms based % on level-set. In IEEE International Conference On Image Processing. % Hong Kong, China, 2010." % % Bernard method % "O. Bernard, D. Friboulet, P. Thevenaz, M. Unser. Variational B-Spline % Level-Set: A Linear Filtering Approach for Fast Deformable Model % Evolution. In IEEE Transactions on Image Processing. volume 18, no. 06, % pp. 1179-1191, 2009." % % Caselles method % "V. Caselles, R. Kimmel, and G. Sapiro. Geodesic active contours. % International Journal of Computer Vision, volume 22, pp. 61-79, 1997." % % Chan & Vese method % "T. Chan and L. Vese. Active contours without edges. IEEE Transactions on % Image Processing. volume10, pp. 266-277, February 2001." % % Lankton method % "S. Lankton, A. Tannenbaum. Localizing Region-Based Active Contours. In % IEEE Transactions on Image Processing. volume 17, no. 11, pp. 2029-2039, % 2008." % % Li method % "C. Li, C.Y. Kao, J.C. Gore, Z. Ding. Minimization of Region-Scalable % Fitting Energy for Image Segmentation. In IEEE Transactions on Image % Processing. volume 17, no. 10, pp. 1940-1949, 2008." % % Shi method % "Yonggang Shi, William Clem Karl. A Real-Time Algorithm for the % Approximation of Level-Set-Based Curve Evolution. In IEEE Transactions % on Image Processing. volume 17, no. 05, pp. 645-656, 2008." % % This software is governed by the BSD license and % abiding by the rules of distribution of free software. % % As a counterpart to the access to the source code and rights to copy, % modify and redistribute granted by the license, users are provided only % with a limited warranty and the software's author, the holder of the % economic rights, and the successive licensors have only limited % liability. % % In this respect, the user's attention is drawn to the risks associated % with loading, using, modifying and/or developing or reproducing the % software by the user in light of its specific status of free software, % that may mean that it is complicated to manipulate, and that also % therefore means that it is reserved for developers and experienced % professionals having in-depth computer knowledge. Users are therefore % encouraged to load and test the software's suitability as regards their % requirements in conditions enabling the security of their systems and/or % data to be ensured and, more generally, to use and operate it in the % same conditions as regards security. % %------------------------------------------------------------------------ function creaseg_mouseMove(src,evt) current_object = hittest; fig = findobj(0,'tag','creaseg'); ud = get(fig,'userdata'); if ( ~isempty(ud) ) fd = get(ud.imageId,'userdata'); pos = floor(get(ud.gca,'CurrentPoint')); if ( isempty(ud.imageId) ) if ( strcmp(get(current_object,'Type'), 'image') && ( ... strcmp(get(current_object,'Tag'), 'mainImg') ) && ... (pos(1,1)>0) && pos(1,2)>0 ) set(ud.txtPositionIntensity,'string',sprintf('x:%02d y:%02d i:NaN',pos(1,1),pos(1,2)),'foregroundcolor',[1 1 1]); else set(ud.txtPositionIntensity,'string',''); end else if ( ~isempty(fd.data) ) if ( ~strcmp(get(current_object,'Tag'),'pan') && strcmp(get(current_object,'Tag'),'mainImg') && ... (pos(1,1)>0) && (pos(1,2)>0) && (pos(1,1)<=size(fd.data,2)) && ... (pos(1,2)<=size(fd.data,1)) ) %-- check whether the pan button is pressed or not if (get(ud.buttonAction(6),'background')~=[160/255 130/255 95/255]) %-- set mouse pointer to pointer if pointer mode is selected if (get(ud.buttonAction(3),'background')==[160/255 130/255 95/255]) set(fig,'pointer','arrow'); %-- set mouse pointer to crosshair if drawing mode is selected elseif (get(ud.buttonAction(1),'background')==[160/255 130/255 95/255]) set(fig,'pointer','crosshair'); %-- set mouse pointer to crosshair if drawing mode is selected elseif (get(ud.handleAlgoComparison(17),'background')==[160/255 130/255 95/255]) set(fig,'pointer','crosshair'); else set(fig,'pointer','arrow'); end drawnow; end set(ud.txtPositionIntensity,'string',sprintf('x:%02d y:%02d i:%03.1f',pos(1,1),pos(1,2),fd.data(pos(1,2),pos(1,1))),'foregroundcolor',[1 1 1]); else %-- set mouse pointer to watch set(fig,'pointer','arrow'); drawnow; set(ud.txtPositionIntensity,'string',''); end else if ( strcmp(get(current_object,'Type'), 'image') && ( ... strcmp(get(current_object,'Tag'), 'mainImg') ) && ... (pos(1,1)>0) && pos(1,2)>0 ) set(ud.txtPositionIntensity,'string',sprintf('x:%02d y:%02d i:NaN',pos(1,1),pos(1,2)),'foregroundcolor',[1 1 1]); else set(ud.txtPositionIntensity,'string',''); end end end end % % % %-- Checking if a Reference contour is being drawn and if a point is currently being modified % % % if ( strcmp(fd.method, 'Reference') && isfield(fd,'PtsRef') && ~isempty(fd.PtsRef) ) % % % % axes(get(ud.imageId,'parent')); % % % % % % ctr = fd.PtsRef; % % % % ctr is a 3xn matrix containing the x and y coordinates and a flag to % % % % know if the point is selected (position will be modified) or not % % % % % % m = find(fd.PtsRef(3,:) == 0,1); %-- Find the index of the first point whose flag is 0 (ie that is modified) % % % % % % if ~isempty(m) % % % %-- % % % pos = floor(get(ud.gca(1),'CurrentPoint')); % % % x = pos(1,1); y = pos(1,2); % % % % % % %-- Updating the point position (+ check bounds) % % % ctr(1,m) = min( max( y, 1), size(fd.data,1) ); % % % ctr(2,m) = min( max( x, 1), size(fd.data,2) ); % % % % % % method = (get(ud.handleAlgoComparison(19),'Value') - 1) * ud.Spline; % % % % % % %-- Deleting all the lines outside the function so that ud has not to be a parameter of the display function % % % delete(findobj(get(ud.imageId(1),'parent'),'type','line')); % % % show_contour(ctr, method, m); % % % end % % % end % % % % % % end % % % % % % % % % %----- Display Function -----% % % % function show_contour(ctr, method, m) % % % if ~isempty(ctr) % % % switch method % % % case 0 % % % hold on; % % % plot(ctr(2,:),ctr(1,:),'y--','Linewidth',3); % % % tmp = ctr(:,1); tmp(:,end+1) = ctr(:,end); % % % plot(tmp(2,:), tmp(1,:), 'y--', 'linewidth', 3); % % % plot(ctr(2,:), ctr(1,:), 'or', 'linewidth', 2); % % % hold off; % % % case 1 % % % spline = cscvn([[ctr(2,:) ctr(2,1)]; [ctr(1,:) ctr(1,1)]]); % % % hold on; fnplt(spline, 3, 'y--'); % % % plot(ctr(2,:), ctr(1,:), 'or', 'linewidth', 2); % % % hold off; % % % end % % % %-- Plot in green the point that is selected % % % hold on; plot(ctr(2,m),ctr(1,m),'og','Linewidth',2); hold off; % % % end % % %
github
jacksky64/imageProcessing-master
creaseg_cleanOverlays.m
.m
imageProcessing-master/segmentation/creaseg/creaseg/creaseg/src/creaseg_cleanOverlays.m
6,644
utf_8
239fbd07c65e3a4d1dba76563a072b6c
% Copyright or © or Copr. CREATIS laboratory, Lyon, France. % % Contributor: Olivier Bernard, Associate Professor at the french % engineering university INSA (Institut National des Sciences Appliquees) % and a member of the CREATIS-LRMN laboratory (CNRS 5220, INSERM U630, % INSA, Claude Bernard Lyon 1 University) in France (Lyon). % % Date of creation: 8th of October 2009 % % E-mail of the author: [email protected] % % This software is a computer program whose purpose is to evaluate the % performance of different level-set based segmentation algorithms in the % context of image processing (and more particularly on biomedical % images). % % The software has been designed for two main purposes. % - firstly, CREASEG allows you to use six different level-set methods. % These methods have been chosen in order to work with a wide range of % level-sets. You can select for instance classical methods such as % Caselles or Chan & Vese level-set, or more recent approaches such as the % one developped by Lankton or Bernard. % - finally, the software allows you to compare the performance of the six % level-set methods on different images. The performance can be evaluated % either visually, or from measurements (either using the Dice coefficient % or the PSNR value) between a reference and the results of the % segmentation. % % The level-set segmentation platform is citationware. If you are % publishing any work, where this program has been used, or which used one % of the proposed level-set algorithms, please remember that it was % obtained free of charge. You must reference the papers shown below and % the name of the CREASEG software must be mentioned in the publication. % % CREASEG software % "T. Dietenbeck, M. Alessandrini, D. Friboulet, O. Bernard. CREASEG: a % free software for the evaluation of image segmentation algorithms based % on level-set. In IEEE International Conference On Image Processing. % Hong Kong, China, 2010." % % Bernard method % "O. Bernard, D. Friboulet, P. Thevenaz, M. Unser. Variational B-Spline % Level-Set: A Linear Filtering Approach for Fast Deformable Model % Evolution. In IEEE Transactions on Image Processing. volume 18, no. 06, % pp. 1179-1191, 2009." % % Caselles method % "V. Caselles, R. Kimmel, and G. Sapiro. Geodesic active contours. % International Journal of Computer Vision, volume 22, pp. 61-79, 1997." % % Chan & Vese method % "T. Chan and L. Vese. Active contours without edges. IEEE Transactions on % Image Processing. volume10, pp. 266-277, February 2001." % % Lankton method % "S. Lankton, A. Tannenbaum. Localizing Region-Based Active Contours. In % IEEE Transactions on Image Processing. volume 17, no. 11, pp. 2029-2039, % 2008." % % Li method % "C. Li, C.Y. Kao, J.C. Gore, Z. Ding. Minimization of Region-Scalable % Fitting Energy for Image Segmentation. In IEEE Transactions on Image % Processing. volume 17, no. 10, pp. 1940-1949, 2008." % % Shi method % "Yonggang Shi, William Clem Karl. A Real-Time Algorithm for the % Approximation of Level-Set-Based Curve Evolution. In IEEE Transactions % on Image Processing. volume 17, no. 05, pp. 645-656, 2008." % % This software is governed by the BSD license and % abiding by the rules of distribution of free software. % % As a counterpart to the access to the source code and rights to copy, % modify and redistribute granted by the license, users are provided only % with a limited warranty and the software's author, the holder of the % economic rights, and the successive licensors have only limited % liability. % % In this respect, the user's attention is drawn to the risks associated % with loading, using, modifying and/or developing or reproducing the % software by the user in light of its specific status of free software, % that may mean that it is complicated to manipulate, and that also % therefore means that it is reserved for developers and experienced % professionals having in-depth computer knowledge. Users are therefore % encouraged to load and test the software's suitability as regards their % requirements in conditions enabling the security of their systems and/or % data to be ensured and, more generally, to use and operate it in the % same conditions as regards security. % %------------------------------------------------------------------------ %------------------------------------------------------------------------ % Description: This code implements the paper: "Variational B-Spline % Level-Set: A Linear Filtering Approach for Fast Deformable Model % Evolution." By Olivier Bernard. % % Coded by: Olivier Bernard (www.creatis.insa-lyon.fr/~bernard) %------------------------------------------------------------------------ %------------------------------------------------------------------ function creaseg_cleanOverlays(keepLS) %-- default value for parameter max_its is 100 if(~exist('keepLS','var')) keepLS = 0; end %-- get structures fig = findobj(0,'tag','creaseg'); ud = get(fig,'userdata'); fd = get(ud.imageId,'userdata'); %-- refresh flag in case fd.drawingManualFlag = 0; fd.drawingMultiManualFlag = 0; fd.drawingReferenceFlag = 0; %-- clean all if ( strcmp(fd.method,'Caselles') || strcmp(fd.method,'Chan & Vese') || ... strcmp(fd.method,'Chunming Li') || strcmp(fd.method,'Lankton') || ... strcmp(fd.method,'Bernard') || strcmp(fd.method,'Shi') || ... strcmp(fd.method,'Personal') || strcmp(fd.method,'Reference') || ... strcmp(fd.method,'Comparison') ) axes(get(ud.imageId,'parent')); delete(findobj(get(ud.imageId,'parent'),'type','line')); fd.method = []; end if ( size(fd.handleRect,2) > 0 ) for k=size(fd.handleRect,2):-1:1 delete(fd.handleRect{k}); fd.handleRect(k)=[]; end end if ( size(fd.handleElliRect,2) > 0 ) for k=size(fd.handleElliRect,2):-1:1 delete(fd.handleElliRect{k}(2)); fd.handleElliRect(k)=[]; end end if ( size(fd.handleManual,2) > 0 ) for k=size(fd.handleManual,2):-1:1 for l=1:size(fd.handleManual{k},1) if ( fd.handleManual{k}(l) ~= 0 ) delete(fd.handleManual{k}(l)); end end fd.handleManual(k)=[]; fd.points = []; end end if ( keepLS == 0 ) fd.levelset = zeros(size(fd.data)); end set(ud.imageId,'userdata',fd); %-- end clean all
github
jacksky64/imageProcessing-master
creaseg_drawMultiManualContours.m
.m
imageProcessing-master/segmentation/creaseg/creaseg/creaseg/src/creaseg_drawMultiManualContours.m
8,867
utf_8
6efb32e8df6bfe08fa1b3acd6f26d2eb
% Copyright or © or Copr. CREATIS laboratory, Lyon, France. % % Contributor: Olivier Bernard, Associate Professor at the french % engineering university INSA (Institut National des Sciences Appliquees) % and a member of the CREATIS-LRMN laboratory (CNRS 5220, INSERM U630, % INSA, Claude Bernard Lyon 1 University) in France (Lyon). % % Date of creation: 8th of October 2009 % % E-mail of the author: [email protected] % % This software is a computer program whose purpose is to evaluate the % performance of different level-set based segmentation algorithms in the % context of image processing (and more particularly on biomedical % images). % % The software has been designed for two main purposes. % - firstly, CREASEG allows you to use six different level-set methods. % These methods have been chosen in order to work with a wide range of % level-sets. You can select for instance classical methods such as % Caselles or Chan & Vese level-set, or more recent approaches such as the % one developped by Lankton or Bernard. % - finally, the software allows you to compare the performance of the six % level-set methods on different images. The performance can be evaluated % either visually, or from measurements (either using the Dice coefficient % or the PSNR value) between a reference and the results of the % segmentation. % % The level-set segmentation platform is citationware. If you are % publishing any work, where this program has been used, or which used one % of the proposed level-set algorithms, please remember that it was % obtained free of charge. You must reference the papers shown below and % the name of the CREASEG software must be mentioned in the publication. % % CREASEG software % "T. Dietenbeck, M. Alessandrini, D. Friboulet, O. Bernard. CREASEG: a % free software for the evaluation of image segmentation algorithms based % on level-set. In IEEE International Conference On Image Processing. % Hong Kong, China, 2010." % % Bernard method % "O. Bernard, D. Friboulet, P. Thevenaz, M. Unser. Variational B-Spline % Level-Set: A Linear Filtering Approach for Fast Deformable Model % Evolution. In IEEE Transactions on Image Processing. volume 18, no. 06, % pp. 1179-1191, 2009." % % Caselles method % "V. Caselles, R. Kimmel, and G. Sapiro. Geodesic active contours. % International Journal of Computer Vision, volume 22, pp. 61-79, 1997." % % Chan & Vese method % "T. Chan and L. Vese. Active contours without edges. IEEE Transactions on % Image Processing. volume10, pp. 266-277, February 2001." % % Lankton method % "S. Lankton, A. Tannenbaum. Localizing Region-Based Active Contours. In % IEEE Transactions on Image Processing. volume 17, no. 11, pp. 2029-2039, % 2008." % % Li method % "C. Li, C.Y. Kao, J.C. Gore, Z. Ding. Minimization of Region-Scalable % Fitting Energy for Image Segmentation. In IEEE Transactions on Image % Processing. volume 17, no. 10, pp. 1940-1949, 2008." % % Shi method % "Yonggang Shi, William Clem Karl. A Real-Time Algorithm for the % Approximation of Level-Set-Based Curve Evolution. In IEEE Transactions % on Image Processing. volume 17, no. 05, pp. 645-656, 2008." % % This software is governed by the BSD license and % abiding by the rules of distribution of free software. % % As a counterpart to the access to the source code and rights to copy, % modify and redistribute granted by the license, users are provided only % with a limited warranty and the software's author, the holder of the % economic rights, and the successive licensors have only limited % liability. % % In this respect, the user's attention is drawn to the risks associated % with loading, using, modifying and/or developing or reproducing the % software by the user in light of its specific status of free software, % that may mean that it is complicated to manipulate, and that also % therefore means that it is reserved for developers and experienced % professionals having in-depth computer knowledge. Users are therefore % encouraged to load and test the software's suitability as regards their % requirements in conditions enabling the security of their systems and/or % data to be ensured and, more generally, to use and operate it in the % same conditions as regards security. % %------------------------------------------------------------------------ function creaseg_drawMultiManualContours(src,evt) %-- get structures fig = findobj(0,'tag','creaseg'); ud = get(fig,'userdata'); fd = get(ud.imageId,'userdata'); pos = floor(get(ud.gca(1),'CurrentPoint')); if ~( pos(1,1) < size(fd.data,2) && pos(1,1) > 1 && pos(1,2) < size(fd.data,1) && pos(1,2) >1 ) return; %Clic outside the image => do nothing end if ( strcmp(get(ud.gcf,'SelectionType'),'normal') ) %-- Set drawingMultiManualFlag flag to 1 fd.drawingMultiManualFlag = 1; %-- disable run and pointer buttons set(ud.buttonAction(2),'enable','off'); set(ud.buttonAction(3),'enable','off'); %-- delete any overlay lines if ( size(fd.handleManual,2)>0 ) for k=1:size(fd.handleManual{end},1) if ( fd.handleManual{end}(k) ~= 0 ) delete(fd.handleManual{end}(k)); end end else fd.handleManual{1} = 0; end %-- Get point coordinates pt = get(ud.gca,'CurrentPoint'); pt = pt(1,1:2); if (isempty(fd.points)) fd.points = [pt(1),pt(2)]; hold on; h = plot(pt(1), pt(2), 'oy', 'linewidth', 2); fd.handleManual{end} = h; else fd.points(end+1,:) = [pt(1),pt(2)]; color = ud.colorSpec(get(ud.handleContourColor,'userdata')); if length(fd.points(:,1)) < 3 hold on; h1 = plot(fd.points(:,1),fd.points(:,2),'--','color',color{1},'Linewidth',2); tmp = fd.points(1,:); tmp(end+1,:) = fd.points(end,:); h2 = plot(tmp(:,1), tmp(:,2), 'y--', 'linewidth', 2); else [xs, ys] = creaseg_spline(fd.points(:,1)',fd.points(:,2)'); fin = find((xs == fd.points(end,1)) & (ys == fd.points(end,2)) ); deb = find((xs == fd.points(1,1)) & (ys == fd.points(1,2)) ); xs = xs([deb:end, 1:deb]); ys = ys([deb:end, 1:deb]); if deb > fin idx = length(xs) + fin - deb; else idx = fin - deb; end clear deb fin; hold on; h1 = plot(xs(1:idx),ys(1:idx),'--','color',color{1},'Linewidth',2); hold on; h2 = plot(xs(idx:end),ys(idx:end),'y--','Linewidth',2); end h3 = plot(fd.points(:,1), fd.points(:,2), 'oy', 'linewidth', 2); hold off; fd.handleManual{end} = [h1;h2;h3]; end else %-- create final contour %-- Set drawingMultiManualFlag flag to 1 fd.drawingMultiManualFlag = 1; %-- enable run and pointer buttons set(ud.buttonAction(2),'enable','on'); set(ud.buttonAction(3),'enable','on'); set(ud.buttonAction(6),'enable','on'); %-- display final contour if ( size(fd.points,1)>2 ) %-- delete any overlay lines if ( size(fd.handleManual,2)>0 ) for k=1:size(fd.handleManual{end},1) delete(fd.handleManual{end}(k)); end end %-- color = ud.colorSpec(get(ud.handleContourColor,'userdata')); if length(fd.points(:,1)) < 3 tmp = fd.points; tmp(end+1,:) = tmp(1,:); hold on; h = plot(tmp(:,1),tmp(:,2),'--','color',color{1},'Linewidth',2); else [xs, ys] = creaseg_spline(fd.points(:,1)',fd.points(:,2)'); hold on; h = plot(xs,ys,'--','color',color{1},'Linewidth',2); end fd.handleManual{end} = h; %-- create manual mask X = get(fd.handleManual{end},'X'); Y = get(fd.handleManual{end},'Y'); fd.levelset = xor(roipoly(fd.data,X,Y),fd.levelset); %-- save initialization info ud.LastPlot = 'levelset'; fd.method = 'Initial region'; %-- prepare next contour fd.handleManual{end+1} = 0; end fd.points = []; end %-- save structure set(ud.imageId,'userdata',fd); set(ud.gcf,'userdata',ud);
github
jacksky64/imageProcessing-master
creaseg_show.m
.m
imageProcessing-master/segmentation/creaseg/creaseg/creaseg/src/creaseg_show.m
4,785
utf_8
4342d9bf2b06bf50633bc90d41206b4b
% Copyright or © or Copr. CREATIS laboratory, Lyon, France. % % Contributor: Olivier Bernard, Associate Professor at the french % engineering university INSA (Institut National des Sciences Appliquees) % and a member of the CREATIS-LRMN laboratory (CNRS 5220, INSERM U630, % INSA, Claude Bernard Lyon 1 University) in France (Lyon). % % Date of creation: 8th of October 2009 % % E-mail of the author: [email protected] % % This software is a computer program whose purpose is to evaluate the % performance of different level-set based segmentation algorithms in the % context of image processing (and more particularly on biomedical % images). % % The software has been designed for two main purposes. % - firstly, CREASEG allows you to use six different level-set methods. % These methods have been chosen in order to work with a wide range of % level-sets. You can select for instance classical methods such as % Caselles or Chan & Vese level-set, or more recent approaches such as the % one developped by Lankton or Bernard. % - finally, the software allows you to compare the performance of the six % level-set methods on different images. The performance can be evaluated % either visually, or from measurements (either using the Dice coefficient % or the PSNR value) between a reference and the results of the % segmentation. % % The level-set segmentation platform is citationware. If you are % publishing any work, where this program has been used, or which used one % of the proposed level-set algorithms, please remember that it was % obtained free of charge. You must reference the papers shown below and % the name of the CREASEG software must be mentioned in the publication. % % CREASEG software % "T. Dietenbeck, M. Alessandrini, D. Friboulet, O. Bernard. CREASEG: a % free software for the evaluation of image segmentation algorithms based % on level-set. In IEEE International Conference On Image Processing. % Hong Kong, China, 2010." % % Bernard method % "O. Bernard, D. Friboulet, P. Thevenaz, M. Unser. Variational B-Spline % Level-Set: A Linear Filtering Approach for Fast Deformable Model % Evolution. In IEEE Transactions on Image Processing. volume 18, no. 06, % pp. 1179-1191, 2009." % % Caselles method % "V. Caselles, R. Kimmel, and G. Sapiro. Geodesic active contours. % International Journal of Computer Vision, volume 22, pp. 61-79, 1997." % % Chan & Vese method % "T. Chan and L. Vese. Active contours without edges. IEEE Transactions on % Image Processing. volume10, pp. 266-277, February 2001." % % Lankton method % "S. Lankton, A. Tannenbaum. Localizing Region-Based Active Contours. In % IEEE Transactions on Image Processing. volume 17, no. 11, pp. 2029-2039, % 2008." % % Li method % "C. Li, C.Y. Kao, J.C. Gore, Z. Ding. Minimization of Region-Scalable % Fitting Energy for Image Segmentation. In IEEE Transactions on Image % Processing. volume 17, no. 10, pp. 1940-1949, 2008." % % Shi method % "Yonggang Shi, William Clem Karl. A Real-Time Algorithm for the % Approximation of Level-Set-Based Curve Evolution. In IEEE Transactions % on Image Processing. volume 17, no. 05, pp. 645-656, 2008." % % This software is governed by the BSD license and % abiding by the rules of distribution of free software. % % As a counterpart to the access to the source code and rights to copy, % modify and redistribute granted by the license, users are provided only % with a limited warranty and the software's author, the holder of the % economic rights, and the successive licensors have only limited % liability. % % In this respect, the user's attention is drawn to the risks associated % with loading, using, modifying and/or developing or reproducing the % software by the user in light of its specific status of free software, % that may mean that it is complicated to manipulate, and that also % therefore means that it is reserved for developers and experienced % professionals having in-depth computer knowledge. Users are therefore % encouraged to load and test the software's suitability as regards their % requirements in conditions enabling the security of their systems and/or % data to be ensured and, more generally, to use and operate it in the % same conditions as regards security. % %------------------------------------------------------------------------ function creaseg_show() %-- get structures fig = findobj(0,'tag','creaseg'); ud = get(fig,'userdata'); fd = get(ud.imageId,'userdata'); %-- parameters img = fd.visu; imageId = ud.imageId; s = size(img); %-- show image figure(fig); set(imageId,'cdata',double(img),'xdata',1:s(2),'ydata',1:s(1)); set(get(imageId,'parent'),'xlim',[1 s(2)],'ylim',[1 s(1)]);
github
jacksky64/imageProcessing-master
creaseg_loadimage.m
.m
imageProcessing-master/segmentation/creaseg/creaseg/creaseg/src/creaseg_loadimage.m
8,808
utf_8
d10078f1fec9727042491dd7e1cc550e
% Copyright or © or Copr. CREATIS laboratory, Lyon, France. % % Contributor: Olivier Bernard, Associate Professor at the french % engineering university INSA (Institut National des Sciences Appliquees) % and a member of the CREATIS-LRMN laboratory (CNRS 5220, INSERM U630, % INSA, Claude Bernard Lyon 1 University) in France (Lyon). % % Date of creation: 8th of October 2009 % % E-mail of the author: [email protected] % % This software is a computer program whose purpose is to evaluate the % performance of different level-set based segmentation algorithms in the % context of image processing (and more particularly on biomedical % images). % % The software has been designed for two main purposes. % - firstly, CREASEG allows you to use six different level-set methods. % These methods have been chosen in order to work with a wide range of % level-sets. You can select for instance classical methods such as % Caselles or Chan & Vese level-set, or more recent approaches such as the % one developped by Lankton or Bernard. % - finally, the software allows you to compare the performance of the six % level-set methods on different images. The performance can be evaluated % either visually, or from measurements (either using the Dice coefficient % or the PSNR value) between a reference and the results of the % segmentation. % % The level-set segmentation platform is citationware. If you are % publishing any work, where this program has been used, or which used one % of the proposed level-set algorithms, please remember that it was % obtained free of charge. You must reference the papers shown below and % the name of the CREASEG software must be mentioned in the publication. % % CREASEG software % "T. Dietenbeck, M. Alessandrini, D. Friboulet, O. Bernard. CREASEG: a % free software for the evaluation of image segmentation algorithms based % on level-set. In IEEE International Conference On Image Processing. % Hong Kong, China, 2010." % % Bernard method % "O. Bernard, D. Friboulet, P. Thevenaz, M. Unser. Variational B-Spline % Level-Set: A Linear Filtering Approach for Fast Deformable Model % Evolution. In IEEE Transactions on Image Processing. volume 18, no. 06, % pp. 1179-1191, 2009." % % Caselles method % "V. Caselles, R. Kimmel, and G. Sapiro. Geodesic active contours. % International Journal of Computer Vision, volume 22, pp. 61-79, 1997." % % Chan & Vese method % "T. Chan and L. Vese. Active contours without edges. IEEE Transactions on % Image Processing. volume10, pp. 266-277, February 2001." % % Lankton method % "S. Lankton, A. Tannenbaum. Localizing Region-Based Active Contours. In % IEEE Transactions on Image Processing. volume 17, no. 11, pp. 2029-2039, % 2008." % % Li method % "C. Li, C.Y. Kao, J.C. Gore, Z. Ding. Minimization of Region-Scalable % Fitting Energy for Image Segmentation. In IEEE Transactions on Image % Processing. volume 17, no. 10, pp. 1940-1949, 2008." % % Shi method % "Yonggang Shi, William Clem Karl. A Real-Time Algorithm for the % Approximation of Level-Set-Based Curve Evolution. In IEEE Transactions % on Image Processing. volume 17, no. 05, pp. 645-656, 2008." % % This software is governed by the BSD license and % abiding by the rules of distribution of free software. % % As a counterpart to the access to the source code and rights to copy, % modify and redistribute granted by the license, users are provided only % with a limited warranty and the software's author, the holder of the % economic rights, and the successive licensors have only limited % liability. % % In this respect, the user's attention is drawn to the risks associated % with loading, using, modifying and/or developing or reproducing the % software by the user in light of its specific status of free software, % that may mean that it is complicated to manipulate, and that also % therefore means that it is reserved for developers and experienced % professionals having in-depth computer knowledge. Users are therefore % encouraged to load and test the software's suitability as regards their % requirements in conditions enabling the security of their systems and/or % data to be ensured and, more generally, to use and operate it in the % same conditions as regards security. % %------------------------------------------------------------------------ function creaseg_loadimage(varargin) if nargin == 1 fig = varargin{1}; else fig = gcbf; end ud = get(fig,'userdata'); fd = get(ud.imageId,'userdata'); %-- [fname,pname] = uigetfile('*.png;*.jpg;*.pgm;*.bmp;*.gif;*.tif;*.dcm;','Pick a file','multiselect','off','data/Image'); input_file = fullfile(pname,fname); if ~exist(input_file,'file') warning(['File: ' input_file ' does not exist']); return; else [pathstr, name, ext] = fileparts(input_file); end try if (ext=='.dcm') img = dicomread(input_file); info = dicominfo(input_file); else img = imread(input_file); info = imfinfo(input_file); end catch warning(['Could not load: ' input_file]); return; end img = im2graydouble(img); fd.data = img; fd.visu = img; fd.tagImage = 1; fd.dimX = size(img,2); fd.dimY = size(img,1); fd.info = info; if ( isfield(fd.info,'Width') ) set(ud.txtInfo1,'string',sprintf('width:%d pixels',fd.info.Width), 'color', [1 1 0]); end if ( isfield(fd.info,'Height') ) set(ud.txtInfo2,'string',sprintf('height:%d pixels',fd.info.Height)); end if ( isfield(fd.info,'BitDepth') ) set(ud.txtInfo3,'string',sprintf('bit depth:%d',fd.info.BitDepth)); end if ( isfield(fd.info,'XResolution') && (~isempty(fd.info.XResolution)) ) if ( isfield(fd.info,'ResolutionUnit') ) if ( strcmp(fd.info.ResolutionUnit,'meter') ) set(ud.txtInfo4,'string',sprintf('XResolution:%0.3f mm',fd.info.XResolution/1000)); elseif ( strcmp(fd.info.ResolutionUnit,'millimeter') ) set(ud.txtInfo4,'string',sprintf('XResolution:%0.3f mm',fd.info.XResolution)); else set(ud.txtInfo4,'string',sprintf('XResolution:%0.3f',fd.info.XResolution)); end else set(ud.txtInfo4,'string',sprintf('XResolution:%f',fd.info.XResolution)); end else set(ud.txtInfo4,'string',''); end if ( isfield(fd.info,'YResolution') && (~isempty(fd.info.YResolution)) ) if ( isfield(fd.info,'ResolutionUnit') ) if ( strcmp(fd.info.ResolutionUnit,'meter') ) set(ud.txtInfo5,'string',sprintf('YResolution:%0.3f mm',fd.info.YResolution/1000)); elseif ( strcmp(fd.info.ResolutionUnit,'millimeter') ) set(ud.txtInfo5,'string',sprintf('YResolution:%0.3f mm',fd.info.YResolution)); else set(ud.txtInfo5,'string',sprintf('YResolution:%0.3f',fd.info.YResolution)); end else set(ud.txtInfo5,'string',sprintf('YResolution:%f',fd.info.XResolution)); end else set(ud.txtInfo5,'string',''); end %-- reset drawing buttons selection for k=3:size(ud.handleInit,1) set(ud.handleInit(k),'BackgroundColor',[240/255 173/255 105/255]); end %-- clean overlays before udating fd structure creaseg_cleanOverlays(); %-- fd.levelset = zeros(size(fd.data)); fd.reference = zeros(size(fd.data)); fd.method = ''; set(ud.buttonAction,'background',[240/255 173/255 105/255]); set(ud.buttonAction(7),'background',[160/255 130/255 95/255]); for k=1:size(ud.handleAlgoConfig,1) set(ud.handleAlgoConfig(k),'Visible','off'); end set(ud.handleAlgoConfig(end),'Visible','on'); set(ud.buttonAction(1),'background',[160/255 130/255 95/255]); set(ud.handleAlgoComparison(16),'Enable','on'); set(ud.handleAlgoComparison(17),'Enable','on'); set(ud.handleAlgoComparison(24),'Enable','off'); %-- ATTACH FD AND UD STRUCTURE TO IMAGEID AND FIG HANDLES set(ud.imageId,'userdata',fd); %-- creaseg_show(); %------------------------------------------------------ %------------------------------------------------------ %-- Converts image to one channel (grayscale) double function img = im2graydouble(img) [dimy, dimx, c] = size(img); if(isfloat(img)) % image is a double if(c==3) img = rgb2gray(uint8(img)); end else % image is a int if(c==3) img = rgb2gray(img); end img = double(img); end
github
jacksky64/imageProcessing-master
creaseg_chanvese.m
.m
imageProcessing-master/segmentation/creaseg/creaseg/creaseg/src/creaseg_chanvese.m
12,585
utf_8
96f30e3263b583f69c472864aa955ad6
% Copyright or © or Copr. CREATIS laboratory, Lyon, France. % % Contributor: Olivier Bernard, Associate Professor at the french % engineering university INSA (Institut National des Sciences Appliquees) % and a member of the CREATIS-LRMN laboratory (CNRS 5220, INSERM U630, % INSA, Claude Bernard Lyon 1 University) in France (Lyon). % % Date of creation: 8th of October 2009 % % E-mail of the author: [email protected] % % This software is a computer program whose purpose is to evaluate the % performance of different level-set based segmentation algorithms in the % context of image processing (and more particularly on biomedical % images). % % The software has been designed for two main purposes. % - firstly, CREASEG allows you to use six different level-set methods. % These methods have been chosen in order to work with a wide range of % level-sets. You can select for instance classical methods such as % Caselles or Chan & Vese level-set, or more recent approaches such as the % one developped by Lankton or Bernard. % - finally, the software allows you to compare the performance of the six % level-set methods on different images. The performance can be evaluated % either visually, or from measurements (either using the Dice coefficient % or the PSNR value) between a reference and the results of the % segmentation. % % The level-set segmentation platform is citationware. If you are % publishing any work, where this program has been used, or which used one % of the proposed level-set algorithms, please remember that it was % obtained free of charge. You must reference the papers shown below and % the name of the CREASEG software must be mentioned in the publication. % % CREASEG software % "T. Dietenbeck, M. Alessandrini, D. Friboulet, O. Bernard. CREASEG: a % free software for the evaluation of image segmentation algorithms based % on level-set. In IEEE International Conference On Image Processing. % Hong Kong, China, 2010." % % Bernard method % "O. Bernard, D. Friboulet, P. Thevenaz, M. Unser. Variational B-Spline % Level-Set: A Linear Filtering Approach for Fast Deformable Model % Evolution. In IEEE Transactions on Image Processing. volume 18, no. 06, % pp. 1179-1191, 2009." % % Caselles method % "V. Caselles, R. Kimmel, and G. Sapiro. Geodesic active contours. % International Journal of Computer Vision, volume 22, pp. 61-79, 1997." % % Chan & Vese method % "T. Chan and L. Vese. Active contours without edges. IEEE Transactions on % Image Processing. volume10, pp. 266-277, February 2001." % % Lankton method % "S. Lankton, A. Tannenbaum. Localizing Region-Based Active Contours. In % IEEE Transactions on Image Processing. volume 17, no. 11, pp. 2029-2039, % 2008." % % Li method % "C. Li, C.Y. Kao, J.C. Gore, Z. Ding. Minimization of Region-Scalable % Fitting Energy for Image Segmentation. In IEEE Transactions on Image % Processing. volume 17, no. 10, pp. 1940-1949, 2008." % % Shi method % "Yonggang Shi, William Clem Karl. A Real-Time Algorithm for the % Approximation of Level-Set-Based Curve Evolution. In IEEE Transactions % on Image Processing. volume 17, no. 05, pp. 645-656, 2008." % % This software is governed by the BSD license and % abiding by the rules of distribution of free software. % % As a counterpart to the access to the source code and rights to copy, % modify and redistribute granted by the license, users are provided only % with a limited warranty and the software's author, the holder of the % economic rights, and the successive licensors have only limited % liability. % % In this respect, the user's attention is drawn to the risks associated % with loading, using, modifying and/or developing or reproducing the % software by the user in light of its specific status of free software, % that may mean that it is complicated to manipulate, and that also % therefore means that it is reserved for developers and experienced % professionals having in-depth computer knowledge. Users are therefore % encouraged to load and test the software's suitability as regards their % requirements in conditions enabling the security of their systems and/or % data to be ensured and, more generally, to use and operate it in the % same conditions as regards security. % %------------------------------------------------------------------------ %------------------------------------------------------------------------ % Region Based Active Contour Segmentation % % seg = region_seg(I,init_mask,max_its,alpha,display) % % Inputs: I 2D image % init_mask Initialization (1 = foreground, 0 = bg) % max_its Number of iterations to run segmentation for % alpha (optional) Weight of smoothing term % higer = smoother. default = 0.2 % display (optional) displays intermediate outputs % default = true % % Outputs: seg Final segmentation mask (1=fg, 0=bg) % % Description: This code implements the paper: "Active Contours Without % Edges" By Chan Vese. This is a nice way to segment images whose % foregrounds and backgrounds are statistically different and homogeneous. % % Example: % img = imread('tire.tif'); % m = zeros(size(img)); % m(33:33+117,44:44+128) = 1; % seg = region_seg(img,m,500); % % Coded by: Shawn Lankton (www.shawnlankton.com) %------------------------------------------------------------------------ function [seg,phi,its] = creaseg_chanvese(I,init_mask,max_its,alpha,thresh,color,display) %-- default value for parameter alpha is .1 if(~exist('alpha','var')) alpha = .2; end %-- default value for parameter thresh is 0 if(~exist('thresh','var')) thresh = 0; end %-- default value for parameter color is 'r' if(~exist('color','var')) color = 'r'; end %-- default behavior is to display intermediate outputs if(~exist('display','var')) display = true; end %-- ensures image is 2D double matrix I = im2graydouble(I); % init_mask = init_mask<=0; %-- Create a signed distance map (SDF) from mask phi = mask2phi(init_mask); %-- fig = findobj(0,'tag','creaseg'); ud = get(fig,'userdata'); %--main loop its = 0; stop = 0; prev_mask = init_mask; c = 0; while ((its < max_its) && ~stop) idx = find(phi <= 1.2 & phi >= -1.2); % get the curve's narrow band if ~isempty(idx) %-- intermediate output if (display>0) if ( mod(its,50)==0 ) set(ud.txtInfo1,'string',sprintf('iteration: %d',its),'color',[1 1 0]); showCurveAndPhi(phi,ud,color); drawnow; end else if ( mod(its,10)==0 ) set(ud.txtInfo1,'string',sprintf('iteration: %d',its),'color',[1 1 0]); drawnow; end end %-- find interior and exterior mean upts = find(phi<=0); % interior points vpts = find(phi>0); % exterior points u = sum(I(upts))/(length(upts)+eps); % interior mean v = sum(I(vpts))/(length(vpts)+eps); % exterior mean F = (I(idx)-u).^2-(I(idx)-v).^2; % force from image information curvature = get_curvature(phi,idx); % force from curvature penalty dphidt = F./max(abs(F)) + alpha*curvature; % gradient descent to minimize energy %-- maintain the CFL condition dt = .45/(max(abs(dphidt))+eps); %-- evolve the curve phi(idx) = phi(idx) + dt.*dphidt; %-- Keep SDF smooth phi = sussman(phi, .5); new_mask = phi<=0; c = convergence(prev_mask,new_mask,thresh,c); if c <= 5 its = its + 1; prev_mask = new_mask; else stop = 1; end else break; end end %-- final output showCurveAndPhi(phi,ud,color); %-- make mask from SDF seg = phi<=0; %-- Get mask from levelset %--------------------------------------------------------------------- %--------------------------------------------------------------------- %-- AUXILIARY FUNCTIONS ---------------------------------------------- %--------------------------------------------------------------------- %--------------------------------------------------------------------- %-- Displays the image with curve superimposed function showCurveAndPhi(phi,ud,cl) axes(get(ud.imageId,'parent')); delete(findobj(get(ud.imageId,'parent'),'type','line')); hold on; [c,h] = contour(phi,[0 0],cl{1},'Linewidth',3); hold off; delete(h); test = isequal(size(c,2),0); while (test==false) s = c(2,1); if ( s == (size(c,2)-1) ) t = c; hold on; plot(t(1,2:end)',t(2,2:end)',cl{1},'Linewidth',3); test = true; else t = c(:,2:s+1); hold on; plot(t(1,1:end)',t(2,1:end)',cl{1},'Linewidth',3); c = c(:,s+2:end); end end %-- converts a mask to a SDF function phi = mask2phi(init_a) phi=bwdist(init_a)-bwdist(1-init_a)+im2double(init_a)-.5; %-- compute curvature along SDF function curvature = get_curvature(phi,idx) [dimy, dimx] = size(phi); [y x] = ind2sub([dimy,dimx],idx); % get subscripts %-- get subscripts of neighbors ym1 = y-1; xm1 = x-1; yp1 = y+1; xp1 = x+1; %-- bounds checking ym1(ym1<1) = 1; xm1(xm1<1) = 1; yp1(yp1>dimy)=dimy; xp1(xp1>dimx) = dimx; %-- get indexes for 8 neighbors idup = sub2ind(size(phi),yp1,x); iddn = sub2ind(size(phi),ym1,x); idlt = sub2ind(size(phi),y,xm1); idrt = sub2ind(size(phi),y,xp1); idul = sub2ind(size(phi),yp1,xm1); idur = sub2ind(size(phi),yp1,xp1); iddl = sub2ind(size(phi),ym1,xm1); iddr = sub2ind(size(phi),ym1,xp1); %-- get central derivatives of SDF at x,y phi_x = -phi(idlt)+phi(idrt); phi_y = -phi(iddn)+phi(idup); phi_xx = phi(idlt)-2*phi(idx)+phi(idrt); phi_yy = phi(iddn)-2*phi(idx)+phi(idup); phi_xy = -0.25*phi(iddl)-0.25*phi(idur)... +0.25*phi(iddr)+0.25*phi(idul); phi_x2 = phi_x.^2; phi_y2 = phi_y.^2; %-- compute curvature (Kappa) curvature = ((phi_x2.*phi_yy + phi_y2.*phi_xx - 2*phi_x.*phi_y.*phi_xy)./... (phi_x2 + phi_y2 +eps).^(3/2)).*(phi_x2 + phi_y2).^(1/2); %-- Converts image to one channel (grayscale) double function img = im2graydouble(img) [dimy, dimx, c] = size(img); if(isfloat(img)) % image is a double if(c==3) img = rgb2gray(uint8(img)); end else % image is a int if(c==3) img = rgb2gray(img); end img = double(img); end %-- level set re-initialization by the sussman method function D = sussman(D, dt) % forward/backward differences a = D - shiftR(D); % backward b = shiftL(D) - D; % forward c = D - shiftD(D); % backward d = shiftU(D) - D; % forward a_p = a; a_n = a; % a+ and a- b_p = b; b_n = b; c_p = c; c_n = c; d_p = d; d_n = d; a_p(a < 0) = 0; a_n(a > 0) = 0; b_p(b < 0) = 0; b_n(b > 0) = 0; c_p(c < 0) = 0; c_n(c > 0) = 0; d_p(d < 0) = 0; d_n(d > 0) = 0; dD = zeros(size(D)); D_neg_ind = find(D < 0); D_pos_ind = find(D > 0); dD(D_pos_ind) = sqrt(max(a_p(D_pos_ind).^2, b_n(D_pos_ind).^2) ... + max(c_p(D_pos_ind).^2, d_n(D_pos_ind).^2)) - 1; dD(D_neg_ind) = sqrt(max(a_n(D_neg_ind).^2, b_p(D_neg_ind).^2) ... + max(c_n(D_neg_ind).^2, d_p(D_neg_ind).^2)) - 1; D = D - dt .* sussman_sign(D) .* dD; %-- whole matrix derivatives function shift = shiftD(M) shift = shiftR(M')'; function shift = shiftL(M) shift = [ M(:,2:size(M,2)) M(:,size(M,2)) ]; function shift = shiftR(M) shift = [ M(:,1) M(:,1:size(M,2)-1) ]; function shift = shiftU(M) shift = shiftL(M')'; function S = sussman_sign(D) S = D ./ sqrt(D.^2 + 1); % Convergence Test function c = convergence(p_mask,n_mask,thresh,c) diff = p_mask - n_mask; n_diff = sum(abs(diff(:))); if n_diff < thresh c = c + 1; else c = 0; end
github
jacksky64/imageProcessing-master
creaseg_bernard.m
.m
imageProcessing-master/segmentation/creaseg/creaseg/creaseg/src/creaseg_bernard.m
21,003
utf_8
c1f942411317c2e73100a8dde1950761
% Copyright or © or Copr. CREATIS laboratory, Lyon, France. % % Contributor: Olivier Bernard, Associate Professor at the french % engineering university INSA (Institut National des Sciences Appliquees) % and a member of the CREATIS-LRMN laboratory (CNRS 5220, INSERM U630, % INSA, Claude Bernard Lyon 1 University) in France (Lyon). % % Date of creation: 8th of October 2009 % % E-mail of the author: [email protected] % % This software is a computer program whose purpose is to evaluate the % performance of different level-set based segmentation algorithms in the % context of image processing (and more particularly on biomedical % images). % % The software has been designed for two main purposes. % - firstly, CREASEG allows you to use six different level-set methods. % These methods have been chosen in order to work with a wide range of % level-sets. You can select for instance classical methods such as % Caselles or Chan & Vese level-set, or more recent approaches such as the % one developped by Lankton or Bernard. % - finally, the software allows you to compare the performance of the six % level-set methods on different images. The performance can be evaluated % either visually, or from measurements (either using the Dice coefficient % or the PSNR value) between a reference and the results of the % segmentation. % % The level-set segmentation platform is citationware. If you are % publishing any work, where this program has been used, or which used one % of the proposed level-set algorithms, please remember that it was % obtained free of charge. You must reference the papers shown below and % the name of the CREASEG software must be mentioned in the publication. % % CREASEG software % "T. Dietenbeck, M. Alessandrini, D. Friboulet, O. Bernard. CREASEG: a % free software for the evaluation of image segmentation algorithms based % on level-set. In IEEE International Conference On Image Processing. % Hong Kong, China, 2010." % % Bernard method % "O. Bernard, D. Friboulet, P. Thevenaz, M. Unser. Variational B-Spline % Level-Set: A Linear Filtering Approach for Fast Deformable Model % Evolution. In IEEE Transactions on Image Processing. volume 18, no. 06, % pp. 1179-1191, 2009." % % Caselles method % "V. Caselles, R. Kimmel, and G. Sapiro. Geodesic active contours. % International Journal of Computer Vision, volume 22, pp. 61-79, 1997." % % Chan & Vese method % "T. Chan and L. Vese. Active contours without edges. IEEE Transactions on % Image Processing. volume10, pp. 266-277, February 2001." % % Lankton method % "S. Lankton, A. Tannenbaum. Localizing Region-Based Active Contours. In % IEEE Transactions on Image Processing. volume 17, no. 11, pp. 2029-2039, % 2008." % % Li method % "C. Li, C.Y. Kao, J.C. Gore, Z. Ding. Minimization of Region-Scalable % Fitting Energy for Image Segmentation. In IEEE Transactions on Image % Processing. volume 17, no. 10, pp. 1940-1949, 2008." % % Shi method % "Yonggang Shi, William Clem Karl. A Real-Time Algorithm for the % Approximation of Level-Set-Based Curve Evolution. In IEEE Transactions % on Image Processing. volume 17, no. 05, pp. 645-656, 2008." % % This software is governed by the BSD license and % abiding by the rules of distribution of free software. % % As a counterpart to the access to the source code and rights to copy, % modify and redistribute granted by the license, users are provided only % with a limited warranty and the software's author, the holder of the % economic rights, and the successive licensors have only limited % liability. % % In this respect, the user's attention is drawn to the risks associated % with loading, using, modifying and/or developing or reproducing the % software by the user in light of its specific status of free software, % that may mean that it is complicated to manipulate, and that also % therefore means that it is reserved for developers and experienced % professionals having in-depth computer knowledge. Users are therefore % encouraged to load and test the software's suitability as regards their % requirements in conditions enabling the security of their systems and/or % data to be ensured and, more generally, to use and operate it in the % same conditions as regards security. % %------------------------------------------------------------------------ %------------------------------------------------------------------------ % Description: This code implements the paper: "Variational B-Spline % Level-Set: A Linear Filtering Approach for Fast Deformable Model % Evolution." By Olivier Bernard. % % Coded by: Olivier Bernard (www.creatis.insa-lyon.fr/~bernard) %------------------------------------------------------------------------ function [seg,phi,its] = creaseg_bernard(img,init_mask,max_its,scale,thresh,color,display) %-- default value for parameter max_its is 1 if(~exist('max_its','var')) max_its = 100; end %-- default value for parameter scale is 1 if(~exist('scale','var')) scale = 1; end %-- default value for parameter thresh is 0 if(~exist('thresh','var')) thresh = 0; end %-- default value for parameter color is 'r' if(~exist('color','var')) color = 'r'; end %-- default behavior is to display intermediate outputs if(~exist('display','var')) display = true; end %-- Ensures image is 2D double matrix img = im2graydouble(img); % init_mask = init_mask<=0; %-- Take care that the scale is an integer value strictly lower that 5 scale = round(scale); if ( scale > 4 ) scale = 4; end %-- Make sure that image is in correct dimension (multiple of scale) [dimI,dimJ] = size(img); dimIN = dimI; dimJN = dimJ; val = power(2,scale); diff = dimIN / val - fix( dimIN / val ); while ( diff ~= 0 ) dimIN = dimIN + 1; diff = dimIN / val - fix( dimIN / val ); end diff = dimJN / val - fix( dimJN / val ); while ( diff ~= 0 ) dimJN = dimJN + 1; diff = dimJN / val - fix( dimJN / val ); end imgN = repmat(0,[dimIN dimJN]); imgN(1:size(img,1),1:size(img,2)) = img; for i=(dimI+1):1:dimIN imgN(i,1:dimJ) = img(end,:); end for j=(dimJ+1):1:dimJN imgN(1:dimI,j) = img(:,end); end img = imgN; clear imgN; %-- Same for mask init_maskN = repmat(0,[dimIN dimJN]); init_maskN(1:size(init_mask,1),1:size(init_mask,2)) = init_mask; init_mask = init_maskN; clear init_maskN; %-- Compute the corresponding bspline filter used for the comutation of %-- the energy gradient from the Bslpine coefficients if ( scale == 0 ) filter = [ 0.1667 0.6667 0.1667 ]; elseif ( scale == 1 ) filter = [ 0.0208 0.1667 0.4792 0.6667 0.4792 0.1667 0.0208 ]; elseif ( scale == 2 ) filter = [ 0.0026 0.0208 0.0703 0.1667 0.3151 0.4792 0.6120 ... 0.6667 0.6120 0.4792 0.3151 0.1667 0.0703 0.0208 0.0026 ]; elseif ( scale == 3 ) filter = [ 3.2552e-004 0.0026 0.0088 0.0208 0.0407 0.0703 0.1117 ... 0.1667 0.2360 0.3151 0.3981 0.4792 0.5524 0.6120 0.6520 ... 0.6667 0.6520 0.6120 0.5524 0.4792 0.3981 0.3151 0.2360 ... 0.1667 0.1117 0.0703 0.0407 0.0208 0.0088 0.0026 3.2552e-004 ]; elseif ( scale == 4 ) filter = [ 4.0690e-005 3.2552e-004 0.0011 0.0026 0.0051 0.0088 ... 0.0140 0.0208 0.0297 0.0407 0.0542 0.0703 0.0894 0.1117 ... 0.1373 0.1667 0.1997 0.2360 0.2747 0.3151 0.3565 0.3981 ... 0.4392 0.4792 0.5171 0.5524 0.5843 0.6120 0.6348 0.6520 ... 0.6629 0.6667 0.6629 0.6520 0.6348 0.6120 0.5843 0.5524 ... 0.5171 0.4792 0.4392 0.3981 0.3565 0.3151 0.2747 0.2360 ... 0.1997 0.1667 0.1373 0.1117 0.0894 0.0703 0.0542 0.0407 ... 0.0297 0.0208 0.0140 0.0088 0.0051 0.0026 0.0011 ... 3.2552e-004 4.0690e-005 ]; else filter = 0; end %-- Create a signed distance map (SDF) from mask phi = mask2phi(init_mask); %-- Create BSpline coefficient image from phi [bspline,phi] = Initialization(phi,scale); %-- fig = findobj(0,'tag','creaseg'); ud = get(fig,'userdata'); %--main loop its = 0; stop = 0; prev_mask = init_mask; c = 0; [u,v,NRJ] = MinimizedFromFeatureParameters(0,0,phi,img,bitmax); % Initializing u, v, NRJ while ((its < max_its) && ~stop) %-- Minimized energy from the BSpline coefficients [u,v,phi,bspline,img,NRJ] = ... MinimizedFromBSplineCoefficients(u,v,phi,bspline,img,NRJ,filter,scale); new_mask = phi<=0; c = convergence(prev_mask,new_mask,thresh,c); if c <= 5 its = its + 1; prev_mask = new_mask; else stop = 1; end %-- intermediate output if (display>0) if ( mod(its,1)==0 ) set(ud.txtInfo1,'string',sprintf('iteration: %d',its),'color',[1 1 0]); showCurveAndPhi(phi,ud,color); drawnow; end else if ( mod(its,10)==0 ) set(ud.txtInfo1,'string',sprintf('iteration: %d',its),'color',[1 1 0]); drawnow; end end end %-- final output showCurveAndPhi(phi,ud,color); %-- make mask from SDF phi = phi(1:dimI,1:dimJ); seg = phi<=0; %-- Get mask from levelset %--------------------------------------------------------------------- %--------------------------------------------------------------------- %-- AUXILIARY FUNCTIONS ---------------------------------------------- %--------------------------------------------------------------------- %--------------------------------------------------------------------- %-- Displays the image with curve superimposed function showCurveAndPhi(phi,ud,cl) axes(get(ud.imageId,'parent')); delete(findobj(get(ud.imageId,'parent'),'type','line')); hold on; [c,h] = contour(phi,[0 0],cl{1},'Linewidth',3); hold off; delete(h); test = isequal(size(c,2),0); while (test==false) s = c(2,1); if ( s == (size(c,2)-1) ) t = c; hold on; plot(t(1,2:end)',t(2,2:end)',cl{1},'Linewidth',3); test = true; else t = c(:,2:s+1); hold on; plot(t(1,1:end)',t(2,1:end)',cl{1},'Linewidth',3); c = c(:,s+2:end); end end %-- converts a mask to a SDF function phi = mask2phi(init_a) phi=bwdist(init_a)-bwdist(1-init_a)+im2double(init_a)-.5; %-- Converts image to one channel (grayscale) double function img = im2graydouble(img) [dimy, dimx, c] = size(img); if(isfloat(img)) % image is a double if(c==3) img = rgb2gray(uint8(img)); end else % image is a int if(c==3) img = rgb2gray(img); end img = double(img); end %-- Converts image to BSpline coeffcients image (double) function BSpline = ConvertImageToBSpline(BSpline) for i=1:1:size(BSpline,1) BSpline(i,:) = ConvertSignalToBSpline(BSpline(i,:)); end for j=1:1:size(BSpline,2) BSpline(:,j) = ConvertSignalToBSpline(BSpline(:,j)); end %-- Converts Signal to BSpline coefficients signal(double) function BSpline = ConvertSignalToBSpline(BSpline) z = sqrt(3)-2; lambda = (1-z)*(1-1/z); BSpline = lambda*BSpline; BSpline(1) = GetInitialCausalCoefficient(BSpline,z); for n=2:1:length(BSpline) BSpline(n) = BSpline(n) + z * BSpline(n-1); end BSpline(end) = (z * BSpline(end-1) + BSpline(end)) * z / (z * z - 1); for n=(length(BSpline)-1):-1:1 BSpline(n) = z * ( BSpline(n+1) - BSpline(n) ); end %-- Compute first BSpline coefficients signal (double) function val = GetInitialCausalCoefficient(BSpline,z) len = length(BSpline); tolerance = 1e-6; z1 = z; zn = power(z,len-1); sum = BSpline(1) + zn * BSpline(end); horizon = 2 + round( log(tolerance) / log(abs(z))); if ( horizon > len ) horizon = len; end zn = zn * zn; for n=2:1:horizon zn = zn / z; sum = sum + (z1 + zn) * BSpline(n); z1 = z1 * z; end val = sum / (1-power(z,2*len-2)); %-- Converts BSpline coeffcients image to image (double) function Image = ConvertBSplineToImage(Image) for i=1:1:size(Image,1) Image(i,:) = ConvertBSplineToSignal(Image(i,:)); end for j=1:1:size(Image,2) Image(:,j) = ConvertBSplineToSignal(Image(:,j)); end %-- Converts BSpline coeffcients signal to signal (double) function Signal = ConvertBSplineToSignal(BSpline) len = length(BSpline); Signal = zeros(size(BSpline)); kernelFilter = [4/6 1/6]; Signal(1) = BSpline(1) * kernelFilter(1) + 2 * BSpline(2) * kernelFilter(2); for n=2:1:(len-1) Signal(n) = BSpline(n) * kernelFilter(1) + ... BSpline(n-1) * kernelFilter(2) + BSpline(n+1) * kernelFilter(2); end Signal(end) = BSpline(end) * kernelFilter(1) + 2 * BSpline(end-1) * kernelFilter(2); %-- Create initial BSpline coefficients from phi with normalization procedure function [bspline,phi] = Initialization(phi,scale) phiDown = imresize(phi,1/power(2,scale)); bspline = ConvertImageToBSpline(phiDown); Linf = max(abs(bspline(:))); bspline = 3 * bspline / Linf; phiDown = ConvertBSplineToImage(bspline); phi = imresize(phiDown,power(2,scale)); %-- Minimized energy from the feature parameters function [u,v,NRJ] = MinimizedFromFeatureParameters(u,v,phi,img,NRJ) %-- Compute new feature parameters un = sum( img(:) .* heavyside(phi(:)) ) / sum( heavyside(phi(:)) ); vn = sum( img(:) .* ( 1 - heavyside(phi(:)) ) ) / sum( 1 - heavyside(phi(:)) ); NewNRJ = sum( (img(:)-un).^2 .* heavyside(phi(:)) + (img(:)-vn).^2 .* (1-heavyside(phi(:))) ); %-- Update feature parameters if ( NewNRJ < NRJ ) u = un; v = vn; NRJ = NewNRJ; end %-- Compute the regularized heaviside function function y = heavyside(x) epsilon = 0.5; y = 0.5 * ( 1 + (2/pi) * atan(x/epsilon) ); %-- Compute the regularized dirac function function y = dirac(x) epsilon = 0.5; y = (1/(pi*epsilon)) ./ ( 1 + (x/epsilon).^2 ); %-- Minimized energy from the BSpline coefficients function [u,v,phi,bspline,img,NRJ] = ... MinimizedFromBSplineCoefficients(u,v,phi,bspline,img,NRJ,filter,scale) %-- Compute energy gradient image feature = ( (img-u).^2 - (img-v).^2 ) .* dirac(phi); valMax = max(abs(feature(:))); feature = feature / valMax; grad = ComputeGradientEnergyFromBSpline(feature,filter,scale); %-- Compute Gradient descent with feedback adjustement nbItMax = 5; diffNRJ = 1; it = 0; mu = 1.5; while ( ( diffNRJ > 0 ) && ( it < nbItMax ) ) %-- Update mu and it it = it + 1; mu = mu / 1.5; %-- Compute new BSpline values bspline_new = bspline - mu*grad; Linf = max(abs(bspline_new(:))); bspline_new = 3 * bspline_new / Linf; %-- Compute the corresponding Levelset phi_new = MultiscaleUpSampling(bspline_new,scale); %-- Compute the corresponding energy value [u_new,v_new,NRJ_new] = MinimizedFromFeatureParameters(u,v,phi_new,img,NRJ); % Update diffNRJ value diffNRJ = NRJ_new - NRJ; end if ( diffNRJ < 0 ) bspline = bspline_new; phi = phi_new; NRJ = NRJ_new; u = u_new; v = v_new; end %-- Compute the energy gradient form the Bspline taking into account the %-- scaling factor function grad = ComputeGradientEnergyFromBSpline(feature,filter,scale) nI = size(feature,1); nJ = size(feature,2); nIScale = nI / power(2,scale); nJScale = nJ / power(2,scale); tmp = zeros(nIScale,nJ); grad = zeros(nIScale,nJScale); for j=1:1:nJ tmp(:,j) = GetMultiscaleConvolution(feature(:,j),filter,scale); end for i=1:1:nIScale vec = GetMultiscaleConvolution(tmp(i,:),filter,scale); grad(i,:) = vec; end %-- Compute the energy gradient form the Bspline taking into account the %-- scaling factor for a signal function out = GetMultiscaleConvolution(in,filter,scale) %-- parameters scaleN = power(2,scale); width = length(in); widthScale = width / scaleN; nx2 = 2 * width - 2; size = scaleN * 4 - 1; index = zeros(1,size); out = zeros(1,widthScale); %-- main loop for n=0:1:(widthScale-1) %-- Compute indexes x = n * scaleN; i = round(floor(x)) - floor(size/2); for k=0:1:(size-1) index(k+1) = i; i = i + 1; end %-- Apply the anti-mirror boundary conditions subImage = zeros(1,size); for k=0:1:(size-1) m = index(k+1); if ( (m>=0) && (m<width) ) subImage(k+1) = in(m+1); elseif (m>=width) subImage(k+1) = 2*in(width)-in(nx2-m+2); elseif (m<0) subImage(k+1) = 2*in(1)-in(-m+1); end end %-- Compute value w = 0; for k=0:1:(size-1) w = w + filter(k+1) * subImage(k+1); end out(n+1) = w; end %-- Upsample by a factor of power(2,h) function output = MultiscaleUpSampling(input,h) dimI = size(input,1); dimJ = size(input,2); scaleDimI = dimI * power(2,h); scaleDimJ = dimJ * power(2,h); output = zeros(scaleDimI,scaleDimJ); %-- Initialization nx2 = 2 * dimI - 2; ny2 = 2 * dimJ - 2; scale = power(2,h); xIndex = zeros(1,4); yIndex = zeros(1,4); xWeight = zeros(1,4); yWeight = zeros(1,4); subImage = zeros(4,4); %-- Compute the sampled image for u=0:1:(scaleDimI-1) for v=0:1:(scaleDimJ-1) %-- Initialization x = u / scale; y = v / scale; %-- Compute the interpolation indexes i = floor(x) - 1; j = floor(y) - 1; for k=0:1:3 xIndex(k+1) = i; yIndex(k+1) = j; i = i + 1; j = j + 1; end %-- Compute the interpolation weights %-- x --% w = x - xIndex(2); xWeight(4) = (1.0 / 6.0) * w * w * w; xWeight(1) = (1.0 / 6.0) + (1.0 / 2.0) * w * (w - 1.0) - xWeight(4); xWeight(3) = w + xWeight(1) - 2.0 * xWeight(4); xWeight(2) = 1.0 - xWeight(1) - xWeight(3) - xWeight(4); %-- y --% w = y - yIndex(2); yWeight(4) = (1.0 / 6.0) * w * w * w; yWeight(1) = (1.0 / 6.0) + (1.0 / 2.0) * w * (w - 1.0) - yWeight(4); yWeight(3) = w + yWeight(1) - 2.0 * yWeight(4); yWeight(2) = 1.0 - yWeight(1) - yWeight(3) - yWeight(4); %-- Apply the anti-mirror boundary conditions for k=0:1:3 m = xIndex(k+1); for l=0:1:3 n = yIndex(l+1); if ( (m>=0) && (m<dimI) ) if ( (n>=0) && (n<dimJ) ) subImage(k+1,l+1) = input(m+1,n+1); elseif (n>=dimJ) subImage(k+1,l+1) = 2*(input(m+1,dimJ))-input(m+1,ny2-n+2); elseif (n<0) subImage(k+1,l+1) = 2*(input(m+1,n+2))-input(m+1,n+3); end elseif (m>=dimI) if ( (n>=0) && (n<dimJ) ) subImage(k+1,l+1) = 2*(input(dimI,n+1))-input(nx2-m+2,n+1); elseif (n>=dimJ) subImage(k+1,l+1) = 2*(input(dimI,dimJ))-input(nx2-m+2,ny2-n+2); elseif (n<0) subImage(k+1,l+1) = 2*(input(dimI,n+2))-input(nx2-m+2,n+3); end elseif (m<0) if ( (n>=0) && (n<dimJ) ) subImage(k+1,l+1) = 2*(input(m+2,n+1))-input(m+3,n+1); elseif (n>=dimJ) subImage(k+1,l+1) = 2*(input(m+2,dimJ))-input(m+3,ny2-n+2); elseif (n<0) subImage(k+1,l+1) = 2*(input(m+2,n+2))-input(m+3,n+3); end end end end %-- perform interpolation val = 0; for k=0:1:3 w = 0; for l=0:1:3 w = w + xWeight(l+1) * subImage(l+1,k+1); end val = val + yWeight(k+1) * w; end output(u+1,v+1) = val; end end % Convergence Test function c = convergence(p_mask,n_mask,thresh,c) diff = p_mask - n_mask; n_diff = sum(abs(diff(:))); if n_diff < thresh c = c + 1; else c = 0; end
github
jacksky64/imageProcessing-master
creaseg_caselles.m
.m
imageProcessing-master/segmentation/creaseg/creaseg/creaseg/src/creaseg_caselles.m
13,230
utf_8
6cfc1c6a7f5ac2f69a422609ce2fec7e
% Copyright or © or Copr. CREATIS laboratory, Lyon, France. % % Contributor: Olivier Bernard, Associate Professor at the french % engineering university INSA (Institut National des Sciences Appliquees) % and a member of the CREATIS-LRMN laboratory (CNRS 5220, INSERM U630, % INSA, Claude Bernard Lyon 1 University) in France (Lyon). % % Date of creation: 8th of October 2009 % % E-mail of the author: [email protected] % % This software is a computer program whose purpose is to evaluate the % performance of different level-set based segmentation algorithms in the % context of image processing (and more particularly on biomedical % images). % % The software has been designed for two main purposes. % - firstly, CREASEG allows you to use six different level-set methods. % These methods have been chosen in order to work with a wide range of % level-sets. You can select for instance classical methods such as % Caselles or Chan & Vese level-set, or more recent approaches such as the % one developped by Lankton or Bernard. % - finally, the software allows you to compare the performance of the six % level-set methods on different images. The performance can be evaluated % either visually, or from measurements (either using the Dice coefficient % or the PSNR value) between a reference and the results of the % segmentation. % % The level-set segmentation platform is citationware. If you are % publishing any work, where this program has been used, or which used one % of the proposed level-set algorithms, please remember that it was % obtained free of charge. You must reference the papers shown below and % the name of the CREASEG software must be mentioned in the publication. % % CREASEG software % "T. Dietenbeck, M. Alessandrini, D. Friboulet, O. Bernard. CREASEG: a % free software for the evaluation of image segmentation algorithms based % on level-set. In IEEE International Conference On Image Processing. % Hong Kong, China, 2010." % % Bernard method % "O. Bernard, D. Friboulet, P. Thevenaz, M. Unser. Variational B-Spline % Level-Set: A Linear Filtering Approach for Fast Deformable Model % Evolution. In IEEE Transactions on Image Processing. volume 18, no. 06, % pp. 1179-1191, 2009." % % Caselles method % "V. Caselles, R. Kimmel, and G. Sapiro. Geodesic active contours. % International Journal of Computer Vision, volume 22, pp. 61-79, 1997." % % Chan & Vese method % "T. Chan and L. Vese. Active contours without edges. IEEE Transactions on % Image Processing. volume10, pp. 266-277, February 2001." % % Lankton method % "S. Lankton, A. Tannenbaum. Localizing Region-Based Active Contours. In % IEEE Transactions on Image Processing. volume 17, no. 11, pp. 2029-2039, % 2008." % % Li method % "C. Li, C.Y. Kao, J.C. Gore, Z. Ding. Minimization of Region-Scalable % Fitting Energy for Image Segmentation. In IEEE Transactions on Image % Processing. volume 17, no. 10, pp. 1940-1949, 2008." % % Shi method % "Yonggang Shi, William Clem Karl. A Real-Time Algorithm for the % Approximation of Level-Set-Based Curve Evolution. In IEEE Transactions % on Image Processing. volume 17, no. 05, pp. 645-656, 2008." % % This software is governed by the BSD license and % abiding by the rules of distribution of free software. % % As a counterpart to the access to the source code and rights to copy, % modify and redistribute granted by the license, users are provided only % with a limited warranty and the software's author, the holder of the % economic rights, and the successive licensors have only limited % liability. % % In this respect, the user's attention is drawn to the risks associated % with loading, using, modifying and/or developing or reproducing the % software by the user in light of its specific status of free software, % that may mean that it is complicated to manipulate, and that also % therefore means that it is reserved for developers and experienced % professionals having in-depth computer knowledge. Users are therefore % encouraged to load and test the software's suitability as regards their % requirements in conditions enabling the security of their systems and/or % data to be ensured and, more generally, to use and operate it in the % same conditions as regards security. % %------------------------------------------------------------------------ %------------------------------------------------------------------------ % Description: This code implements the paper: "Geodesic active contours. % International Journal of Computer Vision." By Vincent Caselles. % % Coded by: Olivier Bernard (www.creatis.insa-lyon.fr/~bernard) %------------------------------------------------------------------------ function [seg,phi,its] = creaseg_caselles(img,init_mask,max_its,propag,thresh,color,display) %-- default value for parameter img and init_mask if(~exist('img','var')) img = imread('data/Image/simu1.bmp'); init_mask = repmat(0,[size(img,1) size(img,2)]); init_mask(round(size(img,1)/3):size(img,1)-round(size(img,1)/3),... round(size(img,2)/3):size(img,2)-round(size(img,2)/3)) = 1; end %-- default value for parameter max_its is 100 if(~exist('max_its','var')) max_its = 100; end %-- default value for parameter propag is 1 if(~exist('propag','var')) propag = 1; end %-- default value for parameter max_its is 1 if(~exist('thresh','var')) thresh = 0; end %-- default value for parameter color is 'r' if(~exist('color','var')) color = 'r'; end %-- default behavior is to display intermediate outputs if(~exist('display','var')) display = true; end %-- ensures image is 2D double matrix img = im2graydouble(img); % init_mask = init_mask<=0; %-- Create a signed distance map (SDF) from mask phi = mask2phi(init_mask); %-- Compute feature image from gradient information h = fspecial('gaussian',[5 5],1); feature = imfilter(img,h,'same'); [FX,FY] = gradient(feature); feature = sqrt(FX.^2+FY.^2+eps); feature = 1 ./ ( 1 + feature.^2 ); %-- fig = findobj(0,'tag','creaseg'); ud = get(fig,'userdata'); %--main loop its = 0; stop = 0; prev_mask = init_mask; c = 0; while ((its < max_its) && ~stop) idx = find(phi <= 1.2 & phi >= -1.2); %-- get the curve's narrow band if ~isempty(idx) %-- intermediate output if (display>0) if ( mod(its,50)==0 ) set(ud.txtInfo1,'string',sprintf('iteration: %d',its),'color',[1 1 0]); showCurveAndPhi(phi,ud,color); drawnow; end else if ( mod(its,10)==0 ) set(ud.txtInfo1,'string',sprintf('iteration: %d',its),'color',[1 1 0]); drawnow; end end %-- force from image information F = feature(idx); [curvature,normGrad,FdotGrad] = ... get_evolution_functions(phi,feature,idx); % force from curvature penalty %-- gradient descent to minimize energy dphidt1 = F.*curvature.*normGrad; dphidt1 = dphidt1./max(abs(dphidt1(:))); dphidt2 = FdotGrad; dphidt2 = dphidt2./max(abs(dphidt2(:))); dphidt3 = F.*normGrad; dphidt3 = dphidt3./max(abs(dphidt3(:))); dphidt = dphidt1 + dphidt2 - propag*dphidt3; %-- maintain the CFL condition dt = .45/(max(abs(dphidt))+eps); %-- evolve the curve phi(idx) = phi(idx) + dt.*dphidt; %-- Keep SDF smooth phi = sussman(phi, .5); new_mask = phi<=0; c = convergence(prev_mask,new_mask,thresh,c); if c <= 5 its = its + 1; prev_mask = new_mask; else stop = 1; end else break; end end %-- final output showCurveAndPhi(phi,ud,color); %-- make mask from SDF seg = phi<=0; %-- Get mask from levelset %--------------------------------------------------------------------- %--------------------------------------------------------------------- %-- AUXILIARY FUNCTIONS ---------------------------------------------- %--------------------------------------------------------------------- %--------------------------------------------------------------------- %-- Displays the image with curve superimposed function showCurveAndPhi(phi,ud,cl) axes(get(ud.imageId,'parent')); delete(findobj(get(ud.imageId,'parent'),'type','line')); hold on; [c,h] = contour(phi,[0 0],cl{1},'Linewidth',3); hold off; delete(h); test = isequal(size(c,2),0); while (test==false) s = c(2,1); if ( s == (size(c,2)-1) ) t = c; hold on; plot(t(1,2:end)',t(2,2:end)',cl{1},'Linewidth',3); test = true; else t = c(:,2:s+1); hold on; plot(t(1,1:end)',t(2,1:end)',cl{1},'Linewidth',3); c = c(:,s+2:end); end end %-- converts a mask to a SDF function phi = mask2phi(init_a) phi=bwdist(init_a)-bwdist(1-init_a)+im2double(init_a)-.5; %-- compute curvature along SDF function [curvature,normGrad,FdotGrad] = get_evolution_functions(phi,feature,idx) [dimy, dimx] = size(phi); [y x] = ind2sub([dimy,dimx],idx); % get subscripts %-- get subscripts of neighbors ym1 = y-1; xm1 = x-1; yp1 = y+1; xp1 = x+1; %-- bounds checking ym1(ym1<1) = 1; xm1(xm1<1) = 1; yp1(yp1>dimy)=dimy; xp1(xp1>dimx) = dimx; %-- get indexes for 8 neighbors idup = sub2ind(size(phi),yp1,x); iddn = sub2ind(size(phi),ym1,x); idlt = sub2ind(size(phi),y,xm1); idrt = sub2ind(size(phi),y,xp1); idul = sub2ind(size(phi),yp1,xm1); idur = sub2ind(size(phi),yp1,xp1); iddl = sub2ind(size(phi),ym1,xm1); iddr = sub2ind(size(phi),ym1,xp1); %-- get central derivatives of SDF at x,y phi_x = (-phi(idlt)+phi(idrt))/2; phi_y = (-phi(iddn)+phi(idup))/2; phi_xx = phi(idlt)-2*phi(idx)+phi(idrt); phi_yy = phi(iddn)-2*phi(idx)+phi(idup); phi_xy = 0.25*phi(iddl)+0.25*phi(idur)... -0.25*phi(iddr)-0.25*phi(idul); phi_x2 = phi_x.^2; phi_y2 = phi_y.^2; %-- compute curvature (Kappa) curvature = ((phi_x2.*phi_yy + phi_y2.*phi_xx - 2*phi_x.*phi_y.*phi_xy)./... (phi_x2 + phi_y2 +eps).^(3/2)); %-- compute norm of gradient phi_xm = phi(idx)-phi(idlt); phi_xp = phi(idrt)-phi(idx); phi_ym = phi(idx)-phi(iddn); phi_yp = phi(idup)-phi(idx); normGrad = sqrt( (max(phi_xm,0)).^2 + (min(phi_xp,0)).^2 + ... (max(phi_ym,0)).^2 + (min(phi_yp,0)).^2 ); %-- compute scalar product between the feature image and the gradient of phi F_x = 0.5*feature(idrt)-0.5*feature(idlt); F_y = 0.5*feature(idup)-0.5*feature(iddn); FdotGrad = (max(F_x,0)).*(phi_xp) + (min(F_x,0)).*(phi_xm) + ... (max(F_y,0)).*(phi_yp) + (min(F_y,0)).*(phi_ym); %-- Converts image to one channel (grayscale) double function img = im2graydouble(img) [dimy, dimx, c] = size(img); if (isfloat(img)) if (c==3) img = rgb2gray(uint8(img)); end else if (c==3) img = rgb2gray(img); end img = double(img); end %-- level set re-initialization by the sussman method function D = sussman(D, dt) % forward/backward differences a = D - shiftR(D); % backward b = shiftL(D) - D; % forward c = D - shiftD(D); % backward d = shiftU(D) - D; % forward a_p = a; a_n = a; % a+ and a- b_p = b; b_n = b; c_p = c; c_n = c; d_p = d; d_n = d; a_p(a < 0) = 0; a_n(a > 0) = 0; b_p(b < 0) = 0; b_n(b > 0) = 0; c_p(c < 0) = 0; c_n(c > 0) = 0; d_p(d < 0) = 0; d_n(d > 0) = 0; dD = zeros(size(D)); D_neg_ind = find(D < 0); D_pos_ind = find(D > 0); dD(D_pos_ind) = sqrt(max(a_p(D_pos_ind).^2, b_n(D_pos_ind).^2) ... + max(c_p(D_pos_ind).^2, d_n(D_pos_ind).^2)) - 1; dD(D_neg_ind) = sqrt(max(a_n(D_neg_ind).^2, b_p(D_neg_ind).^2) ... + max(c_n(D_neg_ind).^2, d_p(D_neg_ind).^2)) - 1; D = D - dt .* sussman_sign(D) .* dD; %-- whole matrix derivatives function shift = shiftD(M) shift = shiftR(M')'; function shift = shiftL(M) shift = [ M(:,2:size(M,2)) M(:,size(M,2)) ]; function shift = shiftR(M) shift = [ M(:,1) M(:,1:size(M,2)-1) ]; function shift = shiftU(M) shift = shiftL(M')'; function S = sussman_sign(D) S = D ./ sqrt(D.^2 + 1); % Convergence Test function c = convergence(p_mask,n_mask,thresh,c) diff = p_mask - n_mask; n_diff = sum(abs(diff(:))); if n_diff < thresh c = c + 1; else c = 0; end
github
jacksky64/imageProcessing-master
creaseg_drawMultiReferenceContours.m
.m
imageProcessing-master/segmentation/creaseg/creaseg/creaseg/src/creaseg_drawMultiReferenceContours.m
11,499
utf_8
5403388b94e5f8f3962a6ca277f2844c
% Copyright or © or Copr. CREATIS laboratory, Lyon, France. % % Contributor: Olivier Bernard, Associate Professor at the french % engineering university INSA (Institut National des Sciences Appliquees) % and a member of the CREATIS-LRMN laboratory (CNRS 5220, INSERM U630, % INSA, Claude Bernard Lyon 1 University) in France (Lyon). % % Date of creation: 8th of October 2009 % % E-mail of the author: [email protected] % % This software is a computer program whose purpose is to evaluate the % performance of different level-set based segmentation algorithms in the % context of image processing (and more particularly on biomedical % images). % % The software has been designed for two main purposes. % - firstly, CREASEG allows you to use six different level-set methods. % These methods have been chosen in order to work with a wide range of % level-sets. You can select for instance classical methods such as % Caselles or Chan & Vese level-set, or more recent approaches such as the % one developped by Lankton or Bernard. % - finally, the software allows you to compare the performance of the six % level-set methods on different images. The performance can be evaluated % either visually, or from measurements (either using the Dice coefficient % or the PSNR value) between a reference and the results of the % segmentation. % % The level-set segmentation platform is citationware. If you are % publishing any work, where this program has been used, or which used one % of the proposed level-set algorithms, please remember that it was % obtained free of charge. You must reference the papers shown below and % the name of the CREASEG software must be mentioned in the publication. % % CREASEG software % "T. Dietenbeck, M. Alessandrini, D. Friboulet, O. Bernard. CREASEG: a % free software for the evaluation of image segmentation algorithms based % on level-set. In IEEE International Conference On Image Processing. % Hong Kong, China, 2010." % % Bernard method % "O. Bernard, D. Friboulet, P. Thevenaz, M. Unser. Variational B-Spline % Level-Set: A Linear Filtering Approach for Fast Deformable Model % Evolution. In IEEE Transactions on Image Processing. volume 18, no. 06, % pp. 1179-1191, 2009." % % Caselles method % "V. Caselles, R. Kimmel, and G. Sapiro. Geodesic active contours. % International Journal of Computer Vision, volume 22, pp. 61-79, 1997." % % Chan & Vese method % "T. Chan and L. Vese. Active contours without edges. IEEE Transactions on % Image Processing. volume10, pp. 266-277, February 2001." % % Lankton method % "S. Lankton, A. Tannenbaum. Localizing Region-Based Active Contours. In % IEEE Transactions on Image Processing. volume 17, no. 11, pp. 2029-2039, % 2008." % % Li method % "C. Li, C.Y. Kao, J.C. Gore, Z. Ding. Minimization of Region-Scalable % Fitting Energy for Image Segmentation. In IEEE Transactions on Image % Processing. volume 17, no. 10, pp. 1940-1949, 2008." % % Shi method % "Yonggang Shi, William Clem Karl. A Real-Time Algorithm for the % Approximation of Level-Set-Based Curve Evolution. In IEEE Transactions % on Image Processing. volume 17, no. 05, pp. 645-656, 2008." % % This software is governed by the BSD license and % abiding by the rules of distribution of free software. % % As a counterpart to the access to the source code and rights to copy, % modify and redistribute granted by the license, users are provided only % with a limited warranty and the software's author, the holder of the % economic rights, and the successive licensors have only limited % liability. % % In this respect, the user's attention is drawn to the risks associated % with loading, using, modifying and/or developing or reproducing the % software by the user in light of its specific status of free software, % that may mean that it is complicated to manipulate, and that also % therefore means that it is reserved for developers and experienced % professionals having in-depth computer knowledge. Users are therefore % encouraged to load and test the software's suitability as regards their % requirements in conditions enabling the security of their systems and/or % data to be ensured and, more generally, to use and operate it in the % same conditions as regards security. % %------------------------------------------------------------------------ function creaseg_drawMultiReferenceContours(src,evt) %-- get structures fig = findobj(0,'tag','creaseg'); ud = get(fig,'userdata'); fd = get(ud.imageId,'userdata'); pos = floor(get(ud.gca(1),'CurrentPoint')); if ~( pos(1,1) < size(fd.data,2) && pos(1,1) > 1 && pos(1,2) < size(fd.data,1) && pos(1,2) >1 ) return; %Clic outside the image => do nothing end if ( strcmp(get(ud.gcf,'SelectionType'),'normal') ) %-- Set drawingReferenceFlag flag to 1 fd.drawingReferenceFlag = 1; %-- disable drawing, run and pointer buttons set(ud.buttonAction(1),'enable','off'); set(ud.buttonAction(2),'enable','off'); set(ud.buttonAction(3),'enable','off'); %-- delete any overlay lines if ( size(fd.handleReference,2)>0 ) for k=1:size(fd.handleReference{1},1) if ( fd.handleReference{1}(k) ~= 0 ) delete(fd.handleReference{1}(k)); end end else fd.handleReference{1} = 0; end %-- Get point coordinates pt = get(ud.gca,'CurrentPoint'); pt = pt(1,1:2); if (isempty(fd.pointsRef)) fd.pointsRef = [pt(1),pt(2)]; hold on; h = plot(pt(1), pt(2), 'oy', 'linewidth', 2); fd.handleReference{1} = h; else fd.pointsRef(end+1,:) = [pt(1),pt(2)]; color = ud.colorSpec(get(ud.handleContourColor,'userdata')); switch (get(ud.handleAlgoComparison(19),'value')-1) case 0 hold on; h1 = plot(fd.pointsRef(:,1),fd.pointsRef(:,2),'--','color',color{1},'Linewidth',2); tmp = fd.pointsRef(1,:); tmp(end+1,:) = fd.pointsRef(end,:); h2 = plot(tmp(:,1), tmp(:,2), 'y--', 'linewidth', 2); case 1 if length(fd.pointsRef(:,1)) < 3 hold on; h1 = plot(fd.pointsRef(:,1),fd.pointsRef(:,2),'--','color',color{1},'Linewidth',2); tmp = fd.pointsRef(1,:); tmp(end+1,:) = fd.pointsRef(end,:); h2 = plot(tmp(:,1), tmp(:,2), 'y--', 'linewidth', 2); else [xs, ys] = creaseg_spline(fd.pointsRef(:,1)',fd.pointsRef(:,2)'); fin = find((xs == fd.pointsRef(end,1)) & (ys == fd.pointsRef(end,2)) ); deb = find((xs == fd.pointsRef(1,1)) & (ys == fd.pointsRef(1,2)) ); xs = xs([deb:end, 1:deb]); ys = ys([deb:end, 1:deb]); if deb > fin idx = length(xs) + fin - deb; else idx = fin - deb; end clear deb fin; hold on; h1 = plot(xs(1:idx),ys(1:idx),'--','color',color{1},'Linewidth',2); hold on; h2 = plot(xs(idx:end),ys(idx:end),'y--','Linewidth',2); end end h3 = plot(fd.pointsRef(:,1), fd.pointsRef(:,2), 'oy', 'linewidth', 2); hold off; fd.handleReference{1} = [h1;h2;h3]; end elseif ( strcmp(get(ud.gcf,'SelectionType'),'alt') ) %-- create final contour %-- Set drawingReferenceFlag flag to 1 fd.drawingReferenceFlag = 1; %-- enable drawing, run and pointer buttons set(ud.buttonAction(1),'enable','on'); set(ud.buttonAction(2),'enable','on'); set(ud.buttonAction(3),'enable','on'); %-- display final contour if ( size(fd.pointsRef,1)>2 ) %-- delete any overlay lines if ( size(fd.handleReference,2)>0 ) for k=1:size(fd.handleReference{1},1) delete(fd.handleReference{1}(k)); end end %-- color = ud.colorSpec(get(ud.handleContourColor,'userdata')); switch (get(ud.handleAlgoComparison(19),'value') - 1) case 0 tmp = fd.pointsRef; tmp(end+1,:) = tmp(1,:); hold on; h = plot(tmp(:,1),tmp(:,2),'color',color{1},'Linewidth',2); hold off; case 1 if length(fd.pointsRef(:,1)) < 3 tmp = fd.pointsRef; tmp(end+1,:) = tmp(1,:); hold on; h = plot(tmp(:,1),tmp(:,2),'--','color',color{1},'Linewidth',2); else [xs, ys] = creaseg_spline(fd.pointsRef(:,1)',fd.pointsRef(:,2)'); hold on; h = plot(xs,ys,'--','color',color{1},'Linewidth',2); end end fd.handleReference{1} = h; %-- create manual mask X = get(fd.handleReference{1},'X'); Y = get(fd.handleReference{1},'Y'); fd.reference = xor(roipoly(fd.data,X,Y),fd.reference); %-- prepare next contour fd.handleReference{1} = 0; end fd.pointsRef = []; else %-- save reference %-- Set drawingReferenceFlag flag to 1 fd.drawingReferenceFlag = 0; [filename, pathname] = uiputfile({'*.mat', 'All .mat Files'; ... '*.*', 'All Files (*.*)'}, 'Save as', 'data/Reference'); %-- if ok, then save reference if not(isequal(filename,0) || isequal(pathname,0)) %-- save reference as a mat file save_file = fullfile(pathname, filename); refLSF = fd.reference; save(save_file,'refLSF'); %-- Put the "Create" button in bright color set(ud.handleAlgoComparison(17),'BackgroundColor',[240/255 173/255 105/255]); %-- Dislpay confirmation message set(ud.txtInfo1,'string','Reference has been succesfully saved','color','y'); set(ud.txtInfo2,'string',''); set(ud.txtInfo3,'string',''); set(ud.txtInfo4,'string',''); set(ud.txtInfo5,'string',''); else %-- otherwise clean up everything set(ud.txtInfo1,'string','Reference has not been saved','color','y'); set(ud.txtInfo2,'string',''); set(ud.txtInfo3,'string',''); set(ud.txtInfo4,'string',''); set(ud.txtInfo5,'string',''); %-- Put the "Create" button in bright color set(ud.handleAlgoComparison(17),'BackgroundColor',[240/255 173/255 105/255]); %-- reinitialize fd.reference fd.reference = zeros(size(fd.data)); delete(findobj(get(ud.imageId,'parent'),'type','line')); end end %-- save structure set(ud.imageId,'userdata',fd); set(ud.gcf,'userdata',ud);
github
jacksky64/imageProcessing-master
creaseg_managedrawing.m
.m
imageProcessing-master/segmentation/creaseg/creaseg/creaseg/src/creaseg_managedrawing.m
28,116
utf_8
aceff7a2d216a6673f1d67b174d1c4d7
% Copyright or © or Copr. CREATIS laboratory, Lyon, France. % % Contributor: Olivier Bernard, Associate Professor at the french % engineering university INSA (Institut National des Sciences Appliquees) % and a member of the CREATIS-LRMN laboratory (CNRS 5220, INSERM U630, % INSA, Claude Bernard Lyon 1 University) in France (Lyon). % % Date of creation: 8th of October 2009 % % E-mail of the author: [email protected] % % This software is a computer program whose purpose is to evaluate the % performance of different level-set based segmentation algorithms in the % context of image processing (and more particularly on biomedical % images). % % The software has been designed for two main purposes. % - firstly, CREASEG allows you to use six different level-set methods. % These methods have been chosen in order to work with a wide range of % level-sets. You can select for instance classical methods such as % Caselles or Chan & Vese level-set, or more recent approaches such as the % one developped by Lankton or Bernard. % - finally, the software allows you to compare the performance of the six % level-set methods on different images. The performance can be evaluated % either visually, or from measurements (either using the Dice coefficient % or the PSNR value) between a reference and the results of the % segmentation. % % The level-set segmentation platform is citationware. If you are % publishing any work, where this program has been used, or which used one % of the proposed level-set algorithms, please remember that it was % obtained free of charge. You must reference the papers shown below and % the name of the CREASEG software must be mentioned in the publication. % % CREASEG software % "T. Dietenbeck, M. Alessandrini, D. Friboulet, O. Bernard. CREASEG: a % free software for the evaluation of image segmentation algorithms based % on level-set. In IEEE International Conference On Image Processing. % Hong Kong, China, 2010." % % Bernard method % "O. Bernard, D. Friboulet, P. Thevenaz, M. Unser. Variational B-Spline % Level-Set: A Linear Filtering Approach for Fast Deformable Model % Evolution. In IEEE Transactions on Image Processing. volume 18, no. 06, % pp. 1179-1191, 2009." % % Caselles method % "V. Caselles, R. Kimmel, and G. Sapiro. Geodesic active contours. % International Journal of Computer Vision, volume 22, pp. 61-79, 1997." % % Chan & Vese method % "T. Chan and L. Vese. Active contours without edges. IEEE Transactions on % Image Processing. volume10, pp. 266-277, February 2001." % % Lankton method % "S. Lankton, A. Tannenbaum. Localizing Region-Based Active Contours. In % IEEE Transactions on Image Processing. volume 17, no. 11, pp. 2029-2039, % 2008." % % Li method % "C. Li, C.Y. Kao, J.C. Gore, Z. Ding. Minimization of Region-Scalable % Fitting Energy for Image Segmentation. In IEEE Transactions on Image % Processing. volume 17, no. 10, pp. 1940-1949, 2008." % % Shi method % "Yonggang Shi, William Clem Karl. A Real-Time Algorithm for the % Approximation of Level-Set-Based Curve Evolution. In IEEE Transactions % on Image Processing. volume 17, no. 05, pp. 645-656, 2008." % % This software is governed by the BSD license and % abiding by the rules of distribution of free software. % % As a counterpart to the access to the source code and rights to copy, % modify and redistribute granted by the license, users are provided only % with a limited warranty and the software's author, the holder of the % economic rights, and the successive licensors have only limited % liability. % % In this respect, the user's attention is drawn to the risks associated % with loading, using, modifying and/or developing or reproducing the % software by the user in light of its specific status of free software, % that may mean that it is complicated to manipulate, and that also % therefore means that it is reserved for developers and experienced % professionals having in-depth computer knowledge. Users are therefore % encouraged to load and test the software's suitability as regards their % requirements in conditions enabling the security of their systems and/or % data to be ensured and, more generally, to use and operate it in the % same conditions as regards security. % %------------------------------------------------------------------------ function creaseg_managedrawing(src,evt,type) %-- parameters fig = findobj(0,'tag','creaseg'); ud = get(fig,'userdata'); fd = get(ud.imageId,'userdata'); set(ud.buttonAction(2),'BackgroundColor',[240/255 173/255 105/255]); set(ud.buttonAction(3),'BackgroundColor',[240/255 173/255 105/255]); set(ud.buttonAction(6),'BackgroundColor',[240/255 173/255 105/255]); set(ud.buttonAction(7),'BackgroundColor',[240/255 173/255 105/255]); set(ud.buttonAction(1),'background',[160/255 130/255 95/255]); pan off; %-- switch case if ( type == 1 ) %-- first button: draw rectangle for k=3:size(ud.handleInit,1) set(ud.handleInit(k),'BackgroundColor',[240/255 173/255 105/255]); end set(ud.handleInit(2+1),'BackgroundColor',[160/255 130/255 95/255]); %-- enable run, pointer and pan buttons set(ud.buttonAction(2),'enable','on'); set(ud.buttonAction(3),'enable','on'); set(ud.buttonAction(6),'enable','on'); %-- displayDrawingInfo(ud,isempty(fd.data),1); %-- creaseg_cleanOverlays(); %-- set(ud.gcf,'WindowButtonDownFcn',{@startdragrectangle}); set(ud.gcf,'WindowButtonUpFcn',{@stopdragrectangle}); elseif ( type == 2 ) %-- second button draw multi-rectangles for k=3:size(ud.handleInit,1) set(ud.handleInit(k),'BackgroundColor',[240/255 173/255 105/255]); end set(ud.handleInit(2+2),'BackgroundColor',[160/255 130/255 95/255]); %-- enable run, pointer and pan buttons set(ud.buttonAction(2),'enable','on'); set(ud.buttonAction(3),'enable','on'); set(ud.buttonAction(6),'enable','on'); %-- displayDrawingInfo(ud,isempty(fd.data),4); %-- creaseg_cleanOverlays(); %-- set(ud.gcf,'WindowButtonDownFcn',{@startdragmultirectangle}); set(ud.gcf,'WindowButtonUpFcn',{@stopdragmultirectangle}); elseif ( type == 3 ) %-- thrid button: draw ellipse for k=3:size(ud.handleInit,1) set(ud.handleInit(k),'BackgroundColor',[240/255 173/255 105/255]); end set(ud.handleInit(2+3),'BackgroundColor',[160/255 130/255 95/255]); %-- enable run, pointer and pan buttons set(ud.buttonAction(2),'enable','on'); set(ud.buttonAction(3),'enable','on'); set(ud.buttonAction(6),'enable','on'); %-- displayDrawingInfo(ud,isempty(fd.data),2); %-- creaseg_cleanOverlays(); %-- set(ud.gcf,'WindowButtonDownFcn',{@startdragellipse}); set(ud.gcf,'WindowButtonUpFcn',{@stopdragellipse}); elseif ( type == 4 ) %-- forth button: draw multi-ellipse for k=3:size(ud.handleInit,1) set(ud.handleInit(k),'BackgroundColor',[240/255 173/255 105/255]); end set(ud.handleInit(2+4),'BackgroundColor',[160/255 130/255 95/255]); %-- enable run, pointer and pan buttons set(ud.buttonAction(2),'enable','on'); set(ud.buttonAction(3),'enable','on'); set(ud.buttonAction(6),'enable','on'); %-- displayDrawingInfo(ud,isempty(fd.data),5); %-- creaseg_cleanOverlays(); %-- set(ud.gcf,'WindowButtonDownFcn',{@startdragmultiellipse}); set(ud.gcf,'WindowButtonUpFcn',{@stopdragmultiellipse}); elseif ( type == 5 ) %-- fith button: draw manual contour for k=3:size(ud.handleInit,1) set(ud.handleInit(k),'BackgroundColor',[240/255 173/255 105/255]); end set(ud.handleInit(2+5),'BackgroundColor',[160/255 130/255 95/255]); %-- disable run and pointer buttons set(ud.buttonAction(2),'enable','off'); set(ud.buttonAction(3),'enable','off'); %-- displayDrawingInfo(ud,isempty(fd.data),3); %-- creaseg_cleanOverlays(); %-- set(ud.gcf,'WindowButtonDownFcn',{@creaseg_drawManualContour}); set(ud.gcf,'WindowButtonUpFcn',''); elseif ( type == 6 ) %-- sixth button: draw multi-manuals for k=3:size(ud.handleInit,1) set(ud.handleInit(k),'BackgroundColor',[240/255 173/255 105/255]); end set(ud.handleInit(2+6),'BackgroundColor',[160/255 130/255 95/255]); %-- disable run and pointer buttons set(ud.buttonAction(2),'enable','off'); set(ud.buttonAction(3),'enable','off'); %-- displayDrawingInfo(ud,isempty(fd.data),6); %-- creaseg_cleanOverlays(); %-- set(ud.gcf,'WindowButtonDownFcn',{@creaseg_drawMultiManualContours}); set(ud.gcf,'WindowButtonUpFcn',''); end %------------------------------------------------------------------ function startdragrectangle(src,evt) %-- get structures fig = findobj(0,'tag','creaseg'); ud = get(fig,'userdata'); fd = get(ud.imageId,'userdata'); pos = floor(get(ud.gca(1),'CurrentPoint')); if ~( pos(1,1) < size(fd.data,2) && pos(1,1) > 1 && pos(1,2) < size(fd.data,1) && pos(1,2) >1 ) % Clic outside the image return; end %-- clean rectangle overlay if ( size(fd.handleRect,2)>0 ) delete(fd.handleRect{1}); fd.handleRect(1)=[]; end %-- initialize rectangle display pt = get(ud.gca,'CurrentPoint'); pt = pt(1,1:2); h = rectangle('Position',[pt(1),pt(2),1,1],'Linewidth',1,'EdgeColor','y','LineStyle','--'); %-- save rectangle position fd.handleRect{1} = h; set(ud.imageId,'userdata',fd); %-- initialize the interactive rectangle display set(ud.gcf,'WindowButtonMotionFcn',{@dragrectangle,pt,h}); %------------------------------------------------------------------ function startdragmultirectangle(src,evt) %-- get structures fig = findobj(0,'tag','creaseg'); ud = get(fig,'userdata'); fd = get(ud.imageId,'userdata'); pos = floor(get(ud.gca(1),'CurrentPoint')); if ~( pos(1,1) < size(fd.data,2) && pos(1,1) > 1 && pos(1,2) < size(fd.data,1) && pos(1,2) >1 ) % Clic outside the image return; end %-- initialize rectangle display pt = get(ud.gca,'CurrentPoint'); pt = pt(1,1:2); h = rectangle('Position',[pt(1),pt(2),1,1],'Linewidth',1,'EdgeColor','y','LineStyle','--'); %-- save rectangle position fd.rect = [pt(1),pt(2),1,1]; fd.handleRect{end+1} = h; set(ud.imageId,'userdata',fd); %-- initialize the interactive rectangle display set(ud.gcf,'WindowButtonMotionFcn',{@dragrectangle,pt,h}); %------------------------------------------------------------------ function dragrectangle(varargin) %-- get structures fig = findobj(0,'tag','creaseg'); ud = get(fig,'userdata'); fd = get(ud.imageId,'userdata'); pt1 = varargin{3}; h = varargin{4}; pt2 = get(ud.gca,'CurrentPoint'); pt2 = pt2(1,1:2); %-- Check bounds pt2(1) = min( max( pt2(1), 1), size(fd.data,2)); pt2(2) = min( max( pt2(2), 1), size(fd.data,1)); wp = abs(pt1(1)-pt2(1)); if ( wp == 0 ) wp = eps; end hp = abs(pt1(2)-pt2(2)); if ( hp == 0 ) hp = eps; end if ( (pt1(1)>pt2(1)) && (pt1(2)>pt2(2)) ) xp = pt2(1); yp = pt2(2); elseif ( (pt1(1)>=pt2(1)) && (pt1(2)<=pt2(2)) ) xp = pt2(1); yp = pt1(2); elseif ( (pt1(1)<=pt2(1)) && (pt1(2)>=pt2(2)) ) xp = pt1(1); yp = pt2(2); else xp = pt1(1); yp = pt1(2); end set(h,'Position',[xp,yp,wp,hp]); %-- save rectangle position fd.handleRect{end} = h; set(ud.imageId,'userdata',fd); %------------------------------------------------------------------ function stopdragrectangle(src,evt) %-- get structures fig = findobj(0,'tag','creaseg'); ud = get(fig,'userdata'); fd = get(ud.imageId,'userdata'); color = ud.colorSpec(get(ud.handleContourColor,'userdata')); if ~isempty(fd.handleRect) set(fd.handleRect{1},'Linewidth',2,'EdgeColor',color{1},'LineStyle','-'); end %-- create rectangle mask if ( size(fd.handleRect,2) > 0 ) rect = get(fd.handleRect{1},'Position'); fd.levelset = roipoly(fd.data,[rect(1),rect(1),min(rect(1)+rect(3),size(fd.data,1)),min(rect(1)+rect(3),size(fd.data,1))]... ,[rect(2),min(rect(2)+rect(4),size(fd.data,2)),min(rect(2)+rect(4),size(fd.data,2)),rect(2)]); end %-- save initialization info ud.LastPlot = 'levelset'; fd.method = 'Initial region'; %-- save structure set(ud.imageId,'userdata',fd); set(ud.gcf,'userdata',ud); %-- switch off the interactive rectangle mode set(ud.gcf,'WindowButtonMotionFcn',{@creaseg_mouseMove}); %------------------------------------------------------------------ function stopdragmultirectangle(src,evt) %-- get structures fig = findobj(0,'tag','creaseg'); ud = get(fig,'userdata'); fd = get(ud.imageId,'userdata'); %-- dislpay last final rectangle in "color" color = ud.colorSpec(get(ud.handleContourColor,'userdata')); if ~isempty(fd.handleRect) set(fd.handleRect{end},'Linewidth',2,'EdgeColor',color{1},'LineStyle','-'); end %-- create multirectangle mask if ( size(fd.handleRect,2) > 0 ) rect = get(fd.handleRect{end},'Position'); fd.levelset = xor(roipoly(fd.data,[rect(1),rect(1),rect(1)+rect(3),rect(1)+rect(3)]... ,[rect(2),rect(2)+rect(4),rect(2)+rect(4),rect(2)]),fd.levelset); end %-- save initialization info ud.LastPlot = 'levelset'; fd.method = 'Initial region'; %-- save structure set(ud.imageId,'userdata',fd); set(ud.gcf,'userdata',ud); %-- switch off the interactive rectangle mode set(ud.gcf,'WindowButtonMotionFcn',{@creaseg_mouseMove}); %------------------------------------------------------------------ function startdragellipse(src,evt) %-- get structures fig = findobj(0,'tag','creaseg'); ud = get(fig,'userdata'); fd = get(ud.imageId,'userdata'); pos = floor(get(ud.gca(1),'CurrentPoint')); if ~( pos(1,1) < size(fd.data,2) && pos(1,1) > 1 && pos(1,2) < size(fd.data,1) && pos(1,2) >1 ) % Clic outside the image if ( size(fd.handleElliRect,2)>0 ) delete(fd.handleElliRect{1}(2)); fd.handleElliRect(1)=[]; end set(ud.imageId,'userdata',fd); return; end %-- clean image overlay if ( size(fd.handleElliRect,2)>0 ) delete(fd.handleElliRect{1}(2)); fd.handleElliRect(1)=[]; end %-- initialize enclosing rectangle display pt = get(ud.gca,'CurrentPoint'); pt = pt(1,1:2); h1 = rectangle('Position',[pt(1),pt(2),1,1],'Linewidth',1,'EdgeColor','y','LineStyle','--'); color = ud.colorSpec(get(ud.handleContourColor,'userdata')); hold on; h2 = plot(pt(1),pt(2),'-','color',color{1},'linewidth',2); %-- save rectangle position fd.handleElliRect{1} = [h1;h2]; set(ud.imageId,'userdata',fd); %-- initialize the interactive rectangle display set(ud.gcf,'WindowButtonMotionFcn',{@dragellipse,pt}); %------------------------------------------------------------------ function startdragmultiellipse(src,evt) %-- get structures fig = findobj(0,'tag','creaseg'); ud = get(fig,'userdata'); fd = get(ud.imageId,'userdata'); pos = floor(get(ud.gca(1),'CurrentPoint')); if ~( pos(1,1) < size(fd.data,2) && pos(1,1) > 1 && pos(1,2) < size(fd.data,1) && pos(1,2) >1 ) % Clic outside the image if ( size(fd.handleElliRect,2)>0 ) delete(fd.handleElliRect{1}(2)); fd.handleElliRect(1)=[]; end set(ud.imageId,'userdata',fd); return; end %-- initialize enclosing rectangle display pt = get(ud.gca,'CurrentPoint'); pt = pt(1,1:2); h1 = rectangle('Position',[pt(1),pt(2),1,1],'Linewidth',1,'EdgeColor','y','LineStyle','--'); color = ud.colorSpec(get(ud.handleContourColor,'userdata')); hold on; h2 = plot(pt(1),pt(2),'-','color',color{1},'linewidth',2); %-- save rectangle position fd.handleElliRect{end+1} = [h1;h2]; set(ud.imageId,'userdata',fd); %-- initialize the interactive rectangle display set(ud.gcf,'WindowButtonMotionFcn',{@dragellipse,pt}); %------------------------------------------------------------------ function dragellipse(varargin) %-- get structures fig = findobj(0,'tag','creaseg'); ud = get(fig,'userdata'); fd = get(ud.imageId,'userdata'); %-- pt1 = varargin{3}; pt2 = get(ud.gca,'CurrentPoint'); pt2 = pt2(1,1:2); wp = abs(pt1(1)-pt2(1)); if ( wp == 0 ) wp = eps; end hp = abs(pt1(2)-pt2(2)); if ( hp == 0 ) hp = eps; end if ( (pt1(1)>pt2(1)) && (pt1(2)>pt2(2)) ) xp = pt2(1); yp = pt2(2); elseif ( (pt1(1)>=pt2(1)) && (pt1(2)<=pt2(2)) ) xp = pt2(1); yp = pt1(2); elseif ( (pt1(1)<=pt2(1)) && (pt1(2)>=pt2(2)) ) xp = pt1(1); yp = pt2(2); else xp = pt1(1); yp = pt1(2); end set(fd.handleElliRect{end}(1),'Position',[xp,yp,wp,hp]); %-- save rectangle position and draw embedded ellipse [X,Y] = computeEllipse(xp,yp,wp,hp); set(fd.handleElliRect{end}(2),'X',X,'Y',Y); set(ud.imageId,'userdata',fd); %------------------------------------------------------------------ function stopdragellipse(src,evt) %-- get structures fig = findobj(0,'tag','creaseg'); ud = get(fig,'userdata'); fd = get(ud.imageId,'userdata'); %-- delete enclosing rectangle if ( size(fd.handleElliRect,2)> 0 ) delete(fd.handleElliRect{end}(1)); end %-- create ellipse mask if ( size(fd.handleElliRect,2) > 0 ) X = get(fd.handleElliRect{1}(2),'X'); Y = get(fd.handleElliRect{1}(2),'Y'); fd.levelset = roipoly(fd.data,X,Y); end %-- save initialization info ud.LastPlot = 'levelset'; fd.method = 'Initial region'; %-- save structure set(ud.imageId,'userdata',fd); set(ud.gcf,'userdata',ud); %-- switch off the interactive rectangle mode set(ud.gcf,'WindowButtonMotionFcn',{@creaseg_mouseMove}); %------------------------------------------------------------------ function stopdragmultiellipse(src,evt) %-- get structures fig = findobj(0,'tag','creaseg'); ud = get(fig,'userdata'); fd = get(ud.imageId,'userdata'); %-- delete enclosing rectangle if ( size(fd.handleElliRect,2)> 0 ) delete(fd.handleElliRect{end}(1)); end %-- create multi-ellipse mask if ( size(fd.handleElliRect,2) > 0 ) X = get(fd.handleElliRect{end}(2),'X'); Y = get(fd.handleElliRect{end}(2),'Y'); fd.levelset = xor(roipoly(fd.data,X,Y),fd.levelset); end %-- save initialization info ud.LastPlot = 'levelset'; fd.method = 'Initial region'; %-- save structure set(ud.imageId,'userdata',fd); set(ud.gcf,'userdata',ud); %-- switch off the interactive rectangle mode set(ud.gcf,'WindowButtonMotionFcn',{@creaseg_mouseMove}); %------------------------------------------------------------------ %-- Draw Ellipse from rectangle info function [X,Y] = computeEllipse(x,y,w,h) %-- determine major axis xa = [x+w/2,x+w/2]; ya = [y,y+h]; %-- determine minor axis xi = [x,x+w]; yi = [y+h/2,y+h/2]; %-- determine centroid based on major axis selection x0 = mean(xa); y0 = mean(ya); %-- determine a and b from user input a = sqrt(diff(xa)^2 + diff(ya)^2)/2; b = sqrt(diff(xi)^2 + diff(yi)^2)/2; %-- determine rho based on major axis selection rho = atan(diff(xa)/diff(ya)); %-- prepare display theta = [-0.03:0.01:2*pi]; %-- Parametric equation of the ellipse %---------------------------------------- x = a*cos(theta); y = b*sin(theta); %-- Coordinate transform %---------------------------------------- Y = cos(rho)*x - sin(rho)*y; X = sin(rho)*x + cos(rho)*y; X = X + x0; Y = Y + y0; % %------------------------------------------------------------------ % function drawMultiManualContours(src,evt) % % %-- get structures % fig = findobj(0,'tag','creaseg'); % ud = get(fig,'userdata'); % fd = get(ud.imageId,'userdata'); % % pos = floor(get(ud.gca(1),'CurrentPoint')); % if ~( pos(1,1) < size(fd.data,2) && pos(1,1) > 1 && pos(1,2) < size(fd.data,1) && pos(1,2) >1 ) % return; %Clic outside the image => do nothing % end % % if ( strcmp(get(ud.gcf,'SelectionType'),'normal') ) % % %-- disable run, pointer and pan button % set(ud.buttonAction(2),'enable','off'); % set(ud.buttonAction(3),'enable','off'); % set(ud.buttonAction(6),'enable','off'); % % %-- delete any overlay lines % if ( size(fd.handleManual,2)>0 ) % for k=1:size(fd.handleManual{end},1) % if ( fd.handleManual{end}(k) ~= 0 ) % delete(fd.handleManual{end}(k)); % end % end % else % fd.handleManual{1} = 0; % end % % %-- Get point coordinates % pt = get(ud.gca,'CurrentPoint'); % pt = pt(1,1:2); % if (isempty(fd.points)) % fd.points = [pt(1),pt(2)]; % hold on; h = plot(pt(1), pt(2), 'oy', 'linewidth', 2); % fd.handleManual{end} = h; % else % fd.points(end+1,:) = [pt(1),pt(2)]; % color = ud.colorSpec(get(ud.handleContourColor,'userdata')); % % switch ud.Spline % case 0 % hold on; h1 = plot(fd.points(:,1),fd.points(:,2),'--','color',color{1},'Linewidth',2); % tmp = fd.points(1,:); tmp(end+1,:) = fd.points(end,:); % h2 = plot(tmp(:,1), tmp(:,2), 'y--', 'linewidth', 2); % case 1 % if size(fd.points,1) == 2 % spline = cscvn([[fd.points(:,2); fd.points(1,2)]'; [fd.points(:,1); fd.points(1,1)]']); % A = fnplt(spline,'.'); % hold on; h2 = plot(A(2,:),A(1,:),'y--','Linewidth',2); % h1 = []; % else % spline = cscvn([[fd.points(:,2); fd.points(1,2)]'; [fd.points(:,1); fd.points(1,1)]']); % A = fnplt(spline,'.'); % a = find(A(2,:) == fd.points(end,1),1); % hold on; h1 = plot(A(2,1:a),A(1,1:a),'--','color',color{1},'Linewidth',2); % h2 = plot(A(2,a:end),A(1,a:end),'y--','Linewidth',2); % end % end % % h3 = plot(fd.points(:,1), fd.points(:,2), 'oy', 'linewidth', 2); % hold off; % fd.handleManual{end} = [h1;h2;h3]; % end % % % else %-- create final contour % % %-- enable run, pointer and pan button % set(ud.buttonAction(2),'enable','on'); % set(ud.buttonAction(3),'enable','on'); % set(ud.buttonAction(6),'enable','on'); % % %-- display final contour % if ( size(fd.points,1)>2 ) % %-- delete any overlay lines % if ( size(fd.handleManual,2)>0 ) % for k=1:size(fd.handleManual{end},1) % delete(fd.handleManual{end}(k)); % end % end % %-- % tmp = fd.points; % tmp(end+1,:) = tmp(1,:); % color = ud.colorSpec(get(ud.handleContourColor,'userdata')); % % switch ud.Spline % case 0 % hold on; h = plot(tmp(:,1),tmp(:,2),'color',color{1},'Linewidth',2); hold off; % case 1 % spline = cscvn([tmp(:,2)'; tmp(:,1)']); % A = fnplt(spline,'.'); % hold on; h = plot(A(2,:),A(1,:),'color',color{1},'Linewidth',2); hold off; % end % fd.handleManual{end} = h; % %-- create manual mask % X = get(fd.handleManual{end},'X'); % Y = get(fd.handleManual{end},'Y'); % fd.levelset = xor(roipoly(fd.data,X,Y),fd.levelset); % %-- save initialization info % ud.LastPlot = 'levelset'; % fd.method = 'Initial region'; % %-- prepare next contour % fd.handleManual{end+1} = 0; % end % fd.points = []; % % end % % %-- save structure % set(ud.imageId,'userdata',fd); % set(ud.gcf,'userdata',ud); %------------------------------------------------------------------ function displayDrawingInfo(ud,flag,var) if (~flag) switch var case 1 %-- draw rectangle set(ud.txtInfo1,'string',sprintf('Click and drag \nto draw a rectangle'),'color','y'); set(ud.txtInfo2,'string',''); set(ud.txtInfo3,'string',''); set(ud.txtInfo4,'string',''); set(ud.txtInfo5,'string',''); case 2 %-- draw ellipse set(ud.txtInfo1,'string',sprintf('Click and drag \nto draw an ellipse'),'color','y'); set(ud.txtInfo2,'string',''); set(ud.txtInfo3,'string',''); set(ud.txtInfo4,'string',''); set(ud.txtInfo5,'string',''); case 3 %-- draw manual points set(ud.txtInfo1,'string',sprintf('Left click to add a point\nRight click to end'),'color','y'); set(ud.txtInfo2,'string',''); set(ud.txtInfo3,'string',''); set(ud.txtInfo4,'string',''); set(ud.txtInfo5,'string',''); case 4 %-- draw multi-rectangle set(ud.txtInfo1,'string',sprintf('Click and drag \nto draw multi-rectangles'),'color','y'); set(ud.txtInfo2,'string',''); set(ud.txtInfo3,'string',''); set(ud.txtInfo4,'string',''); set(ud.txtInfo5,'string',''); case 5 %-- draw multi-ellipse set(ud.txtInfo1,'string',sprintf('Click and drag \nto draw multi-ellipses'),'color','y'); set(ud.txtInfo2,'string',''); set(ud.txtInfo3,'string',''); set(ud.txtInfo4,'string',''); set(ud.txtInfo5,'string',''); case 6 %-- draw multi-manual points set(ud.txtInfo1,'string',sprintf('Left click to add a point\nRight click to end'),'color','y'); set(ud.txtInfo2,'string',''); set(ud.txtInfo3,'string',''); set(ud.txtInfo4,'string',''); set(ud.txtInfo5,'string',''); end end
github
jacksky64/imageProcessing-master
creaseg_run.m
.m
imageProcessing-master/segmentation/creaseg/creaseg/creaseg/src/creaseg_run.m
20,056
utf_8
e09b5d345491ea24c5125c3d878c9766
% Copyright or © or Copr. CREATIS laboratory, Lyon, France. % % Contributor: Olivier Bernard, Associate Professor at the french % engineering university INSA (Institut National des Sciences Appliquees) % and a member of the CREATIS-LRMN laboratory (CNRS 5220, INSERM U630, % INSA, Claude Bernard Lyon 1 University) in France (Lyon). % % Date of creation: 8th of October 2009 % % E-mail of the author: [email protected] % % This software is a computer program whose purpose is to evaluate the % performance of different level-set based segmentation algorithms in the % context of image processing (and more particularly on biomedical % images). % % The software has been designed for two main purposes. % - firstly, CREASEG allows you to use six different level-set methods. % These methods have been chosen in order to work with a wide range of % level-sets. You can select for instance classical methods such as % Caselles or Chan & Vese level-set, or more recent approaches such as the % one developped by Lankton or Bernard. % - finally, the software allows you to compare the performance of the six % level-set methods on different images. The performance can be evaluated % either visually, or from measurements (either using the Dice coefficient % or the PSNR value) between a reference and the results of the % segmentation. % % The level-set segmentation platform is citationware. If you are % publishing any work, where this program has been used, or which used one % of the proposed level-set algorithms, please remember that it was % obtained free of charge. You must reference the papers shown below and % the name of the CREASEG software must be mentioned in the publication. % % CREASEG software % "T. Dietenbeck, M. Alessandrini, D. Friboulet, O. Bernard. CREASEG: a % free software for the evaluation of image segmentation algorithms based % on level-set. In IEEE International Conference On Image Processing. % Hong Kong, China, 2010." % % Bernard method % "O. Bernard, D. Friboulet, P. Thevenaz, M. Unser. Variational B-Spline % Level-Set: A Linear Filtering Approach for Fast Deformable Model % Evolution. In IEEE Transactions on Image Processing. volume 18, no. 06, % pp. 1179-1191, 2009." % % Caselles method % "V. Caselles, R. Kimmel, and G. Sapiro. Geodesic active contours. % International Journal of Computer Vision, volume 22, pp. 61-79, 1997." % % Chan & Vese method % "T. Chan and L. Vese. Active contours without edges. IEEE Transactions on % Image Processing. volume10, pp. 266-277, February 2001." % % Lankton method % "S. Lankton, A. Tannenbaum. Localizing Region-Based Active Contours. In % IEEE Transactions on Image Processing. volume 17, no. 11, pp. 2029-2039, % 2008." % % Li method % "C. Li, C.Y. Kao, J.C. Gore, Z. Ding. Minimization of Region-Scalable % Fitting Energy for Image Segmentation. In IEEE Transactions on Image % Processing. volume 17, no. 10, pp. 1940-1949, 2008." % % Shi method % "Yonggang Shi, William Clem Karl. A Real-Time Algorithm for the % Approximation of Level-Set-Based Curve Evolution. In IEEE Transactions % on Image Processing. volume 17, no. 05, pp. 645-656, 2008." % % This software is governed by the BSD license and % abiding by the rules of distribution of free software. % % As a counterpart to the access to the source code and rights to copy, % modify and redistribute granted by the license, users are provided only % with a limited warranty and the software's author, the holder of the % economic rights, and the successive licensors have only limited % liability. % % In this respect, the user's attention is drawn to the risks associated % with loading, using, modifying and/or developing or reproducing the % software by the user in light of its specific status of free software, % that may mean that it is complicated to manipulate, and that also % therefore means that it is reserved for developers and experienced % professionals having in-depth computer knowledge. Users are therefore % encouraged to load and test the software's suitability as regards their % requirements in conditions enabling the security of their systems and/or % data to be ensured and, more generally, to use and operate it in the % same conditions as regards security. % %------------------------------------------------------------------------ function creaseg_run(src,evt) %-- parameters fig = findobj(0,'tag','creaseg'); ud = get(fig,'userdata'); fd = get(ud.imageId,'userdata'); if ( isempty(fd.data) ) return; end if ( sum(fd.levelset(:)) == 0 ) set(ud.txtInfo1,'string',sprintf('Error: No initial contour has been given'),'color',[1 0 0]); return; end %-- deal with initialization mode set(ud.gcf,'WindowButtonDownFcn',''); set(ud.gcf,'WindowButtonUpFcn',''); for k=3:size(ud.handleInit,1) set(ud.handleInit(k),'BackgroundColor',[240/255 173/255 105/255]); end %-- fd.seg = []; img = fd.visu; levelset = fd.levelset; display = 1; color = ud.colorSpec(get(ud.handleContourColor,'userdata')); ud.LastPlot = 'levelset'; %-- set mouse pointer to watch set(fig,'pointer','watch'); drawnow; %-- invoke function that corresponds to the selected method numIts = 0; numMethod = find(strcmp(get(ud.handleIconAlgo,'State'),'on')); if isempty(numMethod) creaseg_cleanOverlays(); set(ud.txtInfo1,'string',sprintf('Error: No algorithm has been selected'),'color',[1 0 0]); set(fig,'pointer','arrow'); return else % Displaying the corresponding panel for k=1:size(ud.handleAlgoConfig,1) set(ud.handleAlgoConfig(k),'Visible','off'); if k<size(ud.handleAlgoConfig,1)-1 set(ud.handleIconAlgo(k),'State','off'); end end set(ud.handleAlgoConfig(numMethod),'Visible','on'); set(ud.handleIconAlgo(numMethod),'State','on'); end %-- clean overlays and update fd structure creaseg_cleanOverlays(); fd = get(ud.imageId,'userdata'); switch numMethod(1) case 1 %-- Caselles [seg,levelset,numIts] = run_caselles(ud,img,levelset,color,display); fd.method = 'Caselles'; case 2 %-- Chan & Vese [seg,levelset,numIts] = run_chanvese(ud,img,levelset,color,display); fd.method = 'Chan & Vese'; case 3 %-- Chunming Li [seg,levelset,numIts] = run_chunmingli(ud,img,levelset,color,display); fd.method = 'Chunming Li'; case 4 %-- Lankton [seg,levelset,numIts] = run_lankton(ud,img,levelset,color,display); fd.method = 'Lankton'; case 5 %-- Bernard [seg,levelset,numIts] = run_bernard(ud,img,levelset,color,display); fd.method = 'Bernard'; case 6 %-- Shi [seg,levelset,numIts] = run_shi(ud,img,levelset,color,display); fd.method = 'Shi'; case 7 %-- Personal % [seg,levelset,numIts] = run_personal(ud,img,levelset,color,display); % fd.method = 'Personal'; case {8, 9} %-- Comparison test = 0; for i=1:1:7 test = test + get(ud.handleAlgoComparison(6+i),'Value'); end if test ~= 0 % Checking if at least one algorithm has been selected if max(fd.reference(:)) ~= 0 % Checking if a reference has been given % Displaying the Results panel for k=1:size(ud.handleAlgoConfig,1) set(ud.handleAlgoConfig(k),'Visible','off'); if k<size(ud.handleAlgoConfig,1)-1 set(ud.handleIconAlgo(k),'State','off'); end end set(ud.handleAlgoConfig(9),'Visible','on'); set(ud.handleIconAlgo(8),'State','on'); % Enabling the visual check boxes and reseting them set(ud.handleAlgoResults(5),'Value',1); for i=1:1:7 if get(ud.handleAlgoComparison(6+i),'Value') set(ud.handleAlgoResults(5+i),'Enable','on'); set(ud.handleAlgoResults(5+i),'Value',1); else set(ud.handleAlgoResults(5+i),'Enable','off'); set(ud.handleAlgoResults(5+i),'Value',0); end end % Running the comparison fd.seg = run_comp(ud,img,levelset,color); fd.method = 'Comparison'; %-- UPDATE FD AND UD STRUCTURES ATTACHED TO IMAGEID AND FIG HANDLES set(ud.imageId,'userdata',fd); set(fig,'userdata',ud); % Showing all contours creaseg_plotresults(src,evt) set(ud.handleAlgoComparison(24),'Enable','on'); set(ud.txtInfo1,'string','','color',[1 1 0]); ud.LastPlot = 'results'; else axes(get(ud.imageId,'parent')); delete(findobj(get(ud.imageId,'parent'),'type','line')); set(ud.txtInfo1,'string',sprintf('Error: No reference has been given'),'color',[1 0 0]); end else axes(get(ud.imageId,'parent')); delete(findobj(get(ud.imageId,'parent'),'type','line')); set(ud.txtInfo1,'string',sprintf('Error: No algorithm has been selected'),'color',[1 0 0]); end end %-- UPDATE FD AND UD STRUCTURES ATTACHED TO IMAGEID AND FIG HANDLES fd.levelset = levelset; set(ud.imageId,'userdata',fd); set(fig,'userdata',ud); %-- set mouse pointer to arrow set(fig,'pointer','arrow'); %-- put pointer button to select set(ud.buttonAction(3),'BackgroundColor',[160/255 130/255 95/255]); %-- if numMethod<8 set(ud.txtInfo1,'string',sprintf('End of run in %2d its',numIts),'color',[1 1 0]); end %--------------------------------------------------------------------- %-- AUXILIARY FUNCTIONS ---------------------------------------------- %--------------------------------------------------------------------- function [seg,levelset,numIts] = run_caselles(ud,img,levelset,color,display) %-- Caselles max_its = str2double(get(ud.handleAlgoCaselles(4),'string')); thresh = str2double(get(ud.handleAlgoCaselles(6),'string')); propag = str2double(get(ud.handleAlgoCaselles(10),'string')); %-- set(ud.txtInfo2,'string',sprintf('Caselles'),'color',[1 1 0]); [seg,levelset,numIts] = creaseg_caselles(img,levelset,max_its,propag,thresh,color,display); function [seg,levelset,numIts] = run_chanvese(ud,img,levelset,color,display) %-- Chan & Vese max_its = str2double(get(ud.handleAlgoChanVese(4),'string')); thresh = str2double(get(ud.handleAlgoChanVese(6),'string')); curvature = str2double(get(ud.handleAlgoChanVese(10),'string')); %-- set(ud.txtInfo2,'string',sprintf('Chan & Vese'),'color',[1 1 0]); [seg,levelset,numIts] = creaseg_chanvese(img,levelset,max_its,curvature,thresh,color,display); function [seg,levelset,numIts] = run_chunmingli(ud,img,levelset,color,display) %-- Chunming Li max_its = str2double(get(ud.handleAlgoLi(4),'string')); thresh = str2double(get(ud.handleAlgoLi(6),'string')); length = str2double(get(ud.handleAlgoLi(10),'string')); regularization = str2double(get(ud.handleAlgoLi(12),'string')); scale = str2double(get(ud.handleAlgoLi(14),'string')); %-- set(ud.txtInfo2,'string',sprintf('Li'),'color',[1 1 0]); [seg,levelset,numIts] = creaseg_chunmingli(img,levelset,max_its,length,regularization,scale,thresh,color,display); function [seg,levelset,numIts] = run_lankton(ud,img,levelset,color,display) %-- Lankton max_its = str2double(get(ud.handleAlgoLankton(4),'string')); thresh = str2double(get(ud.handleAlgoLankton(6),'string')); method = get(ud.handleAlgoLankton(10),'value'); neigh = get(ud.handleAlgoLankton(12),'value'); curvature = str2double(get(ud.handleAlgoLankton(14),'string')); radius = str2double(get(ud.handleAlgoLankton(16),'string')); %-- set(ud.txtInfo2,'string',sprintf('Lankton'),'color',[1 1 0]); [seg,levelset,numIts] = creaseg_lankton(img,levelset,max_its,radius,curvature,thresh,method,neigh,color,display); function [seg,levelset,numIts] = run_bernard(ud,img,levelset,color,display) %-- Bernard max_its = str2double(get(ud.handleAlgoBernard(4),'string')); thresh = str2double(get(ud.handleAlgoBernard(6),'string')); scale = str2double(get(ud.handleAlgoBernard(10),'string')); %-- set(ud.txtInfo2,'string',sprintf('Bernard'),'color',[1 1 0]); [seg,levelset,numIts] = creaseg_bernard(img,levelset,max_its,scale,thresh,color,display); function [seg,levelset,numIts] = run_shi(ud,img,levelset,color,display) %-- Shi max_its = str2double(get(ud.handleAlgoShi(4),'string')); na = str2double(get(ud.handleAlgoShi(8),'string')); ns = str2double(get(ud.handleAlgoShi(10),'string')); sigma = str2double(get(ud.handleAlgoShi(12),'string')); ng = str2double(get(ud.handleAlgoShi(14),'string')); %-- set(ud.txtInfo2,'string',sprintf('Shi'),'color',[1 1 0]); [seg,levelset,numIts] = creaseg_shi(img,levelset,max_its,na,ns,sigma,ng,color,display); % function [seg,levelset,numIts] = run_personal(ud,img,levelset,color,display) % max_its = str2double(get(ud.handleAlgoPersonal(4),'string')); % thresh = str2double(get(ud.handleAlgoPersonal(6),'string')); % parameter1 = str2double(get(ud.handleAlgoPersonal(10),'string')); % parameter2 = str2double(get(ud.handleAlgoPersonal(12),'string')); % %-- Run your personal method here % set(ud.txtInfo2,'string',sprintf('Personal Algorithm'),'color',[1 1 0]); % set(ud.txtInfo2,'string',sprintf(''),'color',[1 1 0]); function seg = run_comp(ud,img,levelset,color) %-- Comparison fd = get(ud.imageId,'userdata'); seg = zeros(size(img,1),size(img,2),7); res = zeros(7,2); d = get(ud.handleAlgoComparison(22),'Value'); if ud.Version set(ud.handleAlgoResults(2), 'Data', res); switch d % switching depending on the selected criteria case 1 % displaying its name in the table name = get(ud.handleAlgoResults(2), 'ColumnName'); name(2) = {'Dice'}; set(ud.handleAlgoResults(2), 'ColumnName', name); case 2 name = get(ud.handleAlgoResults(2), 'ColumnName'); name(2) = {'PSNR'}; set(ud.handleAlgoResults(2), 'ColumnName', name); case 3 name = get(ud.handleAlgoResults(2), 'ColumnName'); name(2) = {'Hausdorff'}; set(ud.handleAlgoResults(2), 'ColumnName', name); case 4 name = get(ud.handleAlgoResults(2), 'ColumnName'); name(2) = {'MSSD'}; set(ud.handleAlgoResults(2), 'ColumnName', name); end end display = get(ud.handleAlgoComparison(23),'Value'); if get(ud.handleAlgoComparison(7),'Value') %-- Caselles tic; [junk,seg(:,:,1)] = run_caselles(ud,img,levelset,color,display); res(1,1) = toc; res(1,2) = distance(fd.reference, seg(:,:,1), d); end if get(ud.handleAlgoComparison(8),'Value') %-- Chan & Vese tic; [junk,seg(:,:,2)] = run_chanvese(ud,img,levelset,color,display); res(2,1) = toc; res(2,2) = distance(fd.reference, seg(:,:,2), d); end if get(ud.handleAlgoComparison(9),'Value') %-- Chunming Li tic; [junk,seg(:,:,3)] = run_chunmingli(ud,img,levelset,color,display); res(3,1) = toc; res(3,2) = distance(fd.reference, seg(:,:,3), d); end if get(ud.handleAlgoComparison(10),'Value') %-- Lankton tic; [junk,seg(:,:,4)] = run_lankton(ud,img,levelset,color,display); res(4,1) = toc; res(4,2) = distance(fd.reference, seg(:,:,4), d); end if get(ud.handleAlgoComparison(11),'Value') %-- Bernard tic; [junk,seg(:,:,5)] = run_bernard(ud,img,levelset,color,display); res(5,1) = toc; res(5,2) = distance(fd.reference, seg(:,:,5), d); end if get(ud.handleAlgoComparison(12),'Value') %-- Shi tic; [junk,seg(:,:,6)] = run_shi(ud,img,levelset,color,display); res(6,1) = toc; res(6,2) = distance(fd.reference, seg(:,:,6), d); end % if get(ud.handleAlgoComparison(13),'Value') %-- Personal % tic; % [junk,seg(:,:,7)] = run_personal(ud,img,levelset,color,display); % res(7,1) = toc; % res(7,2) = distance(fd.reference, seg(:,:,7), d); % end set(ud.txtInfo2,'string','','color',[1 1 0]); if ud.Version set(ud.handleAlgoResults(2),'Data',res); end switch d case 1, dstr = 'Dice'; case 2, dstr = 'PSNR'; case 3, dstr = 'Hausdorff'; case 4, dstr = 'MSSD'; end save_results(res,dstr); function dist = distance(ref,img,d) % Function that call the correct distance function img = img <= 0; % Creating a mask from the LS function switch d case 1, dist = dist_Dice(ref,img); case 2, dist = dist_PSNR(ref,img); case 3, dist = dist_Hausdorff(ref,img); case 4, dist = dist_MSSD(ref,img); end function dist = dist_Dice(ref,img) % Calculation of the Dice Coefficient idx_img = find(img == 1); idx_ref = find(ref == 1); idx_inter = find((img == 1) & (ref == 1)); dist = 2*length(idx_inter)/(length(idx_ref)+length(idx_img)); function dist = dist_PSNR(ref,img) % Calculation of the PSNR [nrow, ncol] = size(ref); idx1 = find((ref == 1)&(img == 0)); idx2 = find((ref == 0)&(img == 1)); dist = (length(idx1)+length(idx2))/(nrow*ncol); dist = -10*log10(dist); function dist = dist_Hausdorff(ref,img) % Calculation of the Hausdorff distance % Create a distance function for the reference and result phi_ref = bwdist(ref)+bwdist(1-ref); phi_img = bwdist(img)+bwdist(1-img); % Get the reference and image contour se = strel('diamond',1); contour_ref = ref - imerode(ref,se); contour_img = img - imerode(img,se); dist = max(max(phi_ref(contour_img == 1)), max(phi_img(contour_ref == 1))); function dist = dist_MSSD(ref,img) % Calculation of the Mean Sum of Square Distance % Create a distance function for the reference and result phi_ref = bwdist(ref)+bwdist(1-ref); phi_img = bwdist(img)+bwdist(1-img); % Get the reference and image contour se = strel('diamond',1); contour_ref = ref - imerode(ref,se); contour_img = img - imerode(img,se); dist1 = sum(phi_ref(contour_img == 1).^2)/(sum(contour_img(:)) + eps); dist2 = sum(phi_img(contour_ref == 1).^2)/(sum(contour_ref(:)) + eps); dist = max(dist1,dist2); function save_results(res,dstr) % Open or create the .txt File fid = fopen('results/results.txt','w'); % Write the results fprintf(fid,'%s\t %s\t %s\n','Algorithm','Calculation Time', dstr); fprintf(fid,'%s\t \t %3.3f\t \t %1.3f\n','Caselles',res(1,1),res(1,2)); fprintf(fid,'%s\t \t %3.3f\t \t %1.3f\n','Chan & Vese',res(2,1),res(2,2)); fprintf(fid,'%s\t \t %3.3f\t \t %1.3f\n','Chunming Li',res(3,1),res(3,2)); fprintf(fid,'%s\t \t \t %3.3f\t \t %1.3f\n','Lankton',res(4,1),res(4,2)); fprintf(fid,'%s\t \t \t %3.3f\t \t %1.3f\n','Bernard',res(5,1),res(5,2)); fprintf(fid,'%s\t \t \t %3.3f\t \t %1.3f\n','Shi',res(6,1),res(6,2)); fprintf(fid,'%s\t \t %3.3\t \t %1.3f\n','Personal',res(7,1),res(7,2)); % Close the file fclose(fid);
github
jacksky64/imageProcessing-master
creaseg_gui.m
.m
imageProcessing-master/segmentation/creaseg/creaseg/creaseg/src/creaseg_gui.m
80,541
utf_8
4da6ba874bf11f79dbd19da0e148024e
% Copyright or © or Copr. CREATIS laboratory, Lyon, France. % % Contributor: Olivier Bernard, Associate Professor at the french % engineering university INSA (Institut National des Sciences Appliquees) % and a member of the CREATIS-LRMN laboratory (CNRS 5220, INSERM U630, % INSA, Claude Bernard Lyon 1 University) in France (Lyon). % % Date of creation: 8th of October 2009 % % E-mail of the author: [email protected] % % This software is a computer program whose purpose is to evaluate the % performance of different level-set based segmentation algorithms in the % context of image processing (and more particularly on biomedical % images). % % The software has been designed for two main purposes. % - firstly, CREASEG allows you to use six different level-set methods. % These methods have been chosen in order to work with a wide range of % level-sets. You can select for instance classical methods such as % Caselles or Chan & Vese level-set, or more recent approaches such as the % one developped by Lankton or Bernard. % - finally, the software allows you to compare the performance of the six % level-set methods on different images. The performance can be evaluated % either visually, or from measurements (either using the Dice coefficient % or the PSNR value) between a reference and the results of the % segmentation. % % The level-set segmentation platform is citationware. If you are % publishing any work, where this program has been used, or which used one % of the proposed level-set algorithms, please remember that it was % obtained free of charge. You must reference the papers shown below and % the name of the CREASEG software must be mentioned in the publication. % % CREASEG software % "T. Dietenbeck, M. Alessandrini, D. Friboulet, O. Bernard. CREASEG: a % free software for the evaluation of image segmentation algorithms based % on level-set. In IEEE International Conference On Image Processing. % Hong Kong, China, 2010." % % Bernard method % "O. Bernard, D. Friboulet, P. Thevenaz, M. Unser. Variational B-Spline % Level-Set: A Linear Filtering Approach for Fast Deformable Model % Evolution. In IEEE Transactions on Image Processing. volume 18, no. 06, % pp. 1179-1191, 2009." % % Caselles method % "V. Caselles, R. Kimmel, and G. Sapiro. Geodesic active contours. % International Journal of Computer Vision, volume 22, pp. 61-79, 1997." % % Chan & Vese method % "T. Chan and L. Vese. Active contours without edges. IEEE Transactions on % Image Processing. volume10, pp. 266-277, February 2001." % % Lankton method % "S. Lankton, A. Tannenbaum. Localizing Region-Based Active Contours. In % IEEE Transactions on Image Processing. volume 17, no. 11, pp. 2029-2039, % 2008." % % Li method % "C. Li, C.Y. Kao, J.C. Gore, Z. Ding. Minimization of Region-Scalable % Fitting Energy for Image Segmentation. In IEEE Transactions on Image % Processing. volume 17, no. 10, pp. 1940-1949, 2008." % % Shi method % "Yonggang Shi, William Clem Karl. A Real-Time Algorithm for the % Approximation of Level-Set-Based Curve Evolution. In IEEE Transactions % on Image Processing. volume 17, no. 05, pp. 645-656, 2008." % % This software is governed by the BSD license and % abiding by the rules of distribution of free software. % % As a counterpart to the access to the source code and rights to copy, % modify and redistribute granted by the license, users are provided only % with a limited warranty and the software's author, the holder of the % economic rights, and the successive licensors have only limited % liability. % % In this respect, the user's attention is drawn to the risks associated % with loading, using, modifying and/or developing or reproducing the % software by the user in light of its specific status of free software, % that may mean that it is complicated to manipulate, and that also % therefore means that it is reserved for developers and experienced % professionals having in-depth computer knowledge. Users are therefore % encouraged to load and test the software's suitability as regards their % requirements in conditions enabling the security of their systems and/or % data to be ensured and, more generally, to use and operate it in the % same conditions as regards security. % %------------------------------------------------------------------------ function creaseg_gui(ud) %-- Checking the Matlab version and if the Spline Toolbox is available a = ver; ud.Spline = 0; i = 1; while ( (i <= size(a,2)) && (~strcmp(a(i).Name,'MATLAB')) ) i = i+ 1; end idx = find(a(i).Version == '.'); v1 = str2double(a(i).Version(1:idx-1)); v2 = str2double(a(i).Version(idx+1:end)); if ( (v1 >= 7) && (v2 >= 6) ) ud.Version = 1; else ud.Version = 0; end ud.LastPlot = ''; %-- create main figure ss = get(0,'ScreenSize'); ud.gcf = figure('position',[300 200 ss(3)*2/3 ss(4)*2/3],'menubar','none','tag','creaseg','color',[87/255 86/255 84/255],'name','CREASEG','NumberTitle','off'); %-- create main menu h1 = uimenu('parent',ud.gcf,'label','File'); uimenu('parent',h1,'label','Open','callback','creaseg_loadimage'); uimenu('parent',h1,'label','Close','callback',{@closeInterface}); uimenu('parent',h1,'label','Save screen','callback',{@saveResult,1}); uimenu('parent',h1,'label','Save result','callback',{@saveResult,3},'separator','on'); %-- create Algorithm item submenu h1 = uimenu('parent',ud.gcf,'label','Algorithms'); h2 = uimenu('parent',h1,'label','1-Caselles','callback',{@manageAlgoItem,1},'ForegroundColor',[255/255, 0/255, 0/255],'Checked','on'); h3 = uimenu('parent',h1,'label','2-Chan & Vese','callback',{@manageAlgoItem,2}); h4 = uimenu('parent',h1,'label','3-Chunming Li','callback',{@manageAlgoItem,3}); h5 = uimenu('parent',h1,'label','4-Lankton','callback',{@manageAlgoItem,4}); h6 = uimenu('parent',h1,'label','5-Bernard','callback',{@manageAlgoItem,5}); h7 = uimenu('parent',h1,'label','6-Shi','callback',{@manageAlgoItem,6}); h8 = uimenu('parent',h1,'label','7-Personal Algorithm','callback',{@manageAlgoItem,7}); h9 = uimenu('parent',h1,'label','C-Comparison Mode','callback',{@manageCompItem,1},'separator','on'); ud.handleMenuAlgorithms = [h2;h3;h4;h5;h6;h7;h8;h9]; S = ['1-Caselles ';'2-Chan & Vese';'3-Chunming Li'; ... '4-Lankton ';'5-Bernard ';'6-Shi '; ... '7-Personal ';'C-Comparison ']; ud.handleMenuAlgorithmsName = cellstr(S); %-- create Tool item submenu h1 = uimenu('parent',ud.gcf,'label','Tool'); uimenu('parent',h1,'label','Draw Initial Region','callback',{@manageAction,1}); uimenu('parent',h1,'label','Run','callback','creaseg_run'); %-- create Help item submenu h1 = uimenu('parent',ud.gcf,'label','Help'); uimenu('parent',h1,'label','About Creaseg','callback',{@open_help}); uimenu('parent',h1,'label','About the author','callback',{@open_author},'separator','on'); %-- create Image Area ud.imagePanel = uipanel('units','normalized','position',[0.35 0.05 0.62 0.80],'BorderType','line','Backgroundcolor',[37/255 37/255 37/255],'HighlightColor',[0/255 0/255 0/255],'tag','imgPanel'); ud.gca = axes('parent',ud.imagePanel,'Tag','mainAxes','DataAspectRatio',[1 1 1],'units','normalized','position',[0.05 0.05 0.9 0.9],'visible','off','tag','mainAxes'); ud.img = image([1 256],[1 256],repmat(37/255,[256,256,3]),'parent',ud.gca,'Tag','mainImg'); axis(ud.gca,'equal'); set(ud.gca,'visible','off'); pos = get(ud.gca,'position'); colormap(gray(256)); ud.imageId = ud.img; ud.imageMask(1,:) = pos; ud.panelIcons = uipanel('parent',ud.gcf,'units','normalized','position',[0.35 0.87 0.42 0.08],'BorderType','line','Backgroundcolor',[113/255 113/255 113/255],'HighlightColor',[0/255 0/255 0/255],'tag','panelIcons','userdata',0); ud.panelText = uipanel('parent',ud.gcf,'units','normalized','position',[0.80 0.87 0.17 0.08],'BorderType','line','Backgroundcolor',[113/255 113/255 113/255],'HighlightColor',[0/255 0/255 0/255]); %-- load('misc/icons/drawInitialization.mat'); ha1 = uicontrol('parent',ud.panelIcons,'units','normalized','position',[0.10 0.25 0.08 0.5],'Style','pushbutton','CData',cdata,'Enable','On','BackgroundColor',[160/255 130/255 95/255],'tooltip','draw initial region','Callback',{@manageAction,1}); load('misc/icons/run2.mat'); ha2 = uicontrol('parent',ud.panelIcons,'units','normalized','position',[0.22 0.25 0.08 0.5],'Style','pushbutton','CData',cdata,'Enable','On','Backgroundcolor',[240/255 173/255 105/255],'tooltip','Run','Callback',{@manageAction,2}); load('misc/icons/arrow.mat'); ha3 = uicontrol('parent',ud.panelIcons,'units','normalized','position',[0.34 0.25 0.08 0.5],'Style','pushbutton','CData',cdata,'Enable','On','BackgroundColor',[240/255 173/255 105/255],'tooltip','Pointer','Callback',{@manageAction,3}); load('misc/icons/zoomIn.mat'); ha4 = uicontrol('parent',ud.panelIcons,'units','normalized','position',[0.46 0.25 0.08 0.5],'Style','pushbutton','CData',cdata,'Enable','On','BackgroundColor',[240/255 173/255 105/255],'tooltip','Zoom In','Callback',{@manageAction,4}); load('misc/icons/zoomOut.mat'); ha5 = uicontrol('parent',ud.panelIcons,'units','normalized','position',[0.58 0.25 0.08 0.5],'Style','pushbutton','CData',cdata,'Enable','On','BackgroundColor',[240/255 173/255 105/255],'tooltip','Zoom Out','Callback',{@manageAction,5}); load('misc/icons/pan.mat'); ha6 = uicontrol('parent',ud.panelIcons,'units','normalized','position',[0.70 0.25 0.08 0.5],'Style','pushbutton','CData',cdata,'Enable','On','BackgroundColor',[240/255 173/255 105/255],'tooltip','Pan','Callback',{@manageAction,6}); load('misc/icons/info.mat'); ha7 = uicontrol('parent',ud.panelIcons,'units','normalized','position',[0.82 0.25 0.08 0.5],'Style','pushbutton','CData',cdata,'Enable','On','BackgroundColor',[240/255 173/255 105/255],'tooltip','Image Info','Callback',{@manageAction,7}); ud.buttonAction = [ha1;ha2;ha3;ha4;ha5;ha6;ha7]; %-- ud.txtPositionIntensity = uicontrol('parent',ud.panelText,'style','text','enable','inactive','fontsize',8,... 'backgroundcolor',[113/255 113/255 113/255],'foregroundcolor',[.9 .9 .9],'horizontalalignment','left'); SetTextIntensityPosition(ud); ud.txtInfo1 = text('Parent',ud.gca,'units','normalized','position',[0.05,0.95], ... 'string','','color',[255/255 255/255 0/255],'FontSize',8); ud.txtInfo2 = text('Parent',ud.gca,'units','normalized','position',[0.05,0.90], ... 'string','','color',[255/255 255/255 0/255],'FontSize',8); ud.txtInfo3 = text('Parent',ud.gca,'units','normalized','position',[0.05,0.85], ... 'string','','color',[255/255 255/255 0/255],'FontSize',8); ud.txtInfo4 = text('Parent',ud.gca,'units','normalized','position',[0.05,0.80], ... 'string','','color',[255/255 255/255 0/255],'FontSize',8); ud.txtInfo5 = text('Parent',ud.gca,'units','normalized','position',[0.05,0.75], ... 'string','','color',[255/255 255/255 0/255],'FontSize',8); %-- create Toolbar hToolbar = uitoolbar('Parent',ud.gcf,'HandleVisibility','callback'); load('misc/icons/open.mat'); uipushtool('Parent',hToolbar,'TooltipString','Open File','CData',cdata,'HandleVisibility','callback','ClickedCallback','creaseg_loadimage'); load('misc/icons/screenshot.mat'); uipushtool('Parent',hToolbar,'TooltipString','Save Screen','CData',cdata,'HandleVisibility','callback','ClickedCallback',{@saveResult,1}); load('misc/icons/save.mat'); uipushtool('Parent',hToolbar,'TooltipString','Save data','CData',cdata,'HandleVisibility','callback','ClickedCallback',{@saveResult,3}); load('misc/icons/one.mat'); ud.AlgoIcon(:,:,:,1) = cdata; hp1 = uitoggletool('Parent',hToolbar,'Separator','on','TooltipString','Caselles','State','On','CData',cdata,'HandleVisibility','callback','ClickedCallback',{@manageAlgoItem,1}); load('misc/icons/two.mat'); ud.AlgoIcon(:,:,:,2) = cdata; hp2 = uitoggletool('Parent',hToolbar,'TooltipString','ChanVese','CData',cdata,'HandleVisibility','callback','ClickedCallback',{@manageAlgoItem,2}); load('misc/icons/three.mat'); ud.AlgoIcon(:,:,:,3) = cdata; hp3 = uitoggletool('Parent',hToolbar,'TooltipString','Chunming Li','CData',cdata,'HandleVisibility','callback','ClickedCallback',{@manageAlgoItem,3}); load('misc/icons/four.mat'); ud.AlgoIcon(:,:,:,4) = cdata; hp4 = uitoggletool('Parent',hToolbar,'TooltipString','Lankton','CData',cdata,'HandleVisibility','callback','ClickedCallback',{@manageAlgoItem,4}); load('misc/icons/five.mat'); ud.AlgoIcon(:,:,:,5) = cdata; hp5 = uitoggletool('Parent',hToolbar,'TooltipString','Bernard','CData',cdata,'HandleVisibility','callback','ClickedCallback',{@manageAlgoItem,5}); load('misc/icons/six.mat'); ud.AlgoIcon(:,:,:,6) = cdata; hp6 = uitoggletool('Parent',hToolbar,'TooltipString','Shi','CData',cdata,'HandleVisibility','callback','ClickedCallback',{@manageAlgoItem,6}); load('misc/icons/seven.mat'); ud.AlgoIcon(:,:,:,7) = cdata; hp7 = uitoggletool('Parent',hToolbar,'TooltipString','Personal Algorithm','CData',cdata,'HandleVisibility','callback','ClickedCallback',{@manageAlgoItem,7}); load('misc/icons/comp.mat'); ud.AlgoIcon(:,:,:,8) = cdata; hp8 = uitoggletool('Parent',hToolbar,'Separator','on','TooltipString','Comparison Mode','CData',cdata,'HandleVisibility','callback','ClickedCallback',{@manageCompItem,1}); load('misc/icons/brushR.mat'); hp9 = uipushtool('Parent',hToolbar,'Separator','on','TooltipString','Change contour color','CData',cdata,'HandleVisibility','callback','userdata',1,'ClickedCallback',{@changeContourColor}); ud.handleContourColor = hp9; load('misc/icons/help.mat'); uipushtool('Parent',hToolbar,'Separator','on','TooltipString','Help','CData',cdata,'HandleVisibility','callback','userdata',1,'ClickedCallback',{@open_help}); ud.handleIconAlgo = [hp1;hp2;hp3;hp4;hp5;hp6;hp7;hp8]; ud.colorSpec = {'r','g','b','y','w','k'}; %-- Create Icon for selected algorithm (in Comparison Mode) load('misc/icons/oneSel.mat'); ud.AlgoIconSel(:,:,:,1) = cdata; load('misc/icons/twoSel.mat'); ud.AlgoIconSel(:,:,:,2) = cdata; load('misc/icons/threeSel.mat'); ud.AlgoIconSel(:,:,:,3) = cdata; load('misc/icons/fourSel.mat'); ud.AlgoIconSel(:,:,:,4) = cdata; load('misc/icons/fiveSel.mat'); ud.AlgoIconSel(:,:,:,5) = cdata; load('misc/icons/sixSel.mat'); ud.AlgoIconSel(:,:,:,6) = cdata; load('misc/icons/sevenSel.mat'); ud.AlgoIconSel(:,:,:,7) = cdata; %-- INTERFACE -> SEGMENTATION CONTROL h1 = uipanel('parent',ud.gcf,'position',[0.03 0.05 0.30 0.9],'Visible','off','BorderType','line','Backgroundcolor',[87/255 86/255 84/255],'HighlightColor',[0/255 0/255 0/255]); h2 = uipanel('parent',ud.gcf,'position',[0.03 0.05 0.30 0.9],'Visible','off','BorderType','line','Backgroundcolor',[87/255 86/255 84/255],'HighlightColor',[0/255 0/255 0/255]); h3 = uipanel('parent',ud.gcf,'position',[0.03 0.05 0.30 0.9],'Visible','off','BorderType','line','Backgroundcolor',[87/255 86/255 84/255],'HighlightColor',[0/255 0/255 0/255]); h4 = uipanel('parent',ud.gcf,'position',[0.03 0.05 0.30 0.9],'Visible','off','BorderType','line','Backgroundcolor',[87/255 86/255 84/255],'HighlightColor',[0/255 0/255 0/255]); h5 = uipanel('parent',ud.gcf,'position',[0.03 0.05 0.30 0.9],'Visible','off','BorderType','line','Backgroundcolor',[87/255 86/255 84/255],'HighlightColor',[0/255 0/255 0/255]); h6 = uipanel('parent',ud.gcf,'position',[0.03 0.05 0.30 0.9],'Visible','off','BorderType','line','Backgroundcolor',[87/255 86/255 84/255],'HighlightColor',[0/255 0/255 0/255]); h7 = uipanel('parent',ud.gcf,'position',[0.03 0.05 0.30 0.9],'Visible','off','BorderType','line','Backgroundcolor',[87/255 86/255 84/255],'HighlightColor',[0/255 0/255 0/255]); h8 = uipanel('parent',ud.gcf,'position',[0.03 0.05 0.30 0.9],'Visible','off','BorderType','line','Backgroundcolor',[87/255 86/255 84/255],'HighlightColor',[0/255 0/255 0/255]); h9 = uipanel('parent',ud.gcf,'position',[0.03 0.05 0.30 0.9],'Visible','off','BorderType','line','Backgroundcolor',[87/255 86/255 84/255],'HighlightColor',[0/255 0/255 0/255]); hi = uipanel('parent',ud.gcf,'position',[0.03 0.05 0.30 0.9],'BorderType','line','Backgroundcolor',[87/255 86/255 84/255],'HighlightColor',[0/255 0/255 0/255]); ud.handleAlgoConfig = [h1;h2;h3;h4;h5;h6;h7;h8;h9;hi]; %-- INTERFACE -> INITIALIZATION CONTROL hi1 = uicontrol('parent',hi,'units','normalized','position',[0 0.92 1 0.05],'Style','text','String','Initialization','FontSize',10,'HorizontalAlignment','center','Backgroundcolor',[87/255 86/255 84/255],'Foregroundcolor',[255/255 255/255 255/255]); hi2 = uipanel('parent',hi,'units','normalized','position',[0.07 0.05 0.85 0.85],'BorderType','line','Backgroundcolor',[113/255 113/255 113/255],'HighlightColor',[0/255 0/255 0/255]); load('misc/icons/rectangle.mat'); hi3 = uicontrol('parent',hi2,'units','normalized','position',[0.35 0.80 0.30 0.05],'Style','pushbutton','CData',cdata,'Enable','On','BackgroundColor',[240/255 173/255 105/255],'Callback',{@creaseg_managedrawing,1}); load('misc/icons/multirectangles.mat'); hi4 = uicontrol('parent',hi2,'units','normalized','position',[0.35 0.70 0.30 0.05],'Style','pushbutton','CData',cdata,'Enable','On','BackgroundColor',[240/255 173/255 105/255],'Callback',{@creaseg_managedrawing,2}); load('misc/icons/ellipse.mat'); hi5 = uicontrol('parent',hi2,'units','normalized','position',[0.35 0.60 0.30 0.05],'Style','pushbutton','CData',cdata,'Enable','On','BackgroundColor',[240/255 173/255 105/255],'Callback',{@creaseg_managedrawing,3}); load('misc/icons/multiellipses.mat'); hi6 = uicontrol('parent',hi2,'units','normalized','position',[0.35 0.50 0.30 0.05],'Style','pushbutton','CData',cdata,'Enable','On','BackgroundColor',[240/255 173/255 105/255],'Callback',{@creaseg_managedrawing,4}); load('misc/icons/manual.mat'); hi7 = uicontrol('parent',hi2,'units','normalized','position',[0.35 0.40 0.30 0.05],'Style','pushbutton','CData',cdata,'Enable','On','BackgroundColor',[240/255 173/255 105/255],'Callback',{@creaseg_managedrawing,5}); load('misc/icons/multimanuals.mat'); hi8 = uicontrol('parent',hi2,'units','normalized','position',[0.35 0.30 0.30 0.05],'Style','pushbutton','CData',cdata,'Enable','On','BackgroundColor',[240/255 173/255 105/255],'Callback',{@creaseg_managedrawing,6}); ud.handleInit = [hi1;hi2;hi3;hi4;hi5;hi6;hi7;hi8]; %-- INTERFACE -> CASELLES CONTROL h11 = uicontrol('parent',h1,'units','normalized','position',[0.0 0.92 1.0 0.05],'Style','text','String','Caselles','FontSize',10,'HorizontalAlignment','center','Backgroundcolor',[87/255 86/255 84/255],'Foregroundcolor',[255/255 255/255 255/255]); h12 = uipanel('parent',h1,'units','normalized','position',[0.07 0.75 0.85 0.15],'BorderType','line','Backgroundcolor',[113/255 113/255 113/255],'HighlightColor',[0/255 0/255 0/255]); h13 = uicontrol('parent',h12,'units','normalized','position',[0.07 0.58 0.5 0.23],'Style','text','String','Number of iterations','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[113/255 113/255 113/255]); h14 = uicontrol('parent',h12,'units','normalized','position',[0.60 0.61 0.3 0.23],'Style','edit','String','200','BackgroundColor',[240/255 173/255 105/255]); h15 = uicontrol('parent',h12,'units','normalized','position',[0.07 0.13 0.5 0.23],'Style','text','String','Convergence thres.','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[113/255 113/255 113/255]); h16 = uicontrol('parent',h12,'units','normalized','position',[0.60 0.16 0.3 0.23],'Style','edit','String','2','BackgroundColor',[240/255 173/255 105/255]); h17 = uicontrol('parent',h1,'units','normalized','position',[0.1 0.66 0.85 0.04],'Style','text','String','Specific parameters','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[87/255 86/255 84/255],'Foregroundcolor',[255/255 255/255 255/255]); h18 = uipanel('parent',h1,'units','normalized','position',[0.07 0.05 0.85 0.61],'BorderType','line','Backgroundcolor',[113/255 113/255 113/255],'HighlightColor',[0/255 0/255 0/255]); h181 = uicontrol('parent',h18,'units','normalized','position',[0.07 0.88 0.5 0.05],'Style','text','String','Propagation term','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[113/255 113/255 113/255]); h182 = uicontrol('parent',h18,'units','normalized','position',[0.55 0.88 0.3 0.055],'Style','edit','String','1','BackgroundColor',[240/255 173/255 105/255]); ud.handleAlgoCaselles = [h11;h12;h13;h14;h15;h16;h17;h18;h181;h182]; %-- INTERFACE -> CHAN VESE CONTROL h21 = uicontrol('parent',h2,'units','normalized','position',[0.0 0.92 1.0 0.05],'Style','text','String','Chan & Vese','FontSize',10,'HorizontalAlignment','center','Backgroundcolor',[87/255 86/255 84/255],'Foregroundcolor',[255/255 255/255 255/255]); h22 = uipanel('parent',h2,'units','normalized','position',[0.07 0.75 0.85 0.15],'BorderType','line','Backgroundcolor',[113/255 113/255 113/255],'HighlightColor',[0/255 0/255 0/255]); h23 = uicontrol('parent',h22,'units','normalized','position',[0.07 0.58 0.5 0.23],'Style','text','String','Number of iterations','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[113/255 113/255 113/255]); h24 = uicontrol('parent',h22,'units','normalized','position',[0.60 0.61 0.3 0.23],'Style','edit','String','200','BackgroundColor',[240/255 173/255 105/255]); h25 = uicontrol('parent',h22,'units','normalized','position',[0.07 0.13 0.5 0.23],'Style','text','String','Convergence thres.','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[113/255 113/255 113/255]); h26 = uicontrol('parent',h22,'units','normalized','position',[0.60 0.16 0.3 0.23],'Style','edit','String','2','units','normalized','BackgroundColor',[240/255 173/255 105/255]); h27 = uicontrol('parent',h2,'units','normalized','position',[0.1 0.66 0.85 0.04],'Style','text','String','Specific parameters','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[87/255 86/255 84/255],'Foregroundcolor',[255/255 255/255 255/255]); h28 = uipanel('parent',h2,'units','normalized','position',[0.07 0.05 0.85 0.61],'BorderType','line','Backgroundcolor',[113/255 113/255 113/255],'HighlightColor',[0/255 0/255 0/255]); h281 = uicontrol('parent',h28,'units','normalized','position',[0.07 0.88 0.5 0.05],'Style','text','String','Curvature term','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[113/255 113/255 113/255]); h282 = uicontrol('parent',h28,'units','normalized','position',[0.55 0.88 0.3 0.055],'Style','edit','String','0.2','BackgroundColor',[240/255 173/255 105/255]); ud.handleAlgoChanVese = [h21;h22;h23;h24;h25;h26;h27;h28;h281;h282]; %-- INTERFACE -> LI CONTROL h31 = uicontrol('parent',h3,'units','normalized','position',[0.0 0.92 1.0 0.05],'Style','text','String','Chunming Li','FontSize',10,'HorizontalAlignment','center','Backgroundcolor',[87/255 86/255 84/255],'Foregroundcolor',[255/255 255/255 255/255]); h32 = uipanel('parent',h3,'units','normalized','position',[0.07 0.75 0.85 0.15],'BorderType','line','Backgroundcolor',[113/255 113/255 113/255],'HighlightColor',[0/255 0/255 0/255]); h33 = uicontrol('parent',h32,'units','normalized','position',[0.07 0.58 0.5 0.23],'Style','text','String','Number of iterations','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[113/255 113/255 113/255]); h34 = uicontrol('parent',h32,'units','normalized','position',[0.60 0.61 0.3 0.23],'Style','edit','String','200','BackgroundColor',[240/255 173/255 105/255]); h35 = uicontrol('parent',h32,'units','normalized','position',[0.07 0.13 0.5 0.23],'Style','text','String','Convergence thres.','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[113/255 113/255 113/255]); h36 = uicontrol('parent',h32,'units','normalized','position',[0.60 0.16 0.3 0.23],'Style','edit','String','2','units','normalized','BackgroundColor',[240/255 173/255 105/255]); h37 = uicontrol('parent',h3,'units','normalized','position',[0.1 0.66 0.85 0.04],'Style','text','String','Specific parameters','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[87/255 86/255 84/255],'Foregroundcolor',[255/255 255/255 255/255]); h38 = uipanel('parent',h3,'units','normalized','position',[0.07 0.05 0.85 0.61],'BorderType','line','Backgroundcolor',[113/255 113/255 113/255],'HighlightColor',[0/255 0/255 0/255]); h39 = uicontrol('parent',h38,'units','normalized','position',[0.07 0.88 0.5 0.05],'Style','text','String','Length term','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[113/255 113/255 113/255]); h391 = uicontrol('parent',h38,'units','normalized','position',[0.55 0.88 0.3 0.055],'Style','edit','String','0.003','BackgroundColor',[240/255 173/255 105/255]); h392 = uicontrol('parent',h38,'units','normalized','position',[0.07 0.78 0.5 0.05],'Style','text','String','Regularization term','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[113/255 113/255 113/255]); h393 = uicontrol('parent',h38,'units','normalized','position',[0.55 0.78 0.3 0.055],'Style','edit','String','1','BackgroundColor',[240/255 173/255 105/255]); h394 = uicontrol('parent',h38,'units','normalized','position',[0.07 0.68 0.5 0.05],'Style','text','String','Scale term','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[113/255 113/255 113/255]); h395 = uicontrol('parent',h38,'units','normalized','position',[0.55 0.68 0.3 0.055],'Style','edit','String','7','BackgroundColor',[240/255 173/255 105/255]); ud.handleAlgoLi = [h31;h32;h33;h34;h35;h36;h37;h38;h39;h391;h392;h393;h394;h395]; %-- INTERFACE -> LANKTON CONTROL h41 = uicontrol('parent',h4,'units','normalized','position',[0.0 0.92 1.0 0.05],'Style','text','String','Lankton','FontSize',10,'HorizontalAlignment','center','Backgroundcolor',[87/255 86/255 84/255],'Foregroundcolor',[255/255 255/255 255/255]); h42 = uipanel('parent',h4,'units','normalized','position',[0.07 0.75 0.85 0.15],'BorderType','line','Backgroundcolor',[113/255 113/255 113/255],'HighlightColor',[0/255 0/255 0/255]); h43 = uicontrol('parent',h42,'units','normalized','position',[0.07 0.58 0.5 0.23],'Style','text','String','Number of iterations','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[113/255 113/255 113/255]); h44 = uicontrol('parent',h42,'units','normalized','position',[0.60 0.61 0.3 0.23],'Style','edit','String','200','BackgroundColor',[240/255 173/255 105/255]); h45 = uicontrol('parent',h42,'units','normalized','position',[0.07 0.13 0.5 0.23],'Style','text','String','Convergence thres.','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[113/255 113/255 113/255]); h46 = uicontrol('parent',h42,'units','normalized','position',[0.60 0.16 0.3 0.23],'Style','edit','String','2','units','normalized','BackgroundColor',[240/255 173/255 105/255]); h47 = uicontrol('parent',h4,'units','normalized','position',[0.1 0.66 0.85 0.04],'Style','text','String','Specific parameters','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[87/255 86/255 84/255],'Foregroundcolor',[255/255 255/255 255/255]); h48 = uipanel('parent',h4,'units','normalized','position',[0.07 0.05 0.85 0.61],'BorderType','line','Backgroundcolor',[113/255 113/255 113/255],'HighlightColor',[0/255 0/255 0/255]); h49 = uicontrol('parent',h48,'units','normalized','position',[0.07 0.88 0.5 0.05],'Style','text','String','Feature type','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[113/255 113/255 113/255]); h491 = uicontrol('parent',h48,'units','normalized','position',[0.55 0.90 0.39 0.04],'Style','popupmenu','String',{'Yezzi','Chan Vese'},'FontSize',9,'BackgroundColor',[240/255, 173/255, 105/255]); h492 = uicontrol('parent',h48,'units','normalized','position',[0.07 0.78 0.5 0.05],'Style','text','String','Neighborhood','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[113/255 113/255 113/255]); h493 = uicontrol('parent',h48,'units','normalized','position',[0.55 0.80 0.39 0.04],'Style','popupmenu','String',{'Circle','Square'},'FontSize',9,'BackgroundColor',[240/255, 173/255, 105/255]); h494 = uicontrol('parent',h48,'units','normalized','position',[0.07 0.68 0.5 0.05],'Style','text','String','Curvature term','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[113/255 113/255 113/255]); h495 = uicontrol('parent',h48,'units','normalized','position',[0.55 0.68 0.3 0.06],'Style','edit','String','0.2','BackgroundColor',[240/255 173/255 105/255]); h496 = uicontrol('parent',h48,'units','normalized','position',[0.07 0.58 0.5 0.05],'Style','text','String','Radius term','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[113/255 113/255 113/255]); h497 = uicontrol('parent',h48,'units','normalized','position',[0.55 0.58 0.3 0.06],'Style','edit','String','9','BackgroundColor',[240/255 173/255 105/255]); ud.handleAlgoLankton = [h41;h42;h43;h44;h45;h46;h47;h48;h49;h491;h492;h493;h494;h495;h496;h497]; %-- INTERFACE -> BERNARD CONTROL h51 = uicontrol('parent',h5,'units','normalized','position',[0.0 0.92 1.0 0.05],'Style','text','String','Bernard','FontSize',10,'HorizontalAlignment','center','Backgroundcolor',[87/255 86/255 84/255],'Foregroundcolor',[255/255 255/255 255/255]); h52 = uipanel('parent',h5,'units','normalized','position',[0.07 0.75 0.85 0.15],'BorderType','line','Backgroundcolor',[113/255 113/255 113/255],'HighlightColor',[0/255 0/255 0/255]); h53 = uicontrol('parent',h52,'units','normalized','position',[0.07 0.58 0.5 0.23],'Style','text','String','Number of iterations','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[113/255 113/255 113/255]); h54 = uicontrol('parent',h52,'units','normalized','position',[0.60 0.61 0.3 0.23],'Style','edit','String','200','BackgroundColor',[240/255 173/255 105/255]); h55 = uicontrol('parent',h52,'units','normalized','position',[0.07 0.13 0.5 0.23],'Style','text','String','Convergence thres.','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[113/255 113/255 113/255]); h56 = uicontrol('parent',h52,'units','normalized','position',[0.60 0.16 0.3 0.23],'Style','edit','String','2','units','normalized','BackgroundColor',[240/255 173/255 105/255]); h57 = uicontrol('parent',h5,'units','normalized','position',[0.1 0.66 0.85 0.04],'Style','text','String','Specific parameters','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[87/255 86/255 84/255],'Foregroundcolor',[255/255 255/255 255/255]); h58 = uipanel('parent',h5,'units','normalized','position',[0.07 0.05 0.85 0.61],'BorderType','line','Backgroundcolor',[113/255 113/255 113/255],'HighlightColor',[0/255 0/255 0/255]); h59 = uicontrol('parent',h58,'units','normalized','position',[0.07 0.88 0.5 0.05],'Style','text','String','Scale term','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[113/255 113/255 113/255]); h591 = uicontrol('parent',h58,'units','normalized','position',[0.55 0.88 0.3 0.055],'Style','edit','String','1','BackgroundColor',[240/255 173/255 105/255]); ud.handleAlgoBernard = [h51;h52;h53;h54;h55;h56;h57;h58;h59;h591]; %-- INTERFACE -> SHI CONTROL h61 = uicontrol('parent',h6,'units','normalized','position',[0.0 0.92 1.0 0.05],'Style','text','String','Shi','FontSize',10,'HorizontalAlignment','center','Backgroundcolor',[87/255 86/255 84/255],'Foregroundcolor',[255/255 255/255 255/255]); h62 = uipanel('parent',h6,'units','normalized','position',[0.07 0.83 0.85 0.07],'BorderType','line','Backgroundcolor',[113/255 113/255 113/255],'HighlightColor',[0/255 0/255 0/255]); h621 = uicontrol('parent',h62,'units','normalized','position',[0.07 0.2 0.5 0.5],'Style','text','String','Number of iterations','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[113/255 113/255 113/255]); h622 = uicontrol('parent',h62,'units','normalized','position',[0.60 0.25 0.3 0.5],'Style','edit','String','200','BackgroundColor',[240/255 173/255 105/255]); h63 = uicontrol('parent',h6,'units','normalized','position',[0.1 0.76 0.85 0.04],'Style','text','String','Specific parameters','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[87/255 86/255 84/255],'Foregroundcolor',[255/255 255/255 255/255]); h64 = uipanel('parent',h6,'units','normalized','position',[0.07 0.05 0.85 0.71],'BorderType','line','Backgroundcolor',[113/255 113/255 113/255],'HighlightColor',[0/255 0/255 0/255]); h641 = uicontrol('parent',h64,'units','normalized','position',[0.07 0.89 0.5 0.05],'Style','text','String','Na term','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[113/255 113/255 113/255]); h642 = uicontrol('parent',h64,'units','normalized','position',[0.55 0.90 0.3 0.047],'Style','edit','String','30','BackgroundColor',[240/255 173/255 105/255]); h643 = uicontrol('parent',h64,'units','normalized','position',[0.07 0.81 0.5 0.05],'Style','text','String','Ns term','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[113/255 113/255 113/255]); h644 = uicontrol('parent',h64,'units','normalized','position',[0.55 0.82 0.3 0.047],'Style','edit','String','3','BackgroundColor',[240/255 173/255 105/255]); h645 = uicontrol('parent',h64,'units','normalized','position',[0.07 0.73 0.5 0.05],'Style','text','String','Sigma term','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[113/255 113/255 113/255]); h646 = uicontrol('parent',h64,'units','normalized','position',[0.55 0.74 0.3 0.047],'Style','edit','String','3','BackgroundColor',[240/255 173/255 105/255]); h647 = uicontrol('parent',h64,'units','normalized','position',[0.07 0.65 0.5 0.05],'Style','text','String','Ng term','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[113/255 113/255 113/255]); h648 = uicontrol('parent',h64,'units','normalized','position',[0.55 0.66 0.3 0.047],'Style','edit','String','1','BackgroundColor',[240/255 173/255 105/255]); ud.handleAlgoShi = [h61;h62;h621;h622;h63;h64;h641;h642;h643;h644;h645;h646;h647;h648]; %-- INTERFACE -> PERSONAL ALGO CONTROL h71 = uicontrol('parent',h7,'units','normalized','position',[0.0 0.92 1.0 0.05],'Style','text','String','Personal Algorithm','FontSize',10,'HorizontalAlignment','center','Backgroundcolor',[87/255 86/255 84/255],'Foregroundcolor',[255/255 255/255 255/255]); h72 = uipanel('parent',h7,'units','normalized','position',[0.07 0.75 0.85 0.15],'BorderType','line','Backgroundcolor',[113/255 113/255 113/255],'HighlightColor',[0/255 0/255 0/255]); h73 = uicontrol('parent',h72,'units','normalized','position',[0.07 0.58 0.5 0.23],'Style','text','String','Number of iterations','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[113/255 113/255 113/255]); h74 = uicontrol('parent',h72,'units','normalized','position',[0.60 0.61 0.3 0.23],'Style','edit','String','200','BackgroundColor',[240/255 173/255 105/255]); h75 = uicontrol('parent',h72,'units','normalized','position',[0.07 0.13 0.5 0.23],'Style','text','String','Convergence thres.','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[113/255 113/255 113/255]); h76 = uicontrol('parent',h72,'units','normalized','position',[0.60 0.16 0.3 0.23],'Style','edit','String','2','BackgroundColor',[240/255 173/255 105/255]); h77 = uicontrol('parent',h7,'units','normalized','position',[0.1 0.66 0.85 0.04],'Style','text','String','Specific parameters','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[87/255 86/255 84/255],'Foregroundcolor',[255/255 255/255 255/255]); h78 = uipanel('parent',h7,'units','normalized','position',[0.07 0.05 0.85 0.61],'BorderType','line','Backgroundcolor',[113/255 113/255 113/255],'HighlightColor',[0/255 0/255 0/255]); h781 = uicontrol('parent',h78,'units','normalized','position',[0.07 0.89 0.5 0.05],'Style','text','String','Parameter 1','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[113/255 113/255 113/255]); h782 = uicontrol('parent',h78,'units','normalized','position',[0.55 0.90 0.3 0.047],'Style','edit','String','1','BackgroundColor',[240/255 173/255 105/255]); h783 = uicontrol('parent',h78,'units','normalized','position',[0.07 0.81 0.5 0.05],'Style','text','String','Parameter 2','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[113/255 113/255 113/255]); h784 = uicontrol('parent',h78,'units','normalized','position',[0.55 0.82 0.3 0.047],'Style','edit','String','1','BackgroundColor',[240/255 173/255 105/255]); ud.handleAlgoPersonal = [h71;h72;h73;h74;h75;h76;h77;h78;h781;h782;h783;h784]; %-- INTERFACE -> COMPARISON CONTROL h81 = uicontrol('parent',h8,'units','normalized','position',[0.0 0.92 1.0 0.05],'Style','text','String','Comparison Mode','FontSize',10,'HorizontalAlignment','center','Backgroundcolor',[87/255 86/255 84/255],'Foregroundcolor',[255/255 255/255 255/255]); h82 = uipanel('parent',h8,'units','normalized','position',[0.07 0.83 0.85 0.07],'BorderType','line','Backgroundcolor',[113/255 113/255 113/255],'HighlightColor',[0/255 0/255 0/255]); h821 = uicontrol('parent',h82,'units','normalized','position',[0.07 0.2 0.5 0.5],'Style','text','String','Number of iterations','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[113/255 113/255 113/255]); h822 = uicontrol('parent',h82,'units','normalized','position',[0.60 0.25 0.3 0.5],'Style','edit','String','200','callback',{@setAllNbIt},'BackgroundColor',[240/255 173/255 105/255]); h83 = uicontrol('parent',h8,'units','normalized','position',[0.1 0.77 0.85 0.03],'Style','text','String','Algorithms','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[87/255 86/255 84/255],'Foregroundcolor',[255/255 255/255 255/255]); h84 = uipanel('parent',h8,'units','normalized','position',[0.07 0.52 0.85 0.25],'BorderType','line','Backgroundcolor',[113/255 113/255 113/255],'HighlightColor',[0/255 0/255 0/255]); h841 = uicontrol('parent',h84,'units','normalized','position',[0.07 0.83 0.85 0.12],'Style','checkbox','String','1- Caselles','FontSize',9,'callback',{@SetIconSelected,1},'BackgroundColor',[113/255 113/255 113/255]); h842 = uicontrol('parent',h84,'units','normalized','position',[0.07 0.70 0.85 0.12],'Style','checkbox','String','2- Chan & Vese','FontSize',9,'callback',{@SetIconSelected,2},'BackgroundColor',[113/255 113/255 113/255]); h843 = uicontrol('parent',h84,'units','normalized','position',[0.07 0.57 0.85 0.12],'Style','checkbox','String','3- Chunming Li','FontSize',9,'callback',{@SetIconSelected,3},'BackgroundColor',[113/255 113/255 113/255]); h844 = uicontrol('parent',h84,'units','normalized','position',[0.07 0.44 0.85 0.12],'Style','checkbox','String','4- Lankton','FontSize',9,'callback',{@SetIconSelected,4},'BackgroundColor',[113/255 113/255 113/255]); h845 = uicontrol('parent',h84,'units','normalized','position',[0.07 0.31 0.85 0.12],'Style','checkbox','String','5- Bernard','FontSize',9,'callback',{@SetIconSelected,5},'BackgroundColor',[113/255 113/255 113/255]); h846 = uicontrol('parent',h84,'units','normalized','position',[0.07 0.18 0.85 0.12],'Style','checkbox','String','6- Shi','FontSize',9,'callback',{@SetIconSelected,6},'BackgroundColor',[113/255 113/255 113/255]); h847 = uicontrol('parent',h84,'units','normalized','position',[0.07 0.05 0.85 0.12],'Style','checkbox','String','7- Personal Algorithm','FontSize',9,'callback',{@SetIconSelected,7},'BackgroundColor',[113/255 113/255 113/255]); h85 = uicontrol('parent',h8,'units','normalized','position',[0.1 0.46 0.85 0.03],'Style','text','String','Reference','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[87/255 86/255 84/255],'Foregroundcolor',[255/255 255/255 255/255]); h86 = uipanel('parent',h8,'units','normalized','position',[0.07 0.34 0.85 0.12],'BorderType','line','Backgroundcolor',[113/255 113/255 113/255],'HighlightColor',[0/255 0/255 0/255]); h861 = uicontrol('parent',h86,'units','normalized','position',[0.15 0.58 0.30 0.31],'Style','pushbutton','String','Load','Backgroundcolor',[240/255 173/255 105/255],'callback','creaseg_loadreference','Enable','off'); h862 = uicontrol('parent',h86,'units','normalized','position',[0.53 0.58 0.30 0.31],'Style','pushbutton','String','Create','Backgroundcolor',[240/255 173/255 105/255],'callback','creaseg_createreference','Enable','off'); h863 = uicontrol('parent',h86,'units','normalized','position',[0.07 0.18 0.50 0.25],'Style','text','String','Interpolation Type','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[113/255 113/255 113/255]); h864 = uicontrol('parent',h86,'units','normalized','position',[0.63 0.20 0.30 0.25],'Style','popupmenu','String',{'Polygon','Spline'},'FontSize',9,'BackgroundColor',[240/255, 173/255, 105/255]); h87 = uipanel('parent',h8,'units','normalized','position',[0.07 0.16 0.85 0.12],'BorderType','line','Backgroundcolor',[113/255 113/255 113/255],'HighlightColor',[0/255 0/255 0/255]); h871 = uicontrol('parent',h87,'units','normalized','position',[0.07 0.55 0.40 0.29],'Style','text','String','Similarity Criteria','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[113/255 113/255 113/255]); h872 = uicontrol('parent',h87,'units','normalized','position',[0.53 0.58 0.40 0.32],'Style','popupmenu','String',{'Dice','PSNR','Hausdorff','MSSD'},'FontSize',9,'BackgroundColor',[240/255, 173/255, 105/255]); h873 = uicontrol('parent',h87,'units','normalized','position',[0.07 0.18 0.85 0.32],'Style','checkbox','String','Intermediate Output','BackgroundColor',[113/255 113/255 113/255],'Value',1); h88 = uicontrol('parent',h8,'units','normalized','position',[0.3 0.086 0.40 0.035],'Style','pushbutton','String','See Results','callback',{@manageCompItem,2},'Enable','off','Backgroundcolor',[240/255 173/255 105/255]); ud.handleAlgoComparison = [h81;h82;h821;h822;h83;h84;h841;h842;h843;h844;h845;h846;h847;h85;h86;h861;h862;h863;h864;h87;h871;h872;h873;h88]; %-- INTERFACE -> RESULTS CONTROL h91 = uicontrol('parent',h9,'units','normalized','position',[0.0 0.92 1.0 0.05],'Style','text','String','Results','FontSize',10,'HorizontalAlignment','center','Backgroundcolor',[87/255 86/255 84/255],'Foregroundcolor',[255/255 255/255 255/255]); if ud.Version h92 = uitable('parent',h9,'units','normalized','position',[0.07 0.62 0.85 0.3],'ColumnName',{'Calculation Time', 'Dice'},'ColumnFormat',{'Bank', 'Bank'},'RowName',{'1','2','3','4','5','6','7'}); else h92 = uicontrol('parent',h9,'units','normalized','position',[0.07 0.62 0.85 0.3],'Style','text','String','Results cannot be displayed here because your Matlab version do not support uitable. Therefore the results are saved in the file results.txt',... 'FontSize',12,'HorizontalAlignment','center','Backgroundcolor',[87/255 86/255 84/255],'Foregroundcolor',[255/255 0 0]); end h93 = uicontrol('parent',h9,'units','normalized','position',[0.1 0.55 0.85 0.03],'Style','text','String','Visual Criteria','FontSize',9,'HorizontalAlignment','left','Backgroundcolor',[87/255 86/255 84/255],'Foregroundcolor',[255/255 255/255 255/255]); h94 = uipanel('parent',h9,'units','normalized','position',[0.07 0.25 0.85 0.3],'BorderType','line','Backgroundcolor',[113/255 113/255 113/255],'HighlightColor',[0/255 0/255 0/255]); h941 = uicontrol('parent',h94,'units','normalized','position',[0.07 0.87 0.85 0.11],'Style','checkbox','String','Reference (White)','FontSize',9,'callback',{@creaseg_plotresults},'BackgroundColor',[113/255 113/255 113/255]); h942 = uicontrol('parent',h94,'units','normalized','position',[0.07 0.75 0.85 0.11],'Style','checkbox','String','1- Caselles (Yellow)','FontSize',9,'callback',{@creaseg_plotresults},'BackgroundColor',[113/255 113/255 113/255]); h943 = uicontrol('parent',h94,'units','normalized','position',[0.07 0.63 0.85 0.11],'Style','checkbox','String','2- Chan & Vese (Blue)','FontSize',9,'callback',{@creaseg_plotresults},'BackgroundColor',[113/255 113/255 113/255]); h944 = uicontrol('parent',h94,'units','normalized','position',[0.07 0.51 0.85 0.11],'Style','checkbox','String','3- Chunming Li (Cyan)','FontSize',9,'callback',{@creaseg_plotresults},'BackgroundColor',[113/255 113/255 113/255]); h945 = uicontrol('parent',h94,'units','normalized','position',[0.07 0.39 0.85 0.11],'Style','checkbox','String','4- Lankton (Red)','FontSize',9,'callback',{@creaseg_plotresults},'BackgroundColor',[113/255 113/255 113/255]); h946 = uicontrol('parent',h94,'units','normalized','position',[0.07 0.27 0.85 0.11],'Style','checkbox','String','5- Bernard (Green)','FontSize',9,'callback',{@creaseg_plotresults},'BackgroundColor',[113/255 113/255 113/255]); h947 = uicontrol('parent',h94,'units','normalized','position',[0.07 0.15 0.85 0.11],'Style','checkbox','String','6- Shi (Magenta)','FontSize',9,'callback',{@creaseg_plotresults},'BackgroundColor',[113/255 113/255 113/255]); h948 = uicontrol('parent',h94,'units','normalized','position',[0.07 0.03 0.85 0.11],'Style','checkbox','String','7- Personal Algorithm (Black)','FontSize',9,'callback',{@creaseg_plotresults},'BackgroundColor',[113/255 113/255 113/255]); h95 = uicontrol('parent',h9,'units','normalized','position',[0.3 0.086 0.4 0.035],'Style','pushbutton','String','See Parameters','callback',{@manageCompItem,1},'Backgroundcolor',[240/255 173/255 105/255]); ud.handleAlgoResults = [h91;h92;h93;h94;h941;h942;h943;h944;h945;h946;h947;h948;h95]; if ud.Version SetTableColumnWidth(ud); end %-- create structure to image handle fd = []; fd.data = []; fd.visu = []; fd.tagImage = 0; fd.levelset = []; fd.visuTmp = []; fd.levelsetTmp = []; fd.translation = [0 0]; fd.info = []; fd.reference = []; fd.points = []; fd.pointsRef = []; fd.handleRect = {}; fd.handleElliRect = {}; fd.handleManual = {}; fd.handleReference = {}; fd.method = ''; fd.drawingManualFlag = 0; fd.drawingMultiManualFlag = 0; %-- Set function to special events set(ud.imageId,'userdata',fd); set(ud.gcf,'WindowButtonMotionFcn',{@creaseg_mouseMove},'visible','on','HandleVisibility','callback','interruptible','off'); set(ud.gcf,'CloseRequestFcn',{@closeInterface}); %-- ATTACH UD STRUCTURE TO FIG HANDLE set(ud.gcf,'userdata',ud); set(ud.gcf,'ResizeFcn',@figResize); %--------------------------------------------------------------------- %-- AUXILIARY FUNCTIONS ---------------------------------------------- %--------------------------------------------------------------------- %------------------------------------------------------------------ function manageAlgoItem(src,evt,num) fig = gcbf; ud = get(fig,'userdata'); %-- cancel drawing mode set(ud.buttonAction(1),'background',[240/255 173/255 105/255]); for k=3:size(ud.handleInit,1) set(ud.handleInit(k),'BackgroundColor',[240/255 173/255 105/255]); end %-- check whether the create button of comparison mode is unselect if ( get(ud.handleAlgoComparison(17),'BackgroundColor')~=[160/255 130/255 95/255] ) set(ud.gcf,'WindowButtonDownFcn',''); set(ud.gcf,'WindowButtonUpFcn',''); %-- put pointer button to select set(ud.buttonAction(3),'BackgroundColor',[160/255 130/255 95/255]); end %-- put run button to unselect set(ud.buttonAction(2),'BackgroundColor',[240/255 173/255 105/255]); %-- if strcmp(get(ud.handleIconAlgo(8),'State'),'off')||(get(ud.handleAlgoComparison(6+num),'Value')==0) if strcmp(get(ud.handleIconAlgo(8),'State'),'on') EnableDisableNbit(ud,'on'); end for k=1:size(ud.handleAlgoConfig,1) set(ud.handleAlgoConfig(k),'Visible','off'); if k<size(ud.handleAlgoConfig,1)-1 set(ud.handleIconAlgo(k),'State','off'); end end set(ud.handleAlgoConfig(num),'Visible','on'); set(ud.handleIconAlgo(num),'State','on'); %-- setAllIcon(ud); %-- for k=1:size(ud.handleMenuAlgorithms,1) set(ud.handleMenuAlgorithms(k),'label',ud.handleMenuAlgorithmsName{k},'ForegroundColor',[0/255, 0/255, 0/255],'Checked','off'); end set(ud.handleMenuAlgorithms(num),'label',ud.handleMenuAlgorithmsName{num},'ForegroundColor',[255/255, 0/255, 0/255],'Checked','on'); else for k=1:size(ud.handleAlgoConfig,1) set(ud.handleAlgoConfig(k),'Visible','off'); if k<size(ud.handleAlgoConfig,1)-1 set(ud.handleIconAlgo(k),'State','off'); end end set(ud.handleAlgoConfig(num),'Visible','on'); set(ud.handleIconAlgo(8),'State','on'); end %-- function manageCompItem(src, evt, num) fig = gcbf; ud = get(fig,'userdata'); EnableDisableNbit(ud,'off'); %-- cancel drawing mode set(ud.buttonAction(1),'background',[240/255 173/255 105/255]); for k=3:size(ud.handleInit,1) set(ud.handleInit(k),'BackgroundColor',[240/255 173/255 105/255]); end %-- check whether the create button of comparison mode is unselect if ( get(ud.handleAlgoComparison(17),'BackgroundColor')~=[160/255 130/255 95/255] ) set(ud.gcf,'WindowButtonDownFcn',''); set(ud.gcf,'WindowButtonUpFcn',''); %-- put pointer button to select set(ud.buttonAction(3),'BackgroundColor',[160/255 130/255 95/255]); end %-- put run button to unselect set(ud.buttonAction(2),'BackgroundColor',[240/255 173/255 105/255]); %-- for k=1:size(ud.handleAlgoConfig,1) set(ud.handleAlgoConfig(k),'Visible','off'); if k<size(ud.handleAlgoConfig,1)-1 set(ud.handleIconAlgo(k),'State','off'); end end if num == 1 set(ud.handleAlgoConfig(8),'Visible','on'); set(ud.handleIconAlgo(8),'State','on'); else set(ud.handleAlgoConfig(9),'Visible','on'); set(ud.handleIconAlgo(8),'State','on') creaseg_plotresults(src,evt); end for k=1:size(ud.handleMenuAlgorithms,1)-1 set(ud.handleMenuAlgorithms(k),'label',ud.handleMenuAlgorithmsName{k},'ForegroundColor',[0/255, 0/255, 0/255],'Checked','off'); end set(ud.handleMenuAlgorithms(8),'label',ud.handleMenuAlgorithmsName{8},'ForegroundColor',[255/255, 0/255, 0/255],'Checked','on'); setAllIcon(ud); setAllNbIt(src,evt); %-- function manageInit(src,evt) fig = gcbf; ud = get(fig,'userdata'); for k=1:size(ud.handleAlgoConfig,1) set(ud.handleAlgoConfig(k),'Visible','off'); end set(ud.handleAlgoConfig(end),'Visible','on'); %-- function closeInterface(src,evt) delete(gcbf); %-- function figResize(src,evt) fig = gcbf; ud = get(fig,'userdata'); SetTextIntensityPosition(ud); if ud.Version SetTableColumnWidth(ud); end %-- function SetTableColumnWidth(ud) ss = get(ud.gcf,'position'); posPanel = get(ud.handleAlgoConfig(9),'position'); posTable = get(ud.handleAlgoResults(2),'position'); w = ss(3)*posPanel(3)*posTable(3)-35; set(ud.handleAlgoResults(2),'ColumnWidth',{w/2,w/2}); %-- function SetTextIntensityPosition(ud) ss = get(ud.gcf,'position'); pos = get(ud.panelText,'position'); w = ss(3)*pos(3); h = ss(4)*pos(4); a = w/5; c = w-2*a; b = 3*h/8; d = h-2*b; set(ud.txtPositionIntensity,'units','pixels','position',[a b c d]); %-- save images function saveResult(src,evt,num) fig = gcbf; ud = get(fig,'userdata'); fd = get(ud.imageId,'userdata'); img = fd.visu; method = fd.method; cl = ud.colorSpec(get(ud.handleContourColor,'userdata')); S = method; switch method case 'Reference' levelset = fd.reference; case 'Comparison' if num == 1 num = 2; end levelset = zeros(size(img,1),size(img,2),8); levelset(:,:,1) = fd.reference; levelset(:,:,2:end) = fd.seg; cl = {'w','y','b','c','r','g','m','k'}; S = ['Reference ';'Caselles ';'Chan & Vese';'Chunming Li'; ... 'Lankton ';'Bernard ';'Shi ';'Personal ']; otherwise levelset = fd.levelset; end method = S; switch num case 1 %-- save screen (one contour) if ( ~isempty(img) ) img = img - min(img(:)); img = uint8(255*img/max(img(:))); imgrgb = repmat(img,[1 1 3]); if ( (~isempty(levelset)) && (size(img,1)==size(levelset,1)) && (size(img,2)==size(levelset,2))) axes(get(ud.imageId,'parent')); delete(findobj(get(ud.imageId,'parent'),'type','line')); hold on; [c,h] = contour(levelset,[0 0],cl{1},'Linewidth',3); hold off; delete(h); tt = round(c); %-- test = isequal(size(c,2),0); while (test==false) s = c(2,1); if ( s == (size(c,2)-1) ) t = c; hold on; plot(t(1,2:end)',t(2,2:end)',cl{1},'Linewidth',3); test = true; else t = c(:,2:s+1); hold on; plot(t(1,1:end)',t(2,1:end)',cl{1},'Linewidth',3); c = c(:,s+2:end); end end %-- tt = tt(:, (tt(1,:)~=0) & (tt(1,:)>=1) & (tt(1,:)<=size(img,2)) ... & (tt(2,:)>=1) & (tt(2,:)<=size(img,1))); imgContour = repmat(0,size(img)); for k=1:size(tt,2) imgContour(tt(2,k),tt(1,k),1) = 1; end if ( min(size(img)) <= 225 ) se = strel('arbitrary',[1 1; 1 1]); elseif ( min(size(img)) <= 450 ) se = strel('disk',1); elseif ( min(size(img)) <= 775 ) se = strel('disk',2); else se = strel('disk',3); end imgContour = imdilate(imgContour,se); [y,x] = find(imgContour~=0); switch cl{1} case 'r' val = [255,0,0]; case 'g' val = [0,255,0]; case 'b' val = [0,0,255]; case 'y' val = [255,255,0]; case 'w' val = [255,255,255]; case 'k' val = [0,0,0]; end for k=1:size(x,1) imgrgb(y(k),x(k),1) = val(1); imgrgb(y(k),x(k),2) = val(2); imgrgb(y(k),x(k),3) = val(3); end set(ud.imageId,'userdata',fd); set(fig,'userdata',ud); end [filename, pathname] = uiputfile({'*.png','Png (*.png)';... '*.bmp','Bmp (*.bmp)';'*.tif','Tif (*.tif)';... '*.gif','Gif (*.gif)';'*.jpg','Jpg (*.jpg)'},'Save as'); if ( ~isempty(pathname) && ~isempty(filename) ) imwrite(imgrgb,[pathname filename]); end end case 2 %-- save screen (Multiple contours) if ( ~isempty(img) ) img = img - min(img(:)); img = uint8(255*img/max(img(:))); imgrgb = repmat(img,[1 1 3]); if ( (~isempty(levelset)) && (size(img,1)==size(levelset,1)) && (size(img,2)==size(levelset,2))) for i = 1:1:size(levelset,3) if (max(max(levelset(:,:,i)))~=0) && (get(ud.handleAlgoResults(4+i),'Value')) axes(get(ud.imageId,'parent')); hold on; [c,h] = contour(levelset(:,:,i),[0 0],cl{i},'Linewidth',3); hold off; delete(h); tt = round(c); %-- test = isequal(size(c,2),0); while (test==false) s = c(2,1); if ( s == (size(c,2)-1) ) t = c; hold on; plot(t(1,2:end)',t(2,2:end)',cl{i},'Linewidth',3); test = true; else t = c(:,2:s+1); hold on; plot(t(1,1:end)',t(2,1:end)',cl{i},'Linewidth',3); c = c(:,s+2:end); end end %-- tt = tt(:, (tt(1,:)~=0) & (tt(1,:)>=1) & (tt(1,:)<=size(img,2)) ... & (tt(2,:)>=1) & (tt(2,:)<=size(img,1))); imgContour = repmat(0,size(img)); for k=1:size(tt,2) imgContour(tt(2,k),tt(1,k),1) = 1; end if ( min(size(img)) <= 225 ) se = strel('arbitrary',[1 1; 1 1]); elseif ( min(size(img)) <= 450 ) se = strel('disk',1); elseif ( min(size(img)) <= 775 ) se = strel('disk',2); else se = strel('disk',3); end imgContour = imdilate(imgContour,se); [y,x] = find(imgContour~=0); switch cl{i} case 'r' val = [255,0,0]; case 'g' val = [0,255,0]; case 'b' val = [0,0,255]; case 'y' val = [255,255,0]; case 'w' val = [255,255,255]; case 'k' val = [0,0,0]; case 'm' val = [255,0,255]; case 'c' val = [0,255,255]; end for k=1:size(x,1) imgrgb(y(k),x(k),1) = val(1); imgrgb(y(k),x(k),2) = val(2); imgrgb(y(k),x(k),3) = val(3); end set(ud.imageId,'userdata',fd); set(fig,'userdata',ud); end end end [filename, pathname] = uiputfile({'*.png','Png (*.png)';... '*.bmp','Bmp (*.bmp)';'*.tif','Tif (*.tif)';... '*.gif','Gif (*.gif)';'*.jpg','Jpg (*.jpg)'},'Save as'); if ( ~isempty(pathname) && ~isempty(filename) ) imwrite(imgrgb,[pathname filename]); end end case 3 %-- save data if ( ~isempty(img) ) if ( (~isempty(levelset)) ) result = struct('img',img,'levelset',levelset, 'Method', method); else result = img; end [filename, pathname] = uiputfile({'*.mat','MAT-files (*.mat)'},'Save as'); if ( ~isempty(pathname) && ~isempty(filename) ) save([pathname filename],'result'); end end end %-- change color of contour display on the image function changeContourColor(src,evt) fig = findobj(0,'tag','creaseg'); ud = get(fig,'userdata'); fd = get(ud.imageId,'userdata'); pos = get(src,'userdata'); if (pos==6) pos = 1; else pos = pos+1; end filename = {'brushR' 'brushG' 'brushB' 'brushY' 'brushW' 'brushK'}; load(['misc/icons/' filename{pos} '.mat']); set(src,'cdata',cdata,'userdata',pos); %-- if ( ~isempty(fd.data) ) switch ud.LastPlot case 'levelset' if ( (~isempty(fd.levelset)) && (size(fd.data,1)==size(fd.levelset,1)) ... && (size(fd.data,2)==size(fd.levelset,2))) cl = ud.colorSpec(pos); if ( size(fd.handleRect,2) > 0 ) for k=size(fd.handleRect,2):-1:1 set(fd.handleRect{k},'EdgeColor',cl{1}); end elseif ( size(fd.handleElliRect,2) > 0 ) for k=size(fd.handleElliRect,2):-1:1 set(fd.handleElliRect{k}(2),'color',cl{1}); end elseif ( size(fd.handleManual,2) > 0 ) for k=size(fd.handleManual,2):-1:1 if ( (size(fd.handleManual{k},1)==1) && (fd.handleManual{k}>0) ) set(fd.handleManual{k},'color',cl{1}); end end else axes(get(ud.imageId,'parent')); delete(findobj(get(ud.imageId,'parent'),'type','line')); hold on; [c,h] = contour(fd.levelset,[0 0],cl{1},'Linewidth',3); hold off; delete(h); test = isequal(size(c,2),0); while (test==false) s = c(2,1); if ( s == (size(c,2)-1) ) t = c; hold on; plot(t(1,2:end)',t(2,2:end)',cl{1},'Linewidth',3); test = true; else t = c(:,2:s+1); hold on; plot(t(1,1:end)',t(2,1:end)',cl{1},'Linewidth',3); c = c(:,s+2:end); end end end end case 'reference' if ( (~isempty(fd.reference)) && (size(fd.data,1)==size(fd.reference,1)) ... && (size(fd.data,2)==size(fd.reference,2))) cl = ud.colorSpec(pos); axes(get(ud.imageId,'parent')); delete(findobj(get(ud.imageId,'parent'),'type','line')); hold on; [c,h] = contour(fd.reference,[0 0],cl{1},'Linewidth',3); hold off; delete(h); test = isequal(size(c,2),0); while (test==false) s = c(2,1); if ( s == (size(c,2)-1) ) t = c; hold on; plot(t(1,2:end)',t(2,2:end)',cl{1},'Linewidth',3); test = true; else t = c(:,2:s+1); hold on; plot(t(1,1:end)',t(2,1:end)',cl{1},'Linewidth',3); c = c(:,s+2:end); end end end end end %-- function SetIconSelected(src,evt,num) fig = gcbf; ud = get(fig,'userdata'); if get(ud.handleAlgoComparison(6+num),'Value') set(ud.handleIconAlgo(num),'cdata',ud.AlgoIconSel(:,:,:,num)) set(ud.handleMenuAlgorithms(num),'label',ud.handleMenuAlgorithmsName{num},'ForegroundColor',[0/255, 153/255, 51/255],'Checked','on'); else set(ud.handleIconAlgo(num),'cdata',ud.AlgoIcon(:,:,:,num)) set(ud.handleMenuAlgorithms(num),'label',ud.handleMenuAlgorithmsName{num},'ForegroundColor',[0/255, 0/255, 0/255],'Checked','off'); end %-- function setAllIcon(ud) for i=1:1:7 if (get(ud.handleAlgoComparison(6+i),'Value')) && strcmp(get(ud.handleIconAlgo(8),'State'),'on') set(ud.handleIconAlgo(i),'cdata',ud.AlgoIconSel(:,:,:,i)); set(ud.handleMenuAlgorithms(i),'label',ud.handleMenuAlgorithmsName{i},'ForegroundColor',[0/255, 153/255, 51/255],'Checked','on'); else set(ud.handleIconAlgo(i),'cdata',ud.AlgoIcon(:,:,:,i)); set(ud.handleMenuAlgorithms(i),'label',ud.handleMenuAlgorithmsName{i},'ForegroundColor',[0/255, 0/255, 0/255],'Checked','off'); end end %-- function EnableDisableNbit(ud,s) set(ud.handleAlgoCaselles(4),'Enable',s); set(ud.handleAlgoChanVese(4),'Enable',s); set(ud.handleAlgoLi(4),'Enable',s); set(ud.handleAlgoLankton(4),'Enable',s); set(ud.handleAlgoBernard(4),'Enable',s); set(ud.handleAlgoShi(4),'Enable',s); set(ud.handleAlgoPersonal(4),'Enable',s); %-- function setAllNbIt(src,evt) fig = gcbf; ud = get(fig,'userdata'); NbIt = get(ud.handleAlgoComparison(4),'String'); set(ud.handleAlgoCaselles(4),'String',NbIt); set(ud.handleAlgoChanVese(4),'String',NbIt); set(ud.handleAlgoLi(4),'String',NbIt); set(ud.handleAlgoLankton(4),'String',NbIt); set(ud.handleAlgoBernard(4),'String',NbIt); set(ud.handleAlgoShi(4),'String',NbIt); set(ud.handleAlgoPersonal(4),'String',NbIt); %-- function creaseg_inittype(src, evt) fig = gcbf; ud = get(fig,'userdata'); switch get(ud.handleInit(4),'Value') case {1,2} InitText_OnOff(ud,0); case 3 InitText_OnOff(ud,1); set(ud.handleInit(5),'String','Center'); set(ud.handleInit(7),'String','Xc'); set(ud.handleInit(9),'String','Yc'); set(ud.handleInit(13),'String','X Axis'); set(ud.handleInit(15),'String','Y Axis'); init_param(ud,get(ud.handleInit(4),'Value')); case 4 InitText_OnOff(ud,1); set(ud.handleInit(5),'String','Center'); set(ud.handleInit(7),'String','Xc'); set(ud.handleInit(9),'String','Yc'); set(ud.handleInit(13),'String','Length'); set(ud.handleInit(15),'String','Width'); init_param(ud,get(ud.handleInit(4),'Value')); case 5 InitText_OnOff(ud,1); set(ud.handleInit(5),'String','Space'); set(ud.handleInit(7),'String','X'); set(ud.handleInit(9),'String','Y'); set(ud.handleInit(13),'String','Radius'); set(ud.handleInit(15),'Enable','Off'); set(ud.handleInit(16),'Enable','Off'); init_param(ud,get(ud.handleInit(4),'Value')); case 6 InitText_OnOff(ud,1); set(ud.handleInit(5),'String','Space'); set(ud.handleInit(7),'String','X'); set(ud.handleInit(9),'String','Y'); set(ud.handleInit(13),'String','Length'); set(ud.handleInit(15),'String','Width'); init_param(ud,get(ud.handleInit(4),'Value')); end %-- function InitText_OnOff(ud,type) if type set(ud.handleInit(7),'Enable','On'); set(ud.handleInit(8),'Enable','On'); set(ud.handleInit(9),'Enable','On'); set(ud.handleInit(10),'Enable','On'); set(ud.handleInit(13),'Enable','On'); set(ud.handleInit(14),'Enable','On'); set(ud.handleInit(15),'Enable','On'); set(ud.handleInit(16),'Enable','On'); else set(ud.handleInit(7),'Enable','Off'); set(ud.handleInit(8),'Enable','Off'); set(ud.handleInit(9),'Enable','Off'); set(ud.handleInit(10),'Enable','Off'); set(ud.handleInit(13),'Enable','Off'); set(ud.handleInit(14),'Enable','Off'); set(ud.handleInit(15),'Enable','Off'); set(ud.handleInit(16),'Enable','Off'); end %-- function init_param(ud, method) fd = get(ud.imageId,'userdata'); if ( isempty(fd.data) ) return; end switch method case {3, 4} set(ud.handleInit(8),'string',num2str(size(fd.data,2)/2)); set(ud.handleInit(10),'string',num2str(size(fd.data,1)/2)); set(ud.handleInit(14),'string',num2str(size(fd.data,2)/4)); set(ud.handleInit(16),'string',num2str(size(fd.data,1)/4)); case {5, 6} set(ud.handleInit(8),'string',num2str(size(fd.data,2)/40)); set(ud.handleInit(10),'string',num2str(size(fd.data,1)/40)); set(ud.handleInit(14),'string',num2str(size(fd.data,2)/20)); set(ud.handleInit(16),'string',num2str(size(fd.data,1)/20)); end %-- function open_author(src,evt) web('http://www.creatis.insa-lyon.fr/~bernard'); %-- function open_help(src,evt) web('http://www.creatis.insa-lyon.fr/~bernard/creaseg'); %-- function manageAction(src,evt,nbBut) %-- parameters fig = findobj(0,'tag','creaseg'); ud = get(fig,'userdata'); fd = get(ud.imageId,'userdata'); %-- deal with pan option if ( (nbBut==2) || (nbBut==3) ) pan off; end %-- clean up all messages if ( nbBut<7) set(ud.txtInfo1,'string',''); set(ud.txtInfo2,'string',''); set(ud.txtInfo3,'string',''); set(ud.txtInfo4,'string',''); set(ud.txtInfo5,'string',''); end if (nbBut==6) if (get(ud.buttonAction(6),'background')==[160/255 130/255 95/255]) set(ud.buttonAction(6),'background',[240/255 173/255 105/255]); else set(ud.buttonAction(6),'background',[160/255 130/255 95/255]); end end if (nbBut==7) if (get(ud.buttonAction(7),'background')==[160/255 130/255 95/255]) set(ud.buttonAction(7),'background',[240/255 173/255 105/255]); set(ud.txtInfo1,'string',''); set(ud.txtInfo2,'string',''); set(ud.txtInfo3,'string',''); set(ud.txtInfo4,'string',''); set(ud.txtInfo5,'string',''); else set(ud.buttonAction(7),'background',[160/255 130/255 95/255]); end end %-- ACTION if ( (fd.tagImage == 1 ) || (nbBut == 1) ) switch nbBut case 1 %-- Draw initial region set(ud.buttonAction(2),'BackgroundColor',[240/255 173/255 105/255]); set(ud.buttonAction(3),'BackgroundColor',[240/255 173/255 105/255]); set(ud.buttonAction(7),'BackgroundColor',[240/255 173/255 105/255]); set(ud.buttonAction(1),'BackgroundColor',[160/255 130/255 95/255]); %-- switch off create button of comparison mode set(ud.handleAlgoComparison(17),'BackgroundColor',[240/255 173/255 105/255]); %-- do corresponding action manageInit(src,evt); case 2 %-- Run method set(ud.buttonAction(1),'BackgroundColor',[240/255 173/255 105/255]); set(ud.buttonAction(2),'BackgroundColor',[160/255 130/255 95/255]); set(ud.buttonAction(6),'BackgroundColor',[240/255 173/255 105/255]); set(ud.buttonAction(7),'BackgroundColor',[240/255 173/255 105/255]); %-- switch off create button of comparison mode set(ud.handleAlgoComparison(17),'BackgroundColor',[240/255 173/255 105/255]); %-- do corresponding action creaseg_run(src,evt); case 3 %-- Set mouse pointer to own (disable current figure option icon properties) set(ud.buttonAction(2),'BackgroundColor',[240/255 173/255 105/255]); set(ud.buttonAction(6),'BackgroundColor',[240/255 173/255 105/255]); set(ud.buttonAction(7),'BackgroundColor',[240/255 173/255 105/255]); set(ud.buttonAction(3),'BackgroundColor',[160/255 130/255 95/255]); %-- put drawing to unclick for k=3:size(ud.handleInit,1) set(ud.handleInit(k),'BackgroundColor',[240/255 173/255 105/255]); end %-- do corresponding action set(ud.gcf,'WindowButtonDownFcn',''); set(ud.gcf,'WindowButtonUpFcn',''); case 4 %-- Zoom in by a factor of 2 set(ud.buttonAction(2),'BackgroundColor',[240/255 173/255 105/255]); set(ud.buttonAction(5),'BackgroundColor',[240/255 173/255 105/255]); set(ud.buttonAction(7),'BackgroundColor',[240/255 173/255 105/255]); set(ud.buttonAction(4),'BackgroundColor',[160/255 130/255 95/255]); %-- do corresponding action axes(get(ud.imageId,'parent')); zoom(ud.gca,2); case 5 %-- Zoom out by a factor of 2 set(ud.buttonAction(2),'BackgroundColor',[240/255 173/255 105/255]); set(ud.buttonAction(4),'BackgroundColor',[240/255 173/255 105/255]); set(ud.buttonAction(7),'BackgroundColor',[240/255 173/255 105/255]); set(ud.buttonAction(5),'BackgroundColor',[160/255 130/255 95/255]); %-- do corresponding action axes(get(ud.imageId,'parent')); zoom(ud.gca,0.5); case 6 %-- Pan into main figure %-- set(ud.buttonAction(7),'BackgroundColor',[240/255 173/255 105/255]); %-- if (get(ud.buttonAction(6),'background')==[240/255 173/255 105/255]) %-- first pan off pan off; if ( get(ud.buttonAction(1),'background')==[240/255 173/255 105/255] ) if ( get(ud.handleAlgoComparison(17),'background')==[240/255 173/255 105/255] ) %-- then put pointer button to selected set(ud.buttonAction(3),'BackgroundColor',[160/255 130/255 95/255]); end end %-- then go back to manual drawing mode if any if ( fd.drawingManualFlag == 1 ) set(ud.gcf,'WindowButtonDownFcn',{@creaseg_drawManualContour}); set(ud.gcf,'WindowButtonUpFcn',''); end %-- then go back to multi manual drawing mode if any if ( fd.drawingMultiManualFlag == 1 ) set(ud.gcf,'WindowButtonDownFcn',{@creaseg_drawMultiManualContours}); set(ud.gcf,'WindowButtonUpFcn',''); end %-- then go back to reference manual drawing mode if any if ( fd.drawingReferenceFlag == 1 ) set(ud.gcf,'WindowButtonDownFcn',{@creaseg_drawMultiReferenceContours}); set(ud.gcf,'WindowButtonUpFcn',''); end else %-- put pointer button to unselected set(ud.buttonAction(3),'BackgroundColor',[240/255 173/255 105/255]); %-- do corresponding action set(ud.gcf,'WindowButtonDownFcn',''); set(ud.gcf,'WindowButtonUpFcn',''); axes(get(ud.imageId,'parent')); pan(ud.gca); end case 7 %-- Display or not current image properties if (get(ud.buttonAction(7),'background')==[160/255 130/255 95/255]) fd = get(ud.imageId,'userdata'); if ( ~isempty(fd.info) ) if ( isfield(fd.info,'Width') ) set(ud.txtInfo1,'string',sprintf('width:%d pixels',fd.info.Width),'color',[1 1 0]); end if ( isfield(fd.info,'Height') ) set(ud.txtInfo2,'string',sprintf('height:%d pixels',fd.info.Height),'color',[1 1 0]); end if ( isfield(fd.info,'BitDepth') ) set(ud.txtInfo3,'string',sprintf('bit depth:%d',fd.info.BitDepth),'color',[1 1 0]); end if ( isfield(fd.info,'XResolution') && (~isempty(fd.info.XResolution)) ) if ( isfield(fd.info,'ResolutionUnit') ) if ( strcmp(fd.info.ResolutionUnit,'meter') ) set(ud.txtInfo4,'string',sprintf('XResolution:%0.3f mm',fd.info.XResolution/1000),'color',[1 1 0]); elseif ( strcmp(fd.info.ResolutionUnit,'millimeter') ) set(ud.txtInfo4,'string',sprintf('XResolution:%0.3f mm',fd.info.XResolution),'color',[1 1 0]); else set(ud.txtInfo4,'string',sprintf('XResolution:%0.3f',fd.info.XResolution),'color',[1 1 0]); end else set(ud.txtInfo4,'string',sprintf('XResolution:%f',fd.info.XResolution),'color',[1 1 0]); end end if ( isfield(fd.info,'YResolution') && (~isempty(fd.info.YResolution)) ) if ( isfield(fd.info,'ResolutionUnit') ) if ( strcmp(fd.info.ResolutionUnit,'meter') ) set(ud.txtInfo5,'string',sprintf('YResolution:%0.3f mm',fd.info.YResolution/1000),'color',[1 1 0]); elseif ( strcmp(fd.info.ResolutionUnit,'millimeter') ) set(ud.txtInfo5,'string',sprintf('YResolution:%0.3f mm',fd.info.YResolution),'color',[1 1 0]); else set(ud.txtInfo5,'string',sprintf('YResolution:%0.3f',fd.info.YResolution),'color',[1 1 0]); end else set(ud.txtInfo5,'string',sprintf('YResolution:%f',fd.info.XResolution),'color',[1 1 0]); end end end end end end
github
jacksky64/imageProcessing-master
creaseg_loadreference.m
.m
imageProcessing-master/segmentation/creaseg/creaseg/creaseg/src/creaseg_loadreference.m
7,423
utf_8
037a1b94310e10c56c297b383370be4c
% Copyright or © or Copr. CREATIS laboratory, Lyon, France. % % Contributor: Olivier Bernard, Associate Professor at the french % engineering university INSA (Institut National des Sciences Appliquees) % and a member of the CREATIS-LRMN laboratory (CNRS 5220, INSERM U630, % INSA, Claude Bernard Lyon 1 University) in France (Lyon). % % Date of creation: 8th of October 2009 % % E-mail of the author: [email protected] % % This software is a computer program whose purpose is to evaluate the % performance of different level-set based segmentation algorithms in the % context of image processing (and more particularly on biomedical % images). % % The software has been designed for two main purposes. % - firstly, CREASEG allows you to use six different level-set methods. % These methods have been chosen in order to work with a wide range of % level-sets. You can select for instance classical methods such as % Caselles or Chan & Vese level-set, or more recent approaches such as the % one developped by Lankton or Bernard. % - finally, the software allows you to compare the performance of the six % level-set methods on different images. The performance can be evaluated % either visually, or from measurements (either using the Dice coefficient % or the PSNR value) between a reference and the results of the % segmentation. % % The level-set segmentation platform is citationware. If you are % publishing any work, where this program has been used, or which used one % of the proposed level-set algorithms, please remember that it was % obtained free of charge. You must reference the papers shown below and % the name of the CREASEG software must be mentioned in the publication. % % CREASEG software % "T. Dietenbeck, M. Alessandrini, D. Friboulet, O. Bernard. CREASEG: a % free software for the evaluation of image segmentation algorithms based % on level-set. In IEEE International Conference On Image Processing. % Hong Kong, China, 2010." % % Bernard method % "O. Bernard, D. Friboulet, P. Thevenaz, M. Unser. Variational B-Spline % Level-Set: A Linear Filtering Approach for Fast Deformable Model % Evolution. In IEEE Transactions on Image Processing. volume 18, no. 06, % pp. 1179-1191, 2009." % % Caselles method % "V. Caselles, R. Kimmel, and G. Sapiro. Geodesic active contours. % International Journal of Computer Vision, volume 22, pp. 61-79, 1997." % % Chan & Vese method % "T. Chan and L. Vese. Active contours without edges. IEEE Transactions on % Image Processing. volume10, pp. 266-277, February 2001." % % Lankton method % "S. Lankton, A. Tannenbaum. Localizing Region-Based Active Contours. In % IEEE Transactions on Image Processing. volume 17, no. 11, pp. 2029-2039, % 2008." % % Li method % "C. Li, C.Y. Kao, J.C. Gore, Z. Ding. Minimization of Region-Scalable % Fitting Energy for Image Segmentation. In IEEE Transactions on Image % Processing. volume 17, no. 10, pp. 1940-1949, 2008." % % Shi method % "Yonggang Shi, William Clem Karl. A Real-Time Algorithm for the % Approximation of Level-Set-Based Curve Evolution. In IEEE Transactions % on Image Processing. volume 17, no. 05, pp. 645-656, 2008." % % This software is governed by the BSD license and % abiding by the rules of distribution of free software. % % As a counterpart to the access to the source code and rights to copy, % modify and redistribute granted by the license, users are provided only % with a limited warranty and the software's author, the holder of the % economic rights, and the successive licensors have only limited % liability. % % In this respect, the user's attention is drawn to the risks associated % with loading, using, modifying and/or developing or reproducing the % software by the user in light of its specific status of free software, % that may mean that it is complicated to manipulate, and that also % therefore means that it is reserved for developers and experienced % professionals having in-depth computer knowledge. Users are therefore % encouraged to load and test the software's suitability as regards their % requirements in conditions enabling the security of their systems and/or % data to be ensured and, more generally, to use and operate it in the % same conditions as regards security. % %------------------------------------------------------------------------ function creaseg_loadreference(varargin) if nargin == 1 fig = varargin{1}; else fig = gcbf; end ud = get(fig,'userdata'); %-- clean figure screen set(ud.txtInfo1,'string',''); set(ud.txtInfo2,'string',''); set(ud.txtInfo3,'string',''); set(ud.txtInfo4,'string',''); set(ud.txtInfo5,'string',''); %-- Put the "Create" button in brighter set(ud.handleAlgoComparison(17),'BackgroundColor',[240/255 173/255 105/255]); %-- in case, enable drawing, run and pointer buttons set(ud.buttonAction(1),'enable','on'); set(ud.buttonAction(2),'enable','on'); set(ud.buttonAction(3),'enable','on'); %-- clean overlays and update fd structure keepLS = 1; creaseg_cleanOverlays(keepLS); fd = get(ud.imageId,'userdata'); %-- flush reference strucuture if any fd.handleReference{1} = 0; %-- Set drawingReferenceFlag flag to 0 fd.drawingReferenceFlag = 0; %-- Set pointsRef to empty fd.pointsRef = []; %-- cancel drawing mode for k=3:size(ud.handleInit,1) set(ud.handleInit(k),'BackgroundColor',[240/255 173/255 105/255]); end %-- put run button to nonselected set(ud.buttonAction(2),'background',[240/255 173/255 105/255]); %-- set(ud.gcf,'WindowButtonDownFcn',''); set(ud.gcf,'WindowButtonUpFcn',''); %-- [fname,pname] = uigetfile('*.mat','Pick a file','multiselect','off','data/Reference'); input_file = fullfile(pname,fname); if ~exist(input_file,'file') warning(['File: ' input_file ' does not exist']); return; end try junk = load(input_file); reference = junk.refLSF; clear junk; catch warning(['Could not load: ' input_file]); return; end %-- Check if the reference size is correct if (size(fd.data,1)~=size(reference,1)) || (size(fd.data,2)~=size(reference,2)) fd.reference = []; set(ud.txtInfo1,'string','Error:Image and Reference must be of the same size','color', [1 0 0]); else fd.reference = reference; ud.LastPlot = 'reference'; fd.method = 'Reference'; %-- color = ud.colorSpec(get(ud.handleContourColor,'userdata')); show_ref(fd.reference,ud,color); set(ud.handleAlgoComparison(24),'Enable','off'); end %-- UPDATE FD AND UD STRUCTURES ATTACHED TO IMAGEID AND FIG HANDLES set(ud.imageId,'userdata',fd); set(fig,'userdata',ud); function show_ref(ref,ud,cl) hold on; [c,h] = contour(ref,[0 0],cl{1},'Linewidth',3); hold off; delete(h); test = isequal(size(c,2),0); while (test==false) s = c(2,1); if ( s == (size(c,2)-1) ) t = c; hold on; plot(t(1,2:end)',t(2,2:end)',cl{1},'Linewidth',3); test = true; else t = c(:,2:s+1); hold on; plot(t(1,1:end)',t(2,1:end)',cl{1},'Linewidth',3); c = c(:,s+2:end); end end
github
jacksky64/imageProcessing-master
creaseg_plotresults.m
.m
imageProcessing-master/segmentation/creaseg/creaseg/creaseg/src/creaseg_plotresults.m
5,561
utf_8
315135765ad2dc382968b0561b6d4a98
% Copyright or © or Copr. CREATIS laboratory, Lyon, France. % % Contributor: Olivier Bernard, Associate Professor at the french % engineering university INSA (Institut National des Sciences Appliquees) % and a member of the CREATIS-LRMN laboratory (CNRS 5220, INSERM U630, % INSA, Claude Bernard Lyon 1 University) in France (Lyon). % % Date of creation: 8th of October 2009 % % E-mail of the author: [email protected] % % This software is a computer program whose purpose is to evaluate the % performance of different level-set based segmentation algorithms in the % context of image processing (and more particularly on biomedical % images). % % The software has been designed for two main purposes. % - firstly, CREASEG allows you to use six different level-set methods. % These methods have been chosen in order to work with a wide range of % level-sets. You can select for instance classical methods such as % Caselles or Chan & Vese level-set, or more recent approaches such as the % one developped by Lankton or Bernard. % - finally, the software allows you to compare the performance of the six % level-set methods on different images. The performance can be evaluated % either visually, or from measurements (either using the Dice coefficient % or the PSNR value) between a reference and the results of the % segmentation. % % The level-set segmentation platform is citationware. If you are % publishing any work, where this program has been used, or which used one % of the proposed level-set algorithms, please remember that it was % obtained free of charge. You must reference the papers shown below and % the name of the CREASEG software must be mentioned in the publication. % % CREASEG software % "T. Dietenbeck, M. Alessandrini, D. Friboulet, O. Bernard. CREASEG: a % free software for the evaluation of image segmentation algorithms based % on level-set. In IEEE International Conference On Image Processing. % Hong Kong, China, 2010." % % Bernard method % "O. Bernard, D. Friboulet, P. Thevenaz, M. Unser. Variational B-Spline % Level-Set: A Linear Filtering Approach for Fast Deformable Model % Evolution. In IEEE Transactions on Image Processing. volume 18, no. 06, % pp. 1179-1191, 2009." % % Caselles method % "V. Caselles, R. Kimmel, and G. Sapiro. Geodesic active contours. % International Journal of Computer Vision, volume 22, pp. 61-79, 1997." % % Chan & Vese method % "T. Chan and L. Vese. Active contours without edges. IEEE Transactions on % Image Processing. volume10, pp. 266-277, February 2001." % % Lankton method % "S. Lankton, A. Tannenbaum. Localizing Region-Based Active Contours. In % IEEE Transactions on Image Processing. volume 17, no. 11, pp. 2029-2039, % 2008." % % Li method % "C. Li, C.Y. Kao, J.C. Gore, Z. Ding. Minimization of Region-Scalable % Fitting Energy for Image Segmentation. In IEEE Transactions on Image % Processing. volume 17, no. 10, pp. 1940-1949, 2008." % % Shi method % "Yonggang Shi, William Clem Karl. A Real-Time Algorithm for the % Approximation of Level-Set-Based Curve Evolution. In IEEE Transactions % on Image Processing. volume 17, no. 05, pp. 645-656, 2008." % % This software is governed by the BSD license and % abiding by the rules of distribution of free software. % % As a counterpart to the access to the source code and rights to copy, % modify and redistribute granted by the license, users are provided only % with a limited warranty and the software's author, the holder of the % economic rights, and the successive licensors have only limited % liability. % % In this respect, the user's attention is drawn to the risks associated % with loading, using, modifying and/or developing or reproducing the % software by the user in light of its specific status of free software, % that may mean that it is complicated to manipulate, and that also % therefore means that it is reserved for developers and experienced % professionals having in-depth computer knowledge. Users are therefore % encouraged to load and test the software's suitability as regards their % requirements in conditions enabling the security of their systems and/or % data to be ensured and, more generally, to use and operate it in the % same conditions as regards security. % %------------------------------------------------------------------------ function creaseg_plotresults(src,evt) %-- parameters fig = findobj(0,'tag','creaseg'); ud = get(fig,'userdata'); fd = get(ud.imageId,'userdata'); if ( isempty(fd.data) ) return; end delete(findobj(get(ud.imageId,'parent'),'type','line')); color = {'w','y','b','c','r','g','m','k'}; if get(ud.handleAlgoResults(5),'Value') show_contour(fd.reference,ud,color(1)); end for i=1:1:7 if ( get(ud.handleAlgoResults(5+i),'Value') ) show_contour(fd.seg(:,:,i),ud,color(i+1)); end end function show_contour(mask,ud,cl) axes(get(ud.imageId,'parent')); hold on; [c,h] = contour(mask,[0 0],cl{1},'Linewidth',3); hold off; delete(h); test = isequal(size(c,2),0); while ( (test==false) && (size(c,1) ~= 0) && (size(c,2) ~= 0) ) s = c(2,1); if ( s == (size(c,2)-1) ) t = c; hold on; plot(t(1,2:end)',t(2,2:end)',cl{1},'linewidth',3); test = true; else t = c(:,2:s+1); hold on; plot(t(1,1:end)',t(2,1:end)',cl{1},'linewidth',3); c = c(:,s+2:end); end end
github
jacksky64/imageProcessing-master
localized_seg.m
.m
imageProcessing-master/segmentation/ActiveContours/Activeontours/localized_seg.m
7,761
utf_8
a248792540c81523bb28994de267cee4
% Localized Region Based Active Contour Segmentation: % % seg = localized_seg(I,init_mask,max_its,rad,alpha,method) % % Inputs: I 2D image % init_mask Initialization (1 = foreground, 0 = bg) % max_its Number of iterations to run segmentation for % rad (optional) Localization Radius (in pixels) % smaller = more local, bigger = more global % alpha (optional) Weight of smoothing term % higer = smoother % method (optional) selects localized energy % 1 = Chan-Vese Energy % 2 = Yezzi Energy (usually works better) % % Outputs: seg Final segmentation mask (1=fg, 0=bg) % % Example: % img = imread('tire.tif'); %-- load the image % m = false(size(img)); %-- create initial mask % m(28:157,37:176) = true; % seg = localized_seg(img,m,150); % % Description: This code implements the paper: "Localizing Region Based % Active Contours" By Lankton and Tannenbaum. In this work, typical % region-based active contour energies are localized in order to handle % images with non-homogeneous foregrounds and backgrounds. % % Coded by: Shawn Lankton (www.shawnlankton.com) %------------------------------------------------------------------------ function seg = localized_seg(I,init_mask,max_its,rad,alpha,method,FigRefreshRate,display) %-- default value for parameter alpha is .1 if(~exist('alpha','var')) alpha = .2; end %-- default value for parameter method is 2 if(~exist('method','var')) method = 2; end %-- default behavior is to display intermediate outputs if(~exist('display','var')) display = true; end if(~exist('FigRefreshRate','var')) FigRefreshRate =20; end %-- Ensures image is 2D double matrix I = im2graydouble(I); %-- Default localization radius is 1/10 of average length [dimy dimx] = size(I); if(~exist('rad','var')) rad = round((dimy+dimx)/(2*8)); if(display>0) disp(['localiztion radius is: ' num2str(rad) ' pixels']); end end %-- Create a signed distance map (SDF) from mask phi = mask2phi(init_mask); %--main loop for its = 1:max_its % Note: no automatic convergence test %-- get the curve's narrow band idx = find(phi <= 1.2 & phi >= -1.2)'; [y x] = ind2sub(size(phi),idx); %-- get windows for localized statistics xneg = x-rad; xpos = x+rad; %get subscripts for local regions yneg = y-rad; ypos = y+rad; xneg(xneg<1)=1; yneg(yneg<1)=1; %check bounds xpos(xpos>dimx)=dimx; ypos(ypos>dimy)=dimy; %-- re-initialize u,v,Ain,Aout u=zeros(size(idx)); v=zeros(size(idx)); Ain=zeros(size(idx)); Aout=zeros(size(idx)); %-- compute local stats for i = 1:numel(idx) % for every point in the narrow band img = I(yneg(i):ypos(i),xneg(i):xpos(i)); %sub image P = phi(yneg(i):ypos(i),xneg(i):xpos(i)); %sub phi upts = find(P<=0); %local interior Ain(i) = length(upts)+eps; u(i) = sum(img(upts))/Ain(i); vpts = find(P>0); %local exterior Aout(i) = length(vpts)+eps; v(i) = sum(img(vpts))/Aout(i); end %-- get image-based forces switch method %-choose which energy is localized case 1, %-- CHAN VESE F = -(u-v).*(2.*I(idx)-u-v); otherwise, %-- YEZZI F = -((u-v).*((I(idx)-u)./Ain+(I(idx)-v)./Aout)); end %-- get forces from curvature penalty curvature = get_curvature(phi,idx,x,y); %-- gradient descent to minimize energy dphidt = F./max(abs(F)) + alpha*curvature; %-- maintain the CFL condition dt = .45/(max(dphidt)+eps); %-- evolve the curve phi(idx) = phi(idx) + dt.*dphidt; %-- Keep SDF smooth phi = sussman(phi, .5); %-- intermediate output if((display>0)&&(mod(its,FigRefreshRate) == 0)) showCurveAndPhi(I,phi,its); end end %-- final output if(display) showCurveAndPhi(I,phi,its); end %-- make mask from SDF seg = phi<=0; %-- Get mask from levelset %--------------------------------------------------------------------- %--------------------------------------------------------------------- %-- AUXILIARY FUNCTIONS ---------------------------------------------- %--------------------------------------------------------------------- %--------------------------------------------------------------------- %-- Displays the image with curve superimposed function showCurveAndPhi(I, phi, i) imshow(I,[]); hold on; contour(phi, [0 0], 'g','LineWidth',4); contour(phi, [0 0], 'k','LineWidth',2); title(['Localized Region Based Active Contour Segmentation ',num2str(i) ' Iterations']); hold off;drawnow; %-- converts a mask to a SDF function phi = mask2phi(init_a) phi=bwdist(init_a)-bwdist(1-init_a)+im2double(init_a)-.5; %-- compute curvature along SDF function curvature = get_curvature(phi,idx,x,y) [dimy, dimx] = size(phi); %-- get subscripts of neighbors ym1 = y-1; xm1 = x-1; yp1 = y+1; xp1 = x+1; %-- bounds checking ym1(ym1<1) = 1; xm1(xm1<1) = 1; yp1(yp1>dimy)=dimy; xp1(xp1>dimx) = dimx; %-- get indexes for 8 neighbors idup = sub2ind(size(phi),yp1,x); iddn = sub2ind(size(phi),ym1,x); idlt = sub2ind(size(phi),y,xm1); idrt = sub2ind(size(phi),y,xp1); idul = sub2ind(size(phi),yp1,xm1); idur = sub2ind(size(phi),yp1,xp1); iddl = sub2ind(size(phi),ym1,xm1); iddr = sub2ind(size(phi),ym1,xp1); %-- get central derivatives of SDF at x,y phi_x = -phi(idlt)+phi(idrt); phi_y = -phi(iddn)+phi(idup); phi_xx = phi(idlt)-2*phi(idx)+phi(idrt); phi_yy = phi(iddn)-2*phi(idx)+phi(idup); phi_xy = -0.25*phi(iddl)-0.25*phi(idur)... +0.25*phi(iddr)+0.25*phi(idul); phi_x2 = phi_x.^2; phi_y2 = phi_y.^2; %-- compute curvature (Kappa) curvature = ((phi_x2.*phi_yy + phi_y2.*phi_xx - 2*phi_x.*phi_y.*phi_xy)./... (phi_x2 + phi_y2 +eps).^(3/2)).*(phi_x2 + phi_y2).^(1/2); %-- Converts image to one channel (grayscale) double function img = im2graydouble(img) [dimy, dimx, c] = size(img); if(isfloat(img)) % image is a double if(c==3) img = rgb2gray(uint8(img)); end else % image is a int if(c==3) img = rgb2gray(img); end img = double(img); end %-- level set re-initialization by the sussman method function D = sussman(D, dt) % forward/backward differences a = D - shiftR(D); % backward b = shiftL(D) - D; % forward c = D - shiftD(D); % backward d = shiftU(D) - D; % forward a_p = a; a_n = a; % a+ and a- b_p = b; b_n = b; c_p = c; c_n = c; d_p = d; d_n = d; a_p(a < 0) = 0; a_n(a > 0) = 0; b_p(b < 0) = 0; b_n(b > 0) = 0; c_p(c < 0) = 0; c_n(c > 0) = 0; d_p(d < 0) = 0; d_n(d > 0) = 0; dD = zeros(size(D)); D_neg_ind = find(D < 0); D_pos_ind = find(D > 0); dD(D_pos_ind) = sqrt(max(a_p(D_pos_ind).^2, b_n(D_pos_ind).^2) ... + max(c_p(D_pos_ind).^2, d_n(D_pos_ind).^2)) - 1; dD(D_neg_ind) = sqrt(max(a_n(D_neg_ind).^2, b_p(D_neg_ind).^2) ... + max(c_n(D_neg_ind).^2, d_p(D_neg_ind).^2)) - 1; D = D - dt .* sussman_sign(D) .* dD; %-- whole matrix derivatives function shift = shiftD(M) shift = shiftR(M')'; function shift = shiftL(M) shift = [ M(:,2:size(M,2)) M(:,size(M,2)) ]; function shift = shiftR(M) shift = [ M(:,1) M(:,1:size(M,2)-1) ]; function shift = shiftU(M) shift = shiftL(M')'; function S = sussman_sign(D) S = D ./ sqrt(D.^2 + 1);
github
jacksky64/imageProcessing-master
ActiveContoursWihoutEdges.m
.m
imageProcessing-master/segmentation/ActiveContours/Activeontours/ActiveContoursWihoutEdges.m
6,749
utf_8
2556c180e19cbdcde6de9d1172c0064d
function ActiveContoursWihoutEdges(hObject,mask) %This function implements the paper "Active Contours without Edges" by %Tony Chan and Luminita Vese. It also present results accourding to user %wish (from ActiveCountorsGUI). Coding- Nikolay S. & Alex B. %Input argument- a Handle to an object of ActiveCountorsGUI handles=guidata(hObject); %% get Alg parametrs from GUI N=get(handles.NAlgEdit,'Value'); % number of iterations Lambda_1=get(handles.Lambda1AlgEdit,'Value'); Lambda_2=get(handles.Lambda2AlgEdit,'Value'); miu=get(handles.MiuAlgEdit,'Value'); % varies from 255*1e-1 to 255*1e-4 v=get(handles.NuAlgEdit,'Value'); delta_t=get(handles.DeltaTAlgEdit,'Value'); HTflag=get(handles.HTBasedAlg,'Value'); %% Get visual/plotting parameters FigRefresRate=get(handles.RefreshRateEdit,'Value'); SaveRefresRate=get(handles.SaveRateEdit,'Value'); SegDispaly=get(handles.SegmentOn,'Value'); EnergyDispaly=get(handles.EnergyOn,'Value'); EnergyImageType=get(handles.EnergyPlotTypeMenu,'Value'); no_of_plots=SegDispaly+EnergyDispaly; uipael_handle=handles.Axis_uipanel; if no_of_plots==1 %set(handles.GUIfig,'CurrentAxes',handles.Axes) subplot(no_of_plots,1,1,'Units','Normalized','Parent',uipael_handle) end %% get I/O parameters out_dir=handles.OutDirPath; % get file name from path file_str=handles.ImageFileAddr; % [pathstr, name, ext, versn] = fileparts(filename) [~, in_file_name, ~] = fileparts(file_str); text_line_length=60; %% divide name too long to cell array to allow compact presentation in text command length_file_str=length(file_str); cell_array_length=ceil(length_file_str/text_line_length); file_str4text=cell(1,cell_array_length); for ind=1:cell_array_length-1 file_str4text{ind}=[file_str((1+(ind-1)*text_line_length):... ind*text_line_length),'...']; end file_str4text{ind+1}=file_str((1+ind*text_line_length):end); %% load image img=handles.ImageData; [img_x,img_y]=size(img); %% Init Phi phi=bwdist(1-mask)-bwdist(mask); % phi=phi.^3; phi=phi/(max(max(phi))-min(min(phi))); %normilize to amplitude=1 % K=zeros(img_x,img_y); %init K matrix if ~strcmpi(class(phi),'double') phi=double(phi); end %define HT if (HTflag) % x=-i*sign(linspace(0,1,150)-.5); N_U=10;N_V=10; [U,V]=meshgrid(linspace(-fix(N_U/2),fix(N_U/2),N_U),linspace(-fix(N_V/2),fix(N_V/2),N_U)); H_UV_HT=sign(U).*sign(V); h_ht=fftshift(ifft(H_UV_HT)); end for n=1:N % main loop %% Active contours iterations c_1=sum(img(phi>=0))/max(1,length(img(phi>0))); % prevent division by zero c_2=sum(img(phi<0))/max(1,length(img(phi<0))); % prevent division by zero if (HTflag) dx=filter2(h_ht,phi,'same'); dy=dx.'; else [dx,dy]=gradient(phi); end grad_norm=max(eps,sqrt(dx.^2+dy.^2));%we want to prevent division by zero % [dxx,dxy]=gradient(dx); % [dyx,dyy]=gradient(dy); % K=(dxx.*dy.^2-2*dx.*dy.*dxy+dyy.*dx.^2)./(grad_norm).^3; % another way to define div(grad/|grad|) K=divergence(dx./grad_norm,dy./grad_norm); %this one is a bit faster speed = Delta_eps(phi).*(miu*K-v-Lambda_1*(img-c_1).^2+Lambda_2*(img-c_2).^2); speed =speed/ sqrt(sum(sum(speed.^2)));%norm by square root of sum of square elements phi=phi+delta_t*speed; %% Presenting relevant graphs if (~mod(n,FigRefresRate)) % it's time to draw current image pause(0.001); if (SegDispaly) if (EnergyDispaly) % two axis on display subplot(no_of_plots,1,1,'Units','Normalized',... 'Parent',uipael_handle); end % imshow(uint8(repmat(img,[1,1,3])));hold on; strechedImg=img-min(img(:)); % now values are between 0:Max strechedImg=255*strechedImg/max(strechedImg(:)); % now values between 0:255 imshow(repmat(uint8(strechedImg),[1,1,3]),[]); hold on; contour(sign(phi),[0 0],'g','LineWidth',2); iterNum=['Segmentation with: Active Contours wihtout Edges, ',num2str(n),' iterations']; title(iterNum,'FontSize',14); axis off;axis equal;hold off; end if (EnergyDispaly) if (SegDispaly) % two axis on display subplot(no_of_plots,1,2,'Units','Normalized',... 'Parent',uipael_handle) end switch(EnergyImageType) case(1) %surf(phi) surf(phi); case(2) %mesh(phi) mesh(phi); case(3) %imagesc(phi) imagesc(phi); axis equal; axis off; case(4) %surf(sign|phi|) surf(sign(phi)); case(5) %mesh(sign|phi|) mesh(sign(phi)); case(6) %imagesc(sign|phi|); imagesc(sign(phi)); axis equal;axis off; end colormap('Jet'); title(['\phi_{',num2str(n),'}'],'FontSize',18); end if (SegDispaly)&&(EnergyDispaly) text_pos=[0.5,1.35]; else text_pos=[0.5,-0.02]; end text(text_pos(1),text_pos(2),{'Applied to file:',file_str4text{:}},... 'HorizontalAlignment','center','Units','Normalized',... 'FontUnits','Normalized'); drawnow; %% it's time to save current image if (~mod(n,SaveRefresRate)) tmp=zeros(size(img,1),size(img,2)); tmp(phi>0)=255; temp_img=repmat(img(:,:,1),[1 1 3]); temp_img(:,:,2)=temp_img(:,:,2)+tmp; imwrite(uint8(temp_img),[out_dir,filesep,in_file_name,'Segment_n_',num2str(n),'.jpg'],'jpg'); max_phi=max(max(phi));min_phi=min(min(phi)); tmp=phi; tmp=255*(tmp-min_phi)/(max_phi-min_phi); imwrite(uint8(tmp),[out_dir,filesep,in_file_name,'Phi_n_',num2str(n),'.jpg'],'jpg'); % saveas(gca,[out_dir,filesep,num2str(n)],'fig') ;%save figure end % if (~mod(n,SaveRefresRate)) end % if (~mod(n,FigRefresRate)) end % for n=1:N % main loop %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Servise sub function % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function out=Delta_eps(z,epsilon) if nargin==1 epsilon=1; end out=epsilon/pi./(epsilon^2+z.^2); % out=(1/(2*epsilon))*(1+cos(pi*z/epsilon)).*(abs(z)<=epsilon);
github
jacksky64/imageProcessing-master
LevelSetEvolutionWithoutReinitialization.m
.m
imageProcessing-master/segmentation/ActiveContours/Activeontours/LevelSetEvolutionWithoutReinitialization.m
5,441
utf_8
e95cf463293db58a1afa6f202ea6596d
function LevelSetEvolutionWithoutReinitialization(Img,sigma,epsilon,mu,lambda,alf,c0,N,PlotRate,mask) % This Matlab file demomstrates the level set method in Li et al's paper % "Level Set Evolution Without Re-initialization: A New Variational Formulation" % in Proceedings of CVPR'05, vol. 1, pp. 430-436. % Author: Chunming Li, all rights reserved. % E-mail: [email protected] % URL: http://www.engr.uconn.edu/~cmli/ if(~exist('PlotRate','var')) PlotRate = 20; end % Img = imread('twoObj.bmp'); % The same cell image in the paper is used here Img=double(Img(:,:,1)); % sigma=1.5; % scale parameter in Gaussian kernel for smoothing. G=fspecial('gaussian',15,sigma); Img_smooth=conv2(Img,G,'same'); % smooth image by Gaussiin convolution [Ix,Iy]=gradient(Img_smooth); f=Ix.^2+Iy.^2; g=1./(1+f); % edge indicator function. % epsilon=1.5; % the papramater in the definition of smoothed Dirac function % mu=0.04; timestep=0.2/mu; % timestep=5; % time step, try timestep=10, 20, ..., 50, ... % mu=0.2/timestep; % coefficient of the internal (penalizing) energy term P(\phi) % Note: the product timestep*mu must be less than 0.25 for stability! % lambda=5; % coefficient of the weighted length term Lg(\phi) % alf=1.5; % coefficient of the weighted area term Ag(\phi); % Note: Choose a positive(negative) alf if the initial contour is outside(inside) the object. [nrow, ncol]=size(Img); % figure(1); % imagesc(Img, [0, 255]);colormap(gray);hold on; % text(10,10,{'1.Left click to get points, right click to get end point','2.Drag the shape to desired posiiton',... % '3.Double click to run the algorithm'},'FontSize',[12],'Color', 'r'); % % % Click mouse to specify initial contour/region % BW = roipoly; % get a region R inside a polygon, BW is a binary image with 1 and 0 inside or outside the polygon; % % c0=4; % the constant value used to define binary level set function; initialLSF= c0*2*(0.5-mask); % initial level set function: -c0 inside R, c0 outside R; u=initialLSF; % [nrow, ncol]=size(Img); % initialLSF=c0*ones(nrow,ncol); % w=round((nrow+ncol)/20); % initialLSF(w+1:end-w, w+1:end-w)=0; % zero level set is on the boundary of R. % % Note: this can be commented out. The intial LSF does NOT necessarily need a zero level set. % initialLSF(w+2:end-w-1, w+2: end-w-1)=-c0; % negative constant -c0 inside of R, postive constant c0 outside of R. % u=initialLSF; imshow(Img, []); hold on; axis off;axis equal; contour(u,[0 0],'r','LineWidth',2); title('Initial contour'); % start level set evolution for n=1:N u=EVOLUTION(u, g ,lambda, mu, alf, epsilon, timestep, 1); if mod(n,PlotRate)==0 pause(0.001); imshow(Img, []); hold on;axis off;axis equal; contour(u,[0 0],'r','LineWidth',2); iterNum=['Level Set Evolution Without Re-initialization: A New Variational Formulation ',num2str(n),' iterations']; title(iterNum); hold off; end end imshow(Img, []);hold on; contour(u,[0 0],'r','LineWidth',2); axis off;axis equal; iterNum=['Level Set Evolution Without Re-initialization: A New Variational Formulation ',num2str(n),' iterations']; title(iterNum); function u = EVOLUTION(u0, g, lambda, mu, alf, epsilon, delt, numIter) % EVOLUTION(u0, g, lambda, mu, alf, epsilon, delt, numIter) updates the level set function % according to the level set evolution equation in Chunming Li et al's paper: % "Level Set Evolution Without Reinitialization: A New Variational Formulation" % in Proceedings CVPR'2005, % Usage: % u0: level set function to be updated % g: edge indicator function % lambda: coefficient of the weighted length term L(\phi) % mu: coefficient of the internal (penalizing) energy term P(\phi) % alf: coefficient of the weighted area term A(\phi), choose smaller alf % epsilon: the papramater in the definition of smooth Dirac function, default value 1.5 % delt: time step of iteration, see the paper for the selection of time step and mu % numIter: number of iterations. % % Author: Chunming Li, all rights reserved. % e-mail: [email protected] % http://vuiis.vanderbilt.edu/~licm/ u=u0; [vx,vy]=gradient(g); for k=1:numIter u=NeumannBoundCond(u); [ux,uy]=gradient(u); normDu=sqrt(ux.^2 + uy.^2 + 1e-10); Nx=ux./normDu; Ny=uy./normDu; diracU=Dirac(u,epsilon); K=curvature_central(Nx,Ny); weightedLengthTerm=lambda*diracU.*(vx.*Nx + vy.*Ny + g.*K); penalizingTerm=mu*(4*del2(u)-K); weightedAreaTerm=alf.*diracU.*g; u=u+delt*(weightedLengthTerm + weightedAreaTerm + penalizingTerm); % update the level set function end % the following functions are called by the main function EVOLUTION function f = Dirac(x, sigma) f=(1/2/sigma)*(1+cos(pi*x/sigma)); b = (x<=sigma) & (x>=-sigma); f = f.*b; function K = curvature_central(nx,ny) [nxx,junk]=gradient(nx); [junk,nyy]=gradient(ny); K=nxx+nyy; function g = NeumannBoundCond(f) % Make a function satisfy Neumann boundary condition [nrow,ncol] = size(f); g = f; g([1 nrow],[1 ncol]) = g([3 nrow-2],[3 ncol-2]); g([1 nrow],2:end-1) = g([3 nrow-2],2:end-1); g(2:end-1,[1 ncol]) = g(2:end-1,[3 ncol-2]);
github
jacksky64/imageProcessing-master
maskcircle2.m
.m
imageProcessing-master/segmentation/Chan-Vese/maskcircle2.m
2,101
utf_8
5172c5d8c496225ecc2354991153d114
function m = maskcircle2(I,type) % auto pick a circular mask for image I % built-in mask creation function % Input: I : input image % type: mask shape keywords % Output: m : mask image % Copyright (c) 2009, % Yue Wu @ ECE Department, Tufts University % All Rights Reserved if size(I,3)~=3 temp = double(I(:,:,1)); else temp = double(rgb2gray(I)); end h = [0 1 0; 1 -4 1; 0 1 0]; T = conv2(temp,h); T(1,:) = 0; T(end,:) = 0; T(:,1) = 0; T(:,end) = 0; thre = max(max(abs(T)))*.5; idx = find(abs(T) > thre); [cx,cy] = ind2sub(size(T),idx); cx = round(mean(cx)); cy = round(mean(cy)); [x,y] = meshgrid(1:min(size(temp,1),size(temp,2))); m = zeros(size(temp)); [p,q] = size(temp); switch lower (type) case 'small' r = 10; n = zeros(size(x)); n((x-cx).^2+(y-cy).^2<r.^2) = 1; m(1:size(n,1),1:size(n,2)) = n; %m((x-cx).^2+(y-cy).^2<r.^2) = 1; case 'medium' r = min(min(cx,p-cx),min(cy,q-cy)); r = max(2/3*r,25); n = zeros(size(x)); n((x-cx).^2+(y-cy).^2<r.^2) = 1; m(1:size(n,1),1:size(n,2)) = n; %m((x-cx).^2+(y-cy).^2<r.^2) = 1; case 'large' r = min(min(cx,p-cx),min(cy,q-cy)); r = max(2/3*r,60); n = zeros(size(x)); n((x-cx).^2+(y-cy).^2<r.^2) = 1; m(1:size(n,1),1:size(n,2)) = n; %m((x-cx).^2+(y-cy).^2<r.^2) = 1; case 'whole' r = 9; m = zeros(round(ceil(max(p,q)/2/(r+1))*3*(r+1))); siz = size(m,1); sx = round(siz/2); i = 1:round(siz/2/(r+1)); j = 1:round(0.9*siz/2/(r+1)); j = j-round(median(j)); m(sx+2*j*(r+1),(2*i-1)*(r+1)) = 1; se = strel('disk',r); m = imdilate(m,se); m = m(round(siz/2-p/2-6):round(siz/2-p/2-6)+p-1,round(siz/2-q/2-6):round(siz/2-q/2-6)+q-1); end tem(:,:,1) = m; M = padarray(m,[floor(2/3*r),floor(2/3*r)],0,'post'); tem(:,:,2) = M(floor(2/3*r)+1:end,floor(2/3*r)+1:end); m = tem; return
github
jacksky64/imageProcessing-master
chenvese.m
.m
imageProcessing-master/segmentation/Chan-Vese/chenvese.m
14,373
utf_8
03a43bed54d85efa5e620ce6bc002161
%========================================================================== % % Active contour with Chen-Vese Method % for image segementation % % Implemented by Yue Wu ([email protected]) % Tufts University % Feb 2009 % http://sites.google.com/site/rexstribeofimageprocessing/ % % all rights reserved % Last update 02/26/2009 %-------------------------------------------------------------------------- % Usage of varibles: % input: % I = any gray/double/RGB input image % mask = initial mask, either customerlized or built-in % num_iter = total number of iterations % mu = weight of length term % method = submethods pick from ('chen','vector','multiphase') % % Types of built-in mask functions % 'small' = create a small circular mask % 'medium' = create a medium circular mask % 'large' = create a large circular mask % 'whole' = create a mask with holes around % 'whole+small' = create a two layer mask with one layer small % circular mask and the other layer with holes around % (only work for method 'multiphase') % Types of methods % 'chen' = general CV method % 'vector' = CV method for vector image % 'multiphase'= CV method for multiphase (2 phases applied here) % % output: % phi0 = updated level set function % %-------------------------------------------------------------------------- % % Description: This code implements the paper: "Active Contours Without % Edges" by Chan and Vese for method 'chen', the paper:"Active Contours Without % Edges for vector image" by Chan and Vese for method 'vector', and the paper % "A Multiphase Level Set Framework for Image Segmentation Using the % Mumford and Shah Model" by Chan and Vese. % %-------------------------------------------------------------------------- % Deomo: Please see HELP file for details %========================================================================== function seg = chenvese(I,mask,num_iter,mu,method) %% %-- Default settings % length term mu = 0.2 and default method = 'chan' if(~exist('mu','var')) mu=0.2; end if(~exist('method','var')) method = 'chan'; end %-- End default settings %% %-- Initializations on input image I and mask % resize original image s = 200./min(size(I,1),size(I,2)); % resize scale if s<1 I = imresize(I,s); end % auto mask settings if ischar(mask) switch lower (mask) case 'small' mask = maskcircle2(I,'small'); case 'medium' mask = maskcircle2(I,'medium'); case 'large' mask = maskcircle2(I,'large'); case 'whole' mask = maskcircle2(I,'whole'); %mask = init_mask(I,30); case 'whole+small' m1 = maskcircle2(I,'whole'); m2 = maskcircle2(I,'small'); mask = zeros(size(I,1),size(I,2),2); mask(:,:,1) = m1(:,:,1); mask(:,:,2) = m2(:,:,2); otherwise error('unrecognized mask shape name (MASK).'); end else if s<1 mask = imresize(mask,s); end if size(mask,1)>size(I,1) || size(mask,2)>size(I,2) error('dimensions of mask unmathch those of the image.') end switch lower(method) case 'multiphase' if (size(mask,3) == 1) error('multiphase requires two masks but only gets one.') end end end switch lower(method) case 'chan' if size(I,3)== 3 P = rgb2gray(uint8(I)); P = double(P); elseif size(I,3) == 2 P = 0.5.*(double(I(:,:,1))+double(I(:,:,2))); else P = double(I); end layer = 1; case 'vector' s = 200./min(size(I,1),size(I,2)); % resize scale I = imresize(I,s); mask = imresize(mask,s); layer = size(I,3); if layer == 1 display('only one image component for vector image') end P = double(I); case 'multiphase' layer = size(I,3); if size(I,1)*size(I,2)>200^2 s = 200./min(size(I,1),size(I,2)); % resize scale I = imresize(I,s); mask = imresize(mask,s); end P = double(I); %P store the original image otherwise error('!invalid method') end %-- End Initializations on input image I and mask %% %-- Core function switch lower(method) case {'chan','vector'} %-- SDF % Get the distance map of the initial mask mask = mask(:,:,1); phi0 = bwdist(mask)-bwdist(1-mask)+im2double(mask)-.5; % initial force, set to eps to avoid division by zeros force = eps; %-- End Initialization %-- Display settings figure(); subplot(2,2,1); imshow(I); title('Input Image'); subplot(2,2,2); contour(flipud(phi0), [0 0], 'r','LineWidth',1); title('initial contour'); subplot(2,2,3); title('Segmentation'); %-- End Display original image and mask %-- Main loop for n=1:num_iter inidx = find(phi0>=0); % frontground index outidx = find(phi0<0); % background index force_image = 0; % initial image force for each layer for i=1:layer L = im2double(P(:,:,i)); % get one image component c1 = sum(sum(L.*Heaviside(phi0)))/(length(inidx)+eps); % average inside of Phi0 c2 = sum(sum(L.*(1-Heaviside(phi0))))/(length(outidx)+eps); % verage outside of Phi0 force_image=-(L-c1).^2+(L-c2).^2+force_image; % sum Image Force on all components (used for vector image) % if 'chan' is applied, this loop become one sigle code as a % result of layer = 1 end % calculate the external force of the image force = mu*kappa(phi0)./max(max(abs(kappa(phi0))))+1/layer.*force_image; % normalized the force force = force./(max(max(abs(force)))); % get stepsize dt dt=0.5; % get parameters for checking whether to stop old = phi0; phi0 = phi0+dt.*force; new = phi0; indicator = checkstop(old,new,dt); % intermediate output if(mod(n,20) == 0) showphi(I,phi0,n); end; if indicator % decide to stop or continue showphi(I,phi0,n); %make mask from SDF seg = phi0<=0; %-- Get mask from levelset subplot(2,2,4); imshow(seg); title('Global Region-Based Segmentation'); return; end end; showphi(I,phi0,n); %make mask from SDF seg = phi0<=0; %-- Get mask from levelset subplot(2,2,4); imshow(seg); title('Global Region-Based Segmentation'); case 'multiphase' %-- Initializations % Get the distance map of the initial masks mask1 = mask(:,:,1); mask2 = mask(:,:,2); phi1=bwdist(mask1)-bwdist(1-mask1)+im2double(mask1)-.5;%Get phi1 from the initial mask 1 phi2=bwdist(mask2)-bwdist(1-mask2)+im2double(mask2)-.5;%Get phi1 from the initial mask 2 %-- Display settings figure(); subplot(2,2,1); if layer ~= 1 imshow(I); title('Input Image'); else imagesc(P); axis image; colormap(gray);title('Input Image'); end subplot(2,2,2); hold on contour(flipud(mask1),[0,0],'r','LineWidth',2.5); contour(flipud(mask1),[0,0],'x','LineWidth',1); contour(flipud(mask2),[0,0],'g','LineWidth',2.5); contour(flipud(mask2),[0,0],'x','LineWidth',1); title('initial contour'); hold off subplot(2,2,3); title('Segmentation'); %-- End display settings %Main loop for n=1:num_iter %-- Narrow band for each phase nb1 = find(phi1<1.2 & phi1>=-1.2); %narrow band of phi1 inidx1 = find(phi1>=0); %phi1 frontground index outidx1 = find(phi1<0); %phi1 background index nb2 = find(phi2<1.2 & phi2>=-1.2); %narrow band of phi2 inidx2 = find(phi2>=0); %phi2 frontground index outidx2 = find(phi2<0); %phi2 background index %-- End initiliazaions on narrow band %-- Mean calculations for different partitions %c11 = mean (phi1>0 & phi2>0) %c12 = mean (phi1>0 & phi2<0) %c21 = mean (phi1<0 & phi2>0) %c22 = mean (phi1<0 & phi2<0) cc11 = intersect(inidx1,inidx2); %index belong to (phi1>0 & phi2>0) cc12 = intersect(inidx1,outidx2); %index belong to (phi1>0 & phi2<0) cc21 = intersect(outidx1,inidx2); %index belong to (phi1<0 & phi2>0) cc22 = intersect(outidx1,outidx2); %index belong to (phi1<0 & phi2<0) f_image11 = 0; f_image12 = 0; f_image21 = 0; f_image22 = 0; % initial image force for each layer for i=1:layer L = im2double(P(:,:,i)); % get one image component if isempty(cc11) c11 = eps; else c11 = mean(L(cc11)); end if isempty(cc12) c12 = eps; else c12 = mean(L(cc12)); end if isempty(cc21) c21 = eps; else c21 = mean(L(cc21)); end if isempty(cc22) c22 = eps; else c22 = mean(L(cc22)); end %-- End mean calculation %-- Force calculation and normalization % force on each partition f_image11=(L-c11).^2.*Heaviside(phi1).*Heaviside(phi2)+f_image11; f_image12=(L-c12).^2.*Heaviside(phi1).*(1-Heaviside(phi2))+f_image12; f_image21=(L-c21).^2.*(1-Heaviside(phi1)).*Heaviside(phi2)+f_image21; f_image22=(L-c22).^2.*(1-Heaviside(phi1)).*(1-Heaviside(phi2))+f_image22; end % sum Image Force on all components (used for vector image) % if 'chan' is applied, this loop become one sigle code as a % result of layer = 1 % calculate the external force of the image % curvature on phi1 curvature1 = mu*kappa(phi1); curvature1 = curvature1(nb1); % image force on phi1 fim1 = 1/layer.*(-f_image11(nb1)+f_image21(nb1)-f_image12(nb1)+f_image22(nb1)); fim1 = fim1./max(abs(fim1)+eps); % curvature on phi2 curvature2 = mu*kappa(phi2); curvature2 = curvature2(nb2); % image force on phi2 fim2 = 1/layer.*(-f_image11(nb2)+f_image12(nb2)-f_image21(nb2)+f_image22(nb2)); fim2 = fim2./max(abs(fim2)+eps); % force on phi1 and phi2 force1 = curvature1+fim1; force2 = curvature2+fim2; %-- End force calculation % detal t dt = 1.5; old(:,:,1) = phi1; old(:,:,2) = phi2; %update of phi1 and phi2 phi1(nb1) = phi1(nb1)+dt.*force1; phi2(nb2) = phi2(nb2)+dt.*force2; new(:,:,1) = phi1; new(:,:,2) = phi2; indicator = checkstop(old,new,dt); if indicator showphi(I, new, n); %make mask from SDF seg11 = (phi1>0 & phi2>0); %-- Get mask from levelset seg12 = (phi1>0 & phi2<0); seg21 = (phi1<0 & phi2>0); seg22 = (phi1<0 & phi2<0); se = strel('disk',1); aa1 = imerode(seg11,se); aa2 = imerode(seg12,se); aa3 = imerode(seg21,se); aa4 = imerode(seg22,se); seg = aa1+2*aa2+3*aa3+4*aa4; subplot(2,2,4); imagesc(seg);axis image;title('Global Region-Based Segmentation'); return end % re-initializations phi1 = reinitialization(phi1, 0.6);%sussman(phi1, 0.6);% phi2 = reinitialization(phi2, 0.6);%sussman(phi2,0.6); %intermediate output if(mod(n,20) == 0) phi(:,:,1) = phi1; phi(:,:,2) = phi2; showphi(I, phi, n); end; end; phi(:,:,1) = phi1; phi(:,:,2) = phi2; showphi(I, phi, n); %make mask from SDF seg11 = (phi1>0 & phi2>0); %-- Get mask from levelset seg12 = (phi1>0 & phi2<0); seg21 = (phi1<0 & phi2>0); seg22 = (phi1<0 & phi2<0); se = strel('disk',1); aa1 = imerode(seg11,se); aa2 = imerode(seg12,se); aa3 = imerode(seg21,se); aa4 = imerode(seg22,se); seg = aa1+2*aa2+3*aa3+4*aa4; %seg = bwlabel(seg); subplot(2,2,4); imagesc(seg);axis image;title('Global Region-Based Segmentation'); end
github
jacksky64/imageProcessing-master
thresholdLocally.m
.m
imageProcessing-master/segmentation/segmenttool/thresholdLocally.m
5,276
utf_8
c3ad5f3e07a48056bf2ec67e275a56d9
function B = thresholdLocally(A, blksz, varargin) % Performs LOCAL Otsu thresholding on an image; user can specify blocksize % % SYNTAX: B = thresholdLocally(A,PV_Pairs) % % THRESHOLDLOCALLY processes an image, calling graythresh on LOCAL % blocks in an image. This facilitates easy thresholding of images with % uneven background illumination, for which global thresholding is % inadequate. Uses the Image Processing Toolbox function BLOCKPROC % (R2009b). % % INPUTS: % A: Any image (or path/name of an image) suitable for processing % with im2bw() % % BLKSZ: Blocksize ([M,N]) with which to process the image. % DEFAULT: [32 32] % % (OPTIONAL): % PV_Pairs: Any valid parameter-value pairs accepted by blockproc. % DEFAULTS: % 'BorderSize': [6 6] % 'PadPartialBlocks': true % 'PadMethod': 'replicate' % 'TrimBorder': true % 'Destination': [NOT SPECIFIED] (See BLOCKPROC for usage) % FudgeFactor: As an additional PV_Pair, one may enter: % 'FudgeFactor', value (DEFAULT = 1), % You may provide a scalar multiplier for the local value % returned by graythresh. % % OUTPUT: % B: Output image (Unless 'DESTINATION' output is specified.) % % USAGE NOTE: To specify any PV_Pairs, BLKSZ must be provided as the second % input. If the default value of blksz is desired, an empty bracket ([]) may be % provided. (See Example 3.) % % EXAMPLES: % % % NOTE: All examples use image 'rice.png', which ships with the Image % % Processing Toolbox. % % img = imread('rice.png'); % % % EXAMPLE 1) Default usage: % thresholded = thresholdLocally(img); % imshow(thresholded) % % % EXAMPLE 2) Specifying non-default blocksize: % thresholded = thresholdLocally(img,[16 16]); % % % EXAMPLE 3) Specifying non-default padmethod (using default blocksize): % thresholded = thresholdLocally(img,[],'PadMethod','symmetric'); % % % EXAMPLE 4) Comparing and local thresholding, and thresholding after % % background normalization using tophat filtering: % figure % subplot(2,2,1);imshow(img);title('Original Image'); % tmp = im2bw(img,graythresh(img)); % subplot(2,2,2);imshow(tmp);title('Globally Thresholded'); % tmp = imtophat(img,strel('disk',15)); % tmp = im2bw(tmp,graythresh(tmp)); % subplot(2,2,3);imshow(tmp);title('Globally Thresholded after Tophat') % tmp = thresholdLocally(img); % subplot(2,2,4);imshow(tmp);title('Locally Thresholded'); % % Written by Brett Shoelson, PhD. % 12/17/2010 % Modifications: % * 12/20/2010 Modified significantly to accept as optional inputs all % parameter-value pairs accepted by BLOCKPROC, as well as an additional % "fudge factor" parameter that allows one to scale the local graythresh % value by a scalar multiple. % * 02/08/2011 Modified default blocksize to that calculated by bestblk % % Copyright 2010 The MathWorks % % See also: blockproc, graythresh, im2bw if ~nargin error('THRESHOLDLOCALLY: Requires at least one input argument.') end if ischar(A) A = imread(A); end % DEFAULTS % M = 32; % N = 32; [M, N] = bestblk(size(A)); opts.BorderSize = [6 6]; opts.PadPartialBlocks = true; opts.PadMethod = 'replicate'; opts.TrimBorder = true; opts.Destination = []; opts.FudgeFactor = 1; if nargin > 1 && ~isempty(blksz) if numel(blksz) == 1 M = blksz; N = M; elseif numel(blksz) == 2 M = blksz(1);N = blksz(2); else error('THRESHOLDLOCALLY: Improper specification of blocksize parameter'); end end if nargin > 2 opts = parsePV_Pairs(opts,varargin); end fun = @(block_struct) im2bw(block_struct.data,... min(max(opts.FudgeFactor*graythresh(block_struct.data),0),1)); if isempty(opts.Destination) B = blockproc(A,[M N],fun,... 'BorderSize',opts.BorderSize,... 'PadPartialBlocks',opts.PadPartialBlocks,... 'PadMethod',opts.PadMethod,... 'TrimBorder',opts.TrimBorder); else B = []; blockproc(A,[M N],fun,... 'BorderSize',opts.BorderSize,... 'PadPartialBlocks',opts.PadPartialBlocks,... 'PadMethod',opts.PadMethod,... 'TrimBorder',opts.TrimBorder,... 'Destination',opts.Destination); end end function opts = parsePV_Pairs(opts,UserInputs) ind = find(strcmpi(UserInputs,'BorderSize')); if ~isempty(ind) opts.BorderSize = UserInputs{ind + 1}; end ind = find(strcmpi(UserInputs,'PadPartialBlocks')); if ~isempty(ind) opts.PadPartialBlocks = UserInputs{ind + 1}; end ind = find(strcmpi(UserInputs,'PadMethod')); if ~isempty(ind) opts.PadMethod = UserInputs{ind + 1}; end ind = find(strcmpi(UserInputs,'TrimBorder')); if ~isempty(ind) opts.TrimBorder = UserInputs{ind + 1}; end ind = find(strcmpi(UserInputs,'Destination')); if ~isempty(ind) opts.Destination = UserInputs{ind + 1}; end ind = find(strcmpi(UserInputs,'FudgeFactor')); if ~isempty(ind) opts.FudgeFactor = UserInputs{ind + 1}; end end
github
jacksky64/imageProcessing-master
uigetvariables.m
.m
imageProcessing-master/segmentation/segmenttool/uigetvariables.m
16,902
utf_8
f4620a99811d119011fab23a47c295ed
function varout = uigetvariables(prompts,intro,types,ndimensions) %% % uigetvariables Open variable selection dialog box % % VARS = uigetvariables(PROMPTS) creates a dialog box that returns % variables selected from the base workspace. PROMPTS is a cell array of % strings, with one entry for each variable you would like the user to % select. VARS is a cell array containing the selected variables. Each % element of VARS corresponds with the selection for the same element of % PROMPTS. % % If the user hits CANCEL or dismisses the dialog, VARS is an empty cell % array. If the user does not select a variable for a given prompt, the % value in VARS for that prompt is an empty array. % % VARS = uigetvariables(PROMPTS,INTRO) includes introductory text to guide the user % of the dialog. INTRO is a string. If INTRO is not specified, no % introduction is included. The text in INTRO is wrapped automatically to % fit in the dialog. % % VARS = uigetvariables(PROMPTS,INTRO,TYPES) restricts the types of the variables % which can be selected for each prompt. TYPES is a cell array of strings % of the same length as PROMPTS, each entry specifies the allowable type of % variables for each prompt. The elements of TYPES may be any of the % following: % any Any type. Use this if you don't care. % numeric Any numeric type, as determined by isnumeric % logical Logical % string String or cell array of strings % % vars = uigetvariables(PROMPTS,INTRO,TYPES,NDIMENSIONS) also specifies required % dimensionality of variables. NDIMENSIONS is a numeric array of length PROMPTS, % with each element specifying the required dimensionality of the variables % for the corresponding element of PROMPTS. NDIMENSIONS works a little % different from ndims, in that it allows you to distinguish among scalars, % vectors, and matrices. % Allowable values are: % % Value Meaning % ------------ ---------- % Inf Any size. Use this if you don't care, or want more than one allowable size % 0 Scalar (1x1) % 1 Vector (1xN or Nx1) % 2 Matrix (NxM) % 3 or higher Specified number of dimensions % % vars = uigetvariables(PROMPTS,INTRO,VALFCN) applies an arbitrary % validation function to determine which variables are valid for each % prompt. VALFCN is either a single function handle, or a cell array of % function handles of same length as PROMPTS. If VALFCN is a single % function handle, it is applied to every prompt. Use a cell array of % function handles to specify a unique validation function for each prompt. % VALFCN must return true if a variable passes the validation or false if % the variable does not. Syntax of VALFCN must be % TF = VALFCN(variable) % % Examples % % % Put some sample data in your base workspace: % scalar1 = 1; % str1 = 'a string'; % cellstr1 = {'a string';'in a cell'};cellstr2 = {'another','string','in','a','cell'}; % cellstr3 = {'1','2';,'3','4'} % vector1 = rand(1,10); vector2 = rand(5,1); % array1 = rand(5,5); array2 = rand(5,5); array3 = rand(10,10); % threed1 = rand(3,4,5); % fourd1 = rand(1,2,3,4); % % % Select any two variables from entire workspace % tvar = uigetvariables({'Please select any variable','And another'}); % % % Include introductory text % tvar = uigetvariables({'Please select any variable','And another'},'Here are some very detailed directions about how you should use this dialog. Pick one variable, then pick another variable.'); % % % Control type of variables % tvar = uigetvariables({'Pick a number:','Pick a string:','Pick another number:'},[],{'numeric','string','numeric'}); % % % Control size of variables. % tvar = uigetvariables({'Pick a scalar:','Pick a vector:','Pick a matrix:'},[],[],[0 1 2]); % % % Control type and size of variables % tvar = uigetvariables({'Pick a scalar:','Pick a string','Pick a 4D array'},[],{'numeric','string','numeric'},[0 Inf 4]); % tvar = uigetvariables({'Pick a scalar:','Pick a string vector','Pick a 3D array'},[],{'numeric','string','numeric'},[0 1 3]); % % % Advanced - use custom validation functions % % % Custom validation functions % tvar = uigetvariables({'Pick a number:','Any number:','One more, please:'},'Use a custom validation function to require every input to be numeric',@isnumeric); % tvar = uigetvariables({'Pick a number:','Pick a cell string:','Pick a 3D array:'},[],{@isnumeric,@iscellstr,@(x) ndims(x)==3}); % % % No variable found % tvar = uigetvariables('Pick a 6D numeric array:','What if there is no valid data?',@(x) isnumeric(x)&&ndims(x)==6); % Scott Hirsch % [email protected] % Copyright 2010-2013 The Mathworks Inc % Allow for single prompt as string if ~iscell(prompts) prompts = {prompts}; end if nargin<2 || isempty(intro) intro = ''; end nPrompts = length(prompts); % Assume the user didn't specify validation function specifiedValidationFcn = false; %% if nargin==3 && ~isempty(types) % See if I've got function handle % Grab the first value from cell to test type if iscell(types) test = types{1}; else test = types; end switch class(test) case 'function_handle' % Put "types" input variable into valfcn % Replicate a single function handle into a cell array if necessary if ~iscell(types) valfcn = cell(nPrompts,1); valfcn = cellfun(@(f) types,valfcn,'UniformOutput',false); else valfcn = types; end specifiedValidationFcn = true; end end %% % If the user didn't specify the validation function, we will build it for % them. if ~specifiedValidationFcn if nargin<3 || isempty(types) types = cellstr(repmat('any',nPrompts,1)); elseif length(types)==1 % allow for single prompt with single type types = {types}; end if nargin<4 || isempty(ndimensions) ndimensions = inf(1,nPrompts); end % Base validation functions to choose from: isscalarfcn = @(var) numel(var)==1; isvectorfcn = @(var) length(size(var))==2&&any(size(var)==1)&&~isscalarfcn(var); isndfcn = @(var,dim) ndims(var)==dim && ~isscalar(var) && ~isvectorfcn(var); isanyfcn = @(var) true; % What an optimistic function! :) isnumericfcn = @(var) isnumeric(var); islogicalfcn = @(var) islogical(var); isstringfcn = @(var) ischar(var) | iscellstr(var); valfcn = cell(1,nPrompts); for ii=1:nPrompts switch types{ii} case 'any' valfcn{ii} = isanyfcn; case 'numeric' valfcn{ii} = isnumericfcn; case 'logical' valfcn{ii} = islogicalfcn; case 'string' valfcn{ii} = isstringfcn; otherwise valfcn{ii} = isanyfcn; end switch ndimensions(ii) case 0 % 0 - scalar valfcn{ii} = @(var) isscalarfcn(var) & valfcn{ii}(var); case 1 % 1 - vector valfcn{ii} = @(var) isvectorfcn(var) & valfcn{ii}(var); case Inf % Inf - Any shape valfcn{ii} = @(var) isanyfcn(var) & valfcn{ii}(var); otherwise % ND valfcn{ii} = @(var) isndfcn(var,ndimensions(ii)) & valfcn{ii}(var); end end end %% Get list of variables in base workspace allvars = evalin('base','whos'); nVars = length(allvars); varnames = {allvars.name}; vartypes = {allvars.class}; varsizes = {allvars.size}; % Convert variable sizes from numbers: % [N M], [N M P], ... etc % to text: % NxM, NxMxP varsizes = cellfun(@mat2str,varsizes,'UniformOutput',false); %too lazy for regexp. Strip off brackets varsizes = cellfun(@(s) s(2:end-1),varsizes,'UniformOutput',false); % replace blank with x varsizes = strrep(varsizes,' ','x'); vardisplay = strcat(varnames,' (',varsizes,{' '},vartypes,')'); %% Build list of variables for each prompt % Also include one that's prettied up a bit for display, which has an extra % first entry saying '(select one)'. This allows for no selection, for % optional input arguments. validVariables = cell(nPrompts,1); validVariablesDisplay = cell(nPrompts,1); for ii=1:nPrompts % turn this into cellfun once I understand what I'm doing. assignin('base','validationfunction_',valfcn{ii}) validVariables{ii} = cell(nVars,1); validVariablesDisplay{ii} = cell(nVars+1,1); t = false(nVars,1); for jj = 1:nVars t(jj) = evalin('base',['validationfunction_(' varnames{jj} ');']); end if any(t) % Found at least one variable validVariables{ii} = varnames(t); validVariablesDisplay{ii} = vardisplay(t); validVariablesDisplay{ii}(2:end+1) = validVariablesDisplay{ii}; validVariablesDisplay{ii}{1} = '(select one)'; else validVariables{ii} = '(no valid variables)'; validVariablesDisplay{ii} = '(no valid variables)'; end evalin('base','clear validationfunction_') end %% Compute layout offset = 1; maxStringLength = max(cellfun(@(s) length(s),prompts)); componentWidth = max([maxStringLength, 50]); componentHeight = 1; % Buttons buttonHeight = 1.77; buttonWidth = 10.6; % Wrap intro string. Need to do this now to include height in dialog. % Could use textwrap, which comes with MATLAB, instead of linewrap. This would just take a % bit more shuffling around with the order I create and size things. if ~isempty(intro) intro = linewrap(intro,componentWidth); introHeight = length(intro); % Intro is now an Nx1 cell string else introHeight = 0; end dialogWidth = componentWidth + 2*offset; dialogHeight = 2*nPrompts*(componentHeight+offset) + buttonHeight + offset + introHeight; % Component positions, starting from bottom of figure popuppos = [offset 2*offset+buttonHeight componentWidth componentHeight]; textpos = popuppos; textpos(2) = popuppos(2)+componentHeight; %% Build figure % hFig = dialog('Units','Characters','WindowStyle','modal','Name','Select variable(s)','CloseRequestFcn',@nestedCloseReq); hFig = dialog('Units','Characters','WindowStyle','normal','Name','Select variable(s)','CloseRequestFcn',@nestedCloseReq); % set(hFig,'DefaultUicontrolFontSize',10) % set(hFig,'DefaultUicontrolFontName','Arial') pos = get(hFig,'Position'); set(hFig,'Position',[pos(1:2) dialogWidth dialogHeight]) uicontrol('Parent',hFig,'style','Pushbutton','Callback',@nestedCloseReq,'String','OK', 'Units','characters','Position',[dialogWidth-2*offset-2*buttonWidth .5*offset buttonWidth buttonHeight]); uicontrol('Parent',hFig,'style','Pushbutton','Callback',@nestedCloseReq,'String','Cancel','Units','characters','Position',[dialogWidth-offset-buttonWidth .5*offset buttonWidth buttonHeight]); for ii=nPrompts:-1:1 uicontrol('Parent',hFig,'Style','text', 'Units','char','Position',textpos, 'String',prompts{ii},'HorizontalAlignment','left'); hPopup(ii) = uicontrol('Parent',hFig,'Style','popupmenu','Units','char','Position',popuppos,'String',validVariablesDisplay{ii},'UserData',validVariables{ii}); % Set up positions for next go round popuppos(2) = popuppos(2) + 1.5*offset + 2*componentHeight; textpos(2) = textpos(2) + 1.5*offset + 2*componentHeight; end if ~isempty(intro) intropos = [offset dialogHeight-introHeight-1 componentWidth introHeight+.5]; uicontrol('Parent',hFig,'Style','text','Units','Characters','Position',intropos, 'String',intro,'HorizontalAlignment','left'); end uiwait(hFig) function nestedCloseReq(obj,~) % How did I get here? % If pressed OK, get variables. Otherwise, don't. if strcmp(get(obj,'type'),'uicontrol') && strcmp(get(obj,'String'),'OK') for ind=1:nPrompts str = get(hPopup(ind),'UserData'); % Store real variable name here val = get(hPopup(ind),'Value')-1; % Remove offset to account for '(select one)' as initial entry if val==0 % User didn't select anything varout{ind} = []; elseif strcmp(str,'(no valid variables)') varout{ind} = []; else varout{ind} = evalin('base',str{val}); end end else % Cancel - return empty varout = {}; end delete(hFig) end end function c = linewrap(s, maxchars) %LINEWRAP Separate a single string into multiple strings % C = LINEWRAP(S, MAXCHARS) separates a single string into multiple % strings by separating the input string, S, on word breaks. S must be a % single-row char array. MAXCHARS is a nonnegative integer scalar % specifying the maximum length of the broken string. C is a cell array % of strings. % % C = LINEWRAP(S) is the same as C = LINEWRAP(S, 80). % % Note: Words longer than MAXCHARS are not broken into separate lines. % This means that C may contain strings longer than MAXCHARS. % % This implementation was inspired a blog posting about a Java line % wrapping function: % http://joust.kano.net/weblog/archives/000060.html % In particular, the regular expression used here is the one mentioned in % Jeremy Stein's comment. % % Example % s = 'Image courtesy of Joe and Frank Hardy, MIT, 1993.' % c = linewrap(s, 40) % % See also TEXTWRAP. % Steven L. Eddins % $Revision: 1.7 $ $Date: 2006/02/08 16:54:51 $ % http://www.mathworks.com/matlabcentral/fileexchange/9909-line-wrap-a-string % Copyright (c) 2009, The MathWorks, Inc. % All rights reserved. % % Redistribution and use in source and binary forms, with or without % modification, are permitted provided that the following conditions are % met: % % * Redistributions of source code must retain the above copyright % notice, this list of conditions and the following disclaimer. % * Redistributions in binary form must reproduce the above copyright % notice, this list of conditions and the following disclaimer in % the documentation and/or other materials provided with the distribution % * Neither the name of the The MathWorks, Inc. nor the names % of its contributors may be used to endorse or promote products derived % from this software without specific prior written permission. % % THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" % AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE % IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE % ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE % LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR % CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF % SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS % INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN % CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) % ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE % POSSIBILITY OF SUCH DAMAGE. narginchk(1, 2); bad_s = ~ischar(s) || (ndims(s) > 2) || (size(s, 1) ~= 1); %#ok<ISMAT> if bad_s error('S must be a single-row char array.'); end if nargin < 2 % Default value for second input argument. maxchars = 80; end % Trim leading and trailing whitespace. s = strtrim(s); % Form the desired regular expression from maxchars. exp = sprintf('(\\S\\S{%d,}|.{1,%d})(?:\\s+|$)', maxchars, maxchars); % Interpretation of regular expression (for maxchars = 80): % '(\\S\\S{80,}|.{1,80})(?:\\s+|$)' % % Match either a non-whitespace character followed by 80 or more % non-whitespace characters, OR any sequence of between 1 and 80 % characters; all followed by either one or more whitespace characters OR % end-of-line. tokens = regexp(s, exp, 'tokens').'; % Each element if the cell array tokens is single-element cell array % containing a string. Convert this to a cell array of strings. get_contents = @(f) f{1}; c = cellfun(get_contents, tokens, 'UniformOutput', false); % Remove trailing whitespace characters from strings in c. This can happen % if multiple whitespace characters separated the last word on a line from % the first word on the following line. c = deblank(c); end
github
jacksky64/imageProcessing-master
regiongrowing.m
.m
imageProcessing-master/segmentation/RegionGrowing/regiongrowing.m
8,119
utf_8
1f10aec0bc9c96dd3b669f6b0c1ac29f
function lMask = RegionGrowing(dImg, dMaxDif, iSeed) %REGIONGROWING A MEXed 2D/3D region growing algorithm. % % lMASK = REGIONGROWING(dIMG, dMAXDIF, iSEED) Returns a binary mask % lMASK, the result of growing a region from the seed point iSEED. % The stoping critereon is fulfilled if no voxels in the region's % 4-neighbourhood have an intensity difference smaller than dMAXDIF to % the region's mean intensity. % % If the seed point is not supplied, a GUI lets you select it. If no % output is requested, the result of the region growing is visualized % % IMPORTANT NOTE: This Matlab function is a front-end for a fast mex % function. Compile it by making the directiory containing this file your % current Matlab working directory and typing % % >> mex RegionGrowing_mex.cpp % % in the Matlab console. % % % Example (requires image processing toolbox): % % load mri; % Gives variable D; % RegionGrowing(squeeze(D), 10, [1 1 1]); % <- segments the background % % Copyright 2013 Christian Wuerslin, University of Tuebingen and % University of Stuttgart, Germany. % Contact: [email protected] % ========================================================================= % *** FUNCTION regiongrowing % *** % *** See above for description. % *** % ========================================================================= dOPACITY = 0.6; % ------------------------------------------------------------------------- % Parse the input arguments if nargin < 2, error('At least two input arguments required!'); end if ndims(dImg) > 3, error('Input image must be either 2D or 3D!'); end dImg = double(dImg); if ~isscalar(dMaxDif), error('Second input argument (MaxDif) must be a scalar!'); end if nargin < 3 iSeed = uint16(fGetSeed(dImg)); if isempty(iSeed), return; end else if numel(iSeed) ~= ndims(dImg), error('Invalid seed point! Must have ndims(dImg) elements!'); end iSeed = uint16(iSeed(:)); end % ------------------------------------------------------------------------- % ------------------------------------------------------------------------- % If the mex file has not been compiled yet, try to do so. if exist('RegionGrowing_mex', 'file') ~= 3 fprintf(1, 'Trying to compile mex file...'); sCurrentPath = cd; sPath = fileparts(mfilename('fullpath')); cd(sPath) try mex([sPath, filesep, 'RegionGrowing_mex.cpp']); fprintf(1, 'done\n'); catch error('Could not compile the mex file :(. Please try to do so manually!'); end cd(sCurrentPath); end % ------------------------------------------------------------------------- % ------------------------------------------------------------------------- % Start the region growing process by calling the mex function if max(dImg(:)) == min(dImg(:)) lMask = true(size(dImg)); warning('All image elements have the same value!'); else lMask = RegionGrowing_mex(dImg, iSeed, dMaxDif); end % ------------------------------------------------------------------------- % ------------------------------------------------------------------------- % If no output requested, visualize the result if ~nargout dImg = dImg - min(dImg(:)); % Normalize the image dImg = dImg./max(dImg(:)); dImg = permute(dImg, [1 2 4 3]); % Change to RGB-mode dImg = repmat(dImg, [1 1 3 1]); dMask = double(permute(lMask, [1 2 4 3])); dMask = cat(3, dMask, zeros(size(dMask)), zeros(size(dMask))); % Make mask the red channel -> red overlay dImg = 1 - (1 - dImg).*(1 - dOPACITY.*dMask); % The 'screen' overlay mode % reduce montage size by selecting the interesting slices, only lSlices = squeeze(sum(sum(dMask(:,:,1,:), 1), 2) > 0 ); figure, montage(dImg(:,:,:,lSlices)); end % ------------------------------------------------------------------------- end % ========================================================================= % *** END FUNCTION regiongrowing % ========================================================================= % ========================================================================= % *** FUNCTION fGetSeed % *** % *** A little GUI to select a seed % *** % ========================================================================= function iSeed = fGetSeed(dImg) iSlice = 1; dImg = dImg./max(dImg(:)); dImg = dImg - min(dImg(:)); iImg = uint8(dImg.*255); try hF = figure(... 'Position' , [0 0 size(dImg, 2) size(dImg, 1)], ... 'Units' , 'pixels', ... 'Color' , 'k', ... 'DockControls' , 'off', ... 'MenuBar' , 'none', ... 'Name' , 'Select Seed', ... 'NumberTitle' , 'off', ... 'BusyAction' , 'cancel', ... 'Pointer' , 'crosshair', ... 'CloseRequestFcn' , 'delete(gcbf)', ... 'WindowButtonDownFcn' , 'uiresume(gcbf)', ... 'KeyPressFcn' , @fKeyPressFcn, ... 'WindowScrollWheelFcn' , @fWindowScrollWheelFcn); catch hF = figure(... 'Position' , [0 0 size(dImg, 2) size(dImg, 1)], ... 'Units' , 'pixels', ... 'Color' , 'k', ... 'DockControls' , 'off', ... 'MenuBar' , 'none', ... 'Name' , 'Select Seed', ... 'NumberTitle' , 'off', ... 'BusyAction' , 'cancel', ... 'Pointer' , 'crosshair', ... 'CloseRequestFcn' , 'delete(gcbf)', ... 'WindowButtonDownFcn' , 'uiresume(gcbf)', ... 'KeyPressFcn' , @fKeyPressFcn); end hA = axes(... 'Parent' , hF, ... 'Position' , [0 0 1 1]); hI = image(iImg(:,:,1), ... 'Parent' , hA, ... 'CDataMapping' , 'scaled'); colormap(gray(256)); movegui('center'); uiwait; if ~ishandle(hF) iSeed = []; else iPos = uint16(get(hA, 'CurrentPoint')); iSeed = [iPos(1, 2) iPos(1, 1) iSlice]; delete(hF); end % --------------------------------------------------------------------- % * * NESTED FUNCTION fKeyPressFcn (nested in fGetSeed) % * * % * * Changes the active slice % --------------------------------------------------------------------- function fKeyPressFcn(hObject, eventdata) switch(eventdata.Key) case 'uparrow' iSlice = min([size(iImg, 3), iSlice + 1]); set(hI, 'CData', iImg(:,:,iSlice)); case 'downarrow' iSlice = max([1, iSlice - 1]); set(hI, 'CData', iImg(:,:,iSlice)); end end % --------------------------------------------------------------------- % * * END OF NESTED FUNCTION fKeyPressFcn (nested in fGetSeed) % --------------------------------------------------------------------- % --------------------------------------------------------------------- % * * NESTED FUNCTION fWindowScrollWheelFcn (nested in fGetSeed) % * * % * * Changes the active slice % --------------------------------------------------------------------- function fWindowScrollWheelFcn(hObject, eventdata) iSlice = min([size(iImg, 3), iSlice + eventdata.VerticalScrollCount]); iSlice = max([1, iSlice]); set(hI, 'CData', iImg(:,:,iSlice)); end % --------------------------------------------------------------------- % * * END OF NESTED FUNCTION fWindowScrollWheelFcn (nested in fGetSeed) % --------------------------------------------------------------------- end % ========================================================================= % *** END FUNCTION fGetSeed (and its nested function) % =========================================================================
github
jacksky64/imageProcessing-master
fGetSeed.m
.m
imageProcessing-master/segmentation/RegionGrowing/fGetSeed.m
3,953
utf_8
9abe0cd8d5d9544d06406345cc7363ab
% ========================================================================= % *** FUNCTION fGetSeed % *** % *** A little GUI to select a seed % *** % ========================================================================= function iSeed = fGetSeed(dImg) iSlice = 1; dImg = dImg./max(dImg(:)); dImg = dImg - min(dImg(:)); iImg = uint8(dImg.*255); try hF = figure(... 'Position' , [0 0 size(dImg, 2) size(dImg, 1)], ... 'Units' , 'pixels', ... 'Color' , 'k', ... 'DockControls' , 'off', ... 'MenuBar' , 'none', ... 'Name' , 'Select Seed', ... 'NumberTitle' , 'off', ... 'BusyAction' , 'cancel', ... 'Pointer' , 'crosshair', ... 'CloseRequestFcn' , 'delete(gcbf)', ... 'WindowButtonDownFcn' , 'uiresume(gcbf)', ... 'KeyPressFcn' , @fKeyPressFcn, ... 'WindowScrollWheelFcn' , @fWindowScrollWheelFcn); catch hF = figure(... 'Position' , [0 0 size(dImg, 2) size(dImg, 1)], ... 'Units' , 'pixels', ... 'Color' , 'k', ... 'DockControls' , 'off', ... 'MenuBar' , 'none', ... 'Name' , 'Select Seed', ... 'NumberTitle' , 'off', ... 'BusyAction' , 'cancel', ... 'Pointer' , 'crosshair', ... 'CloseRequestFcn' , 'delete(gcbf)', ... 'WindowButtonDownFcn' , 'uiresume(gcbf)', ... 'KeyPressFcn' , @fKeyPressFcn); end hA = axes(... 'Parent' , hF, ... 'Position' , [0 0 1 1]); hI = image(iImg(:,:,1), ... 'Parent' , hA, ... 'CDataMapping' , 'scaled'); colormap(gray(256)); movegui('center'); uiwait; if ~ishandle(hF) iSeed = []; else iPos = uint16(get(hA, 'CurrentPoint')); iSeed = [iPos(1, 2) iPos(1, 1) iSlice]; delete(hF); end % --------------------------------------------------------------------- % * * NESTED FUNCTION fKeyPressFcn (nested in fGetSeed) % * * % * * Changes the active slice % --------------------------------------------------------------------- function fKeyPressFcn(hObject, eventdata) switch(eventdata.Key) case 'uparrow' iSlice = min([size(iImg, 3), iSlice + 1]); set(hI, 'CData', iImg(:,:,iSlice)); case 'downarrow' iSlice = max([1, iSlice - 1]); set(hI, 'CData', iImg(:,:,iSlice)); end end % --------------------------------------------------------------------- % * * END OF NESTED FUNCTION fKeyPressFcn (nested in fGetSeed) % --------------------------------------------------------------------- % --------------------------------------------------------------------- % * * NESTED FUNCTION fWindowScrollWheelFcn (nested in fGetSeed) % * * % * * Changes the active slice % --------------------------------------------------------------------- function fWindowScrollWheelFcn(hObject, eventdata) iSlice = min([size(iImg, 3), iSlice + eventdata.VerticalScrollCount]); iSlice = max([1, iSlice]); set(hI, 'CData', iImg(:,:,iSlice)); end % --------------------------------------------------------------------- % * * END OF NESTED FUNCTION fWindowScrollWheelFcn (nested in fGetSeed) % --------------------------------------------------------------------- end % ========================================================================= % *** END FUNCTION fGetSeed (and its nested function) % =========================================================================
github
jacksky64/imageProcessing-master
Main.m
.m
imageProcessing-master/segmentation/Image Segmentation & Edge Detection Toolbox/Bc project/Main.m
10,629
utf_8
8fef5db166a4f95c56ece910e8b6367d
function varargout = Main(varargin) % MAIN MATLAB code for Main.fig % MAIN, by itself, creates a new MAIN or raises the existing % singleton*. % % H = MAIN returns the handle to a new MAIN or the handle to % the existing singleton*. % % MAIN('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in MAIN.M with the given input arguments. % % MAIN('Property','Value',...) creates a new MAIN or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before Main_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to Main_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help Main % Last Modified by GUIDE v2.5 31-Aug-2015 12:04:25 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @Main_OpeningFcn, ... 'gui_OutputFcn', @Main_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before Main is made visible. function Main_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to Main (see VARARGIN) % Choose default command line output for Main handles.output = hObject; handles.image = 0; handles.resultImage = 0; % Update handles structure guidata(hObject, handles); % UIWAIT makes Main wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = Main_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; addpath('regionGrowing'); addpath('PSO'); addpath('GraphSeg'); addpath('adaptcluster_kmeans'); addpath('FCMLSM'); addpath('ISODATA'); addpath('html'); % --- Executes on button press in Browse. function Browse_Callback(hObject, eventdata, handles) % hObject handle to Browse (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) [filename, filepath] = uigetfile({'*.jpg;*.png;*.bmp;*.jpeg;*.tiff','Image Files (*.jpg,*.png,*.bmp,*.jpeg,*.tiff)'}); handles.image = imread(strcat(filepath,filename)); guidata(hObject, handles); imshow(handles.image, 'Parent', handles.axes1); % --- Executes on selection change in chooseMethod. function chooseMethod_Callback(hObject, eventdata, handles) % hObject handle to chooseMethod (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: contents = cellstr(get(hObject,'String')) returns chooseMethod contents as cell array % contents{get(hObject,'Value')} returns selected item from chooseMethod persistent t; persistent k; if (isfield(handles, 't')) handles = rmfield (handles, 't'); delete(t); end if (isfield(handles, 'k')) handles = rmfield (handles, 'k'); delete(k); end option = get(handles.chooseMethod, 'Value'); switch option case 3 f = handles.figure1; t = uicontrol(f, 'style', 'text', 'string', 'K : levels of segmentation = 2', 'position', [710 540 140 17.8]); k = uicontrol(f, 'style', 'slider', 'min', 2, 'max', 20, 'value', 2, 'position', [870 540 140 17.8], 'sliderstep' , [1/18 1/18]); handles.t = t; handles.k = k; %k = uicontrol(f, 'Style', 'slider', case 13 f = handles.figure1; t = uicontrol(f, 'style', 'text', 'string', 'K : levels of segmentation = 2', 'position', [710 540 140 17.8]); k = uicontrol(f, 'style', 'slider', 'min', 2, 'max', 20, 'value', 2, 'position', [870 540 140 17.8], 'sliderstep' , [1/18 1/18]); handles.t = t; handles.k = k; case 14 f = handles.figure1; t = uicontrol(f, 'style', 'text', 'string', 'K : levels of segmentation = 2', 'position', [710 540 140 17.8]); k = uicontrol(f, 'style', 'slider', 'min', 2, 'max', 20, 'value', 2, 'position', [870 540 140 17.8], 'sliderstep' , [1/18 1/18]); handles.t = t; handles.k = k; case 15 f = handles.figure1; t = uicontrol(f, 'style', 'text', 'string', 'K : levels of segmentation = 2', 'position', [710 540 140 17.8]); k = uicontrol(f, 'style', 'slider', 'min', 2, 'max', 20, 'value', 2, 'position', [850 540 140 17.8], 'sliderstep' , [1/18 1/18]); handles.t = t; handles.k = k; case 16 f = handles.figure1; t = uicontrol(f, 'style', 'text', 'string', 'K : levels of segmentation = 2', 'position', [710 540 140 17.8]); k = uicontrol(f, 'style', 'slider', 'min', 2, 'max', 20, 'value', 2, 'position', [850 540 140 17.8], 'sliderstep' , [1/18 1/18]); handles.t = t; handles.k = k; end guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function chooseMethod_CreateFcn(hObject, eventdata, handles) % hObject handle to chooseMethod (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: popupmenu controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- Executes on button press in do. function do_Callback(hObject, eventdata, handles) % hObject handle to do (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) image = imread('please-wait.png'); imshow(image, 'Parent', handles.axes2); pause(1); option = get(handles.chooseMethod, 'Value'); switch option case 2 level = graythresh(handles.image); image = im2bw(handles.image,level); handles.resultImage = image; case 3 k = get(handles.k,'Value'); image = (handles.image); level = multithresh(handles.image,k); image = imquantize(image,level); image = label2rgb(image); handles.resultImage = image; case 4 labledImage = adaptcluster_kmeans(handles.image); image = label2rgb(labledImage); handles.resultImage = image; case 5 image = (handles.image); image = edge(image,'Canny'); handles.resultImage = image; case 6 image = (handles.image); image = edge(image,'log'); handles.resultImage = image; case 7 image = (handles.image); image = edge(image,'Prewitt'); handles.resultImage = image; case 8 image = (handles.image); image = edge(image,'Roberts'); handles.resultImage = image; case 9 image = (handles.image); image = edge(image,'Sobel'); handles.resultImage = image; case 10 image = (handles.image); image = edge(image,'zerocross'); handles.resultImage = image; case 11 image = (handles.image); [~, threshold] = edge (image, 'Sobel'); fudgeFactor = 0.5; BWs = edge(image,'sobel', threshold * fudgeFactor); se90 = strel('line', 3, 90); se0 = strel('line', 3, 0); BWsdil = imdilate(BWs, [se90 se0]); BWdfill = imfill(BWsdil, 'holes'); seD = strel('diamond',1); BWfinal = imerode(BWdfill,seD); BWfinal = imerode(BWfinal,seD); BWoutline = bwperim(BWfinal); Segout = handles.image; Segout(repmat(BWoutline,[1,1,size(handles.image,3)])) = 255; handles.resultImage = Segout; case 12 image = (handles.image); [x, y] = size(image); [~, mask] = regionGrowing(image,[floor(rand()*x), floor(rand()*y)]); image = double(handles.image).*repmat(mask,[1,1,size(handles.image,3)]); handles.resultImage = image; case 13 k = get(handles.k,'Value'); image = segmentation(handles.image,k,'PSO'); handles.resultImage = image; case 14 k = get(handles.k,'Value'); image = segmentation(handles.image,k,'DPSO'); handles.resultImage = image; case 15 k = get(handles.k,'Value'); image = segmentation(handles.image,k,'FODPSO'); handles.resultImage = image; case 16 k = get(handles.k,'Value'); image = (handles.image); image = SFCM2D(image,k); for i= 1:k resultImage(:,:,i) = reshape(image(i,:,:),size(handles.image,1),size(handles.image,2)); end % h = vision.AlphaBlender; % image = resultImage(:,:,1); % for i=2:k %image = step(h,image, resultImage(:,:,i)); % image = imfuse(image, resultImage(:,:,i),'blend'); % end %image = reshape(image(1,:,:),size(handles.image,1),size(handles.image,2)); image = ones(size(resultImage,1),size(resultImage,2),1,size(resultImage,3)); image(:,:,1,:) = resultImage; montage(image,'Size',[NaN 3]); case 17 [~, image] = isodata(( handles.image)); handles.resultImage = image; end guidata(hObject, handles); if (option ~= 16) imshow(handles.resultImage, 'Parent', handles.axes2); end function k_Callback(handles) set(handles.t, 'string', strcat('K : levels of segmentation = ', handles.get(k,'value')));
github
jacksky64/imageProcessing-master
FCLSM.m
.m
imageProcessing-master/segmentation/Image Segmentation & Edge Detection Toolbox/Bc project/FCMLSM/FCLSM.m
3,102
utf_8
525c470209f7e282a36c61b3edde9eae
function [imgls,opts,sls]=FCLSM(img,imgfcm,beta) img=double(img); se=5; %template radius for spatial filtering sigma=2; %spatial filter weight d0=.5; %fuzzy thresholding epsilon=1.5; %Dirac regulator %adaptive definition of penalizing item mu u=d0<=imgfcm; bwa=bwarea(u); %area of initial contour bw2=bwperim(u); bwp=sum(sum(bw2)); %peripherium of initial contour mu=bwp/bwa; %Coefficient of the internal (penalizing) energy term P(\phi); opts.mu=mu; timestep=0.2/mu; %The product timestep*mu must be less than 0.25 for stability opts.timestep=timestep; %end % fs=fspecial('disk',5); % imgs=imfilter(img,fs,'replicate'); fs=fspecial('gaussian',se,sigma); img_smooth=conv2(double(img),double(fs),'same'); [Ix,Iy]=gradient(img_smooth); f=Ix.^2+Iy.^2; g=1./(1+f); % edge indicator function. % define initial level set function as -c0, c0 % at points outside and inside of a region R, respectively. u=u-0.5; u=4*epsilon*u; sls(1,:,:)=double(u); lambda=1/mu; opts.lambda=lambda; % nu=2*imgfcm-1; % Coefficient of the weighted area term Ag(\phi); nu=-2*(2*beta*imgfcm-(1-beta)); opts.alf=nu; %Note: Choose a positive(negative) alf if the initial contour is % outside(inside) the object. % start level set evolution bGo=1; nTi=0; while bGo u=EVOLUTION(u, g, lambda, mu, nu, epsilon, timestep, 100); nTi=nTi+1; sls(nTi+1,:,:)=u; pause(0.001); imshow(img,[]);hold on; [c,h] = contour(u,[0 0],'m'); title(sprintf('Time Step: %d',nTi*100)); hold off if ~strcmp(questdlg('Continue or not?'),'Yes'),bGo=0;end pause(0.1); end imgls=u; imshow(img,[]); hold on imgt(:,:)=sls(1,:,:); [c,h] = contour(imgt,[0 0],'m'); [c,h] = contour(u,[0 0],'g','linewidth',2); totalIterNum=[num2str(nTi*100), ' iterations']; title(['Magenta: Initial; Green: Final after ', totalIterNum]); hold off %% core functions of level set methods function u = EVOLUTION(u0, g, lambda, mu, nu, epsilon, delt, numIter) u=u0; [vx,vy]=gradient(g); for k=1:numIter u=NeumannBoundCond(u); [ux,uy]=gradient(u); normDu=sqrt(ux.^2 + uy.^2 + 1e-10); Nx=ux./normDu; Ny=uy./normDu; diracU=Dirac(u,epsilon); K=curvature_central(Nx,Ny); weightedLengthTerm=lambda*diracU.*(vx.*Nx + vy.*Ny + g.*K); penalizingTerm=mu*(4*del2(u)-K); weightedAreaTerm=nu.*diracU.*g; u=u+delt*(weightedLengthTerm + weightedAreaTerm + penalizingTerm); % update the level set function end % the following functions are called by the main function EVOLUTION function f = Dirac(x, sigma) f=(1/2/sigma)*(1+cos(pi*x/sigma)); b = (x<=sigma) & (x>=-sigma); f = f.*b; function K = curvature_central(nx,ny) [nxx,junk]=gradient(nx); [junk,nyy]=gradient(ny); K=nxx+nyy; function g = NeumannBoundCond(f) % Make a function satisfy Neumann boundary condition [nrow,ncol] = size(f); g = f; g([1 nrow],[1 ncol]) = g([3 nrow-2],[3 ncol-2]); g([1 nrow],2:end-1) = g([3 nrow-2],2:end-1); g(2:end-1,[1 ncol]) = g(2:end-1,[3 ncol-2]);
github
jacksky64/imageProcessing-master
fuzzyLSM.m
.m
imageProcessing-master/segmentation/Image Segmentation & Edge Detection Toolbox/Bc project/FCMLSM/fuzzyLSM.m
3,564
utf_8
86b8ad22aa23a0e3a9951328c398a912
function [imgls,sls]=fuzzyLSM(img,imgfcm,beta) % Enhancing level set segmentation by spatial fuzzy clustering % [imgls,sls]=fuzzyLSM(img,imgfcm,fcmind,beta) % img: input grayscale image % imgfcm: the result of spatial fuzzy clustering % beta: modulating argument % imgls: the result level set function % sls: historic records of level set evolution % LI Bing Nan @ NUS, Feb 2009 % If you think it is helpful, please cite: % B.N. Li, C.K. Chui, S. Chang, S.H. Ong (2011) Integrating spatial fuzzy % clustering with level set methods for automated medical image % segmentation. Computers in Biology and Medicine 41(1) 1-10. %-------------------------------------------------------------------------- img=double(img); se=5; %template radius for spatial filtering sigma=2; %gaussian filter weight d0=.5; %fuzzy thresholding epsilon=1.5; %Dirac regulator %adaptive definition of penalizing item mu u=(d0<=imgfcm); bwa=bwarea(u); %area of initial contour bw2=bwperim(u); bwp=sum(sum(bw2)); %peripherium of initial contour mu=bwp/bwa; %Coefficient of the internal (penalizing) energy term P(\phi); timestep=0.2/mu; %The product timestep*mu must be less than 0.25 for stability %end fs=fspecial('gaussian',se,sigma); img_smooth=conv2(double(img),double(fs),'same'); [Ix,Iy]=gradient(img_smooth); f=Ix.^2+Iy.^2; g=1./(1+f); % edge indicator function. % define initial level set function as -c0, c0 % at points outside and inside of a region R, respectively. u=u-0.5; u=4*epsilon*u; sls(1,:,:)=double(u); lambda=1/mu; nu=-2*(2*beta*imgfcm-(1-beta)); %Note: Choose a positive(negative) alf if the initial contour is % outside(inside) the object. % start level set evolution bGo=1; nTi=0; while bGo u=EVOLUTION(u, g, lambda, mu, nu, epsilon, timestep, 100); nTi=nTi+1; sls(nTi+1,:,:)=u; imshow(img,[]);hold on; [c,h] = contour(u,[0 0],'m'); title(sprintf('Time Step: %d',nTi*100)); hold off pause(0.05); if ~strcmp(questdlg('Continue or not?'),'Yes'),bGo=0;end end imgls=u; imshow(img,[]); hold on imgt(:,:)=sls(1,:,:); contour(imgt,[0 0],'m'); contour(u,[0 0],'g','linewidth',2); totalIterNum=[num2str(nTi*100), ' iterations']; title(['Magenta: Initial; Green: Final after ', totalIterNum]); hold off %% core functions of level set methods function u = EVOLUTION(u0, g, lambda, mu, nu, epsilon, delt, numIter) u=u0; [vx,vy]=gradient(g); for k=1:numIter u=NeumannBoundCond(u); [ux,uy]=gradient(u); normDu=sqrt(ux.^2 + uy.^2 + 1e-10); Nx=ux./normDu; Ny=uy./normDu; diracU=Dirac(u,epsilon); K=curvature_central(Nx,Ny); weightedLengthTerm=lambda*diracU.*(vx.*Nx + vy.*Ny + g.*K); penalizingTerm=mu*(4*del2(u)-K); weightedAreaTerm=nu.*diracU.*g; u=u+delt*(weightedLengthTerm + weightedAreaTerm + penalizingTerm); % update the level set function end % the following functions are called by the main function EVOLUTION function f = Dirac(x, sigma) f=(1/2/sigma)*(1+cos(pi*x/sigma)); b = (x<=sigma) & (x>=-sigma); f = f.*b; function K = curvature_central(nx,ny) [nxx,junk]=gradient(nx); [junk,nyy]=gradient(ny); K=nxx+nyy; function g = NeumannBoundCond(f) % Make a function satisfy Neumann boundary condition [nrow,ncol] = size(f); g = f; g([1 nrow],[1 ncol]) = g([3 nrow-2],[3 ncol-2]); g([1 nrow],2:end-1) = g([3 nrow-2],2:end-1); g(2:end-1,[1 ncol]) = g(2:end-1,[3 ncol-2]);
github
jacksky64/imageProcessing-master
srm_getborders.m
.m
imageProcessing-master/segmentation/Image Segmentation & Edge Detection Toolbox/Bc project/srm/srm_getborders.m
226
utf_8
9f24b148c7e587960b326e5d9bfd11e3
function borders = srm_getborders(map) dx = conv2(map, [-1 1], 'same'); dy = conv2(map, [-1 1]', 'same'); dy(end,:) = 0; % ignore the last row of dy dx(:,end) = 0; % and the last col of dx borders = find(dx ~= 0 | dy ~= 0);
github
jacksky64/imageProcessing-master
srm.m
.m
imageProcessing-master/segmentation/Image Segmentation & Edge Detection Toolbox/Bc project/srm/srm.m
4,175
utf_8
34efb3176d6b172ea78cf7ab221e3df9
% Statistical Region Merging % % Nock, Richard and Nielsen, Frank 2004. Statistical Region Merging. IEEE Trans. Pattern Anal. Mach. Intell. 26, 11 (Nov. 2004), 1452-1458. % DOI= http://dx.doi.org/10.1109/TPAMI.2004.110 %Segmentation parameter Q; Q small few segments, Q large may segments function [maps,images]=srm(image,Qlevels) % Smoothing the image, comment this line if you work on clean or synthetic images h=fspecial('gaussian',[3 3],1); image=imfilter(image,h,'symmetric'); smallest_region_allowed=10; size_image=size(image); n_pixels=size_image(1)*size_image(2); % Compute image gradient [Ix,Iy]=srm_imgGrad(image(:,:,:)); Ix=max(abs(Ix),[],3); Iy=max(abs(Iy),[],3); normgradient=sqrt(Ix.^2+Iy.^2); Ix(:,end)=[]; Iy(end,:)=[]; [~,index]=sort(abs([Iy(:);Ix(:)])); n_levels=numel(Qlevels); maps=cell(n_levels,1); images=cell(n_levels,1); im_final=zeros(size_image); map=reshape(1:n_pixels,size_image(1:2)); % gaps=zeros(size(map)); % For future release treerank=zeros(size_image(1:2)); size_segments=ones(size_image(1:2)); image_seg=image; %Building pairs n_pairs=numel(index); idx2=reshape(map(:,1:end-1),[],1); idx1=reshape(map(1:end-1,:),[],1); pairs1=[ idx1;idx2 ]; pairs2=[ idx1+1;idx2+size_image(1) ]; for Q=Qlevels iter=find(Q==Qlevels); for i=1:n_pairs C1=pairs1(index(i)); C2=pairs2(index(i)); %Union-Find structure, here are the finds, average complexity O(1) while (map(C1)~=C1 ); C1=map(C1); end while (map(C2)~=C2 ); C2=map(C2); end % Compute the predicate, region merging test g=256; logdelta=2*log(6*n_pixels); dR=(image_seg(C1)-image_seg(C2))^2; dG=(image_seg(C1+n_pixels)-image_seg(C2+n_pixels))^2; dB=(image_seg(C1+2*n_pixels)-image_seg(C2+2*n_pixels))^2; logreg1 = min(g,size_segments(C1))*log(1.0+size_segments(C1)); logreg2 = min(g,size_segments(C2))*log(1.0+size_segments(C2)); dev1=((g*g)/(2.0*Q*size_segments(C1)))*(logreg1 + logdelta); dev2=((g*g)/(2.0*Q*size_segments(C2)))*(logreg2 + logdelta); dev=dev1+dev2; predicat=( (dR<dev) && (dG<dev) && (dB<dev) ); if (((C1~=C2)&&predicat) || xor(size_segments(C1)<=smallest_region_allowed, size_segments(C2)<=smallest_region_allowed)) % Find the new root for both regions if treerank(C1) > treerank(C2) map(C2) = C1; reg=C1; elseif treerank(C1) < treerank(C2) map(C1) = C2; reg=C2; elseif C1 ~= C2 map(C2) = C1; reg=C1; treerank(C1) = treerank(C1) + 1; end if C1~=C2 % Merge regions nreg=size_segments(C1)+size_segments(C2); image_seg(reg)=(size_segments(C1)*image_seg(C1)+size_segments(C2)*image_seg(C2))/nreg; image_seg(reg+n_pixels)=(size_segments(C1)*image_seg(C1+n_pixels)+size_segments(C2)*image_seg(C2+n_pixels))/nreg; image_seg(reg+2*n_pixels)=(size_segments(C1)*image_seg(C1+2*n_pixels)+size_segments(C2)*image_seg(C2+2*n_pixels))/nreg; size_segments(reg)=nreg; end end end % Done, building two result figures, figure 1 is the segmentation map, % figure 2 is the segmentation map with the average color in each segment while 1 map_ = map(map) ; if isequal(map_,map) ; break ; end map = map_ ; end for i=1:3 im_final(:,:,i)=image_seg(map+(i-1)*n_pixels); end images{iter}=im_final; [clusterlist,~,labels] = unique(map) ; labels=reshape(labels,size(map)); nlabels=numel(clusterlist); maps{iter}=map; bgradient = sparse(srm_boundarygradient(labels, nlabels, normgradient)); bgradient = bgradient - tril(bgradient); idx=find(bgradient>0); [~,index]=sort(bgradient(idx)); n_pairs=numel(idx); [xlabels,ylabels]=ind2sub([nlabels,nlabels],idx); pairs1=clusterlist(xlabels); pairs2=clusterlist(ylabels); end
github
jacksky64/imageProcessing-master
adaptcluster_kmeans.m
.m
imageProcessing-master/segmentation/Image Segmentation & Edge Detection Toolbox/Bc project/adaptcluster_kmeans/adaptcluster_kmeans.m
4,790
utf_8
710b9eaae8fa6dcb28751eecea74f382
function [lb,center] = adaptcluster_kmeans(im) % This code is written to implement kmeans clustering for segmenting any % Gray or Color image. There is no requirement to mention the number of cluster for % clustering. % IM - is input image to be clustered. % LB - is labeled image (Clustered Image). % CENTER - is array of cluster centers. % Execution of this code is very fast. % It generates consistent output for same image. % Written by Ankit Dixit. % January-2014. if size(im,3)>1 [lb,center] = ColorClustering(im); % Check Image is Gray or not. else [lb,center] = GrayClustering(im); end function [lb,center] = GrayClustering(gray) gray = double(gray); array = gray(:); % Copy value into an array. % distth = 25; i = 0;j=0; % Intialize iteration Counters. tic while(true) seed = mean(array); % Initialize seed Point. i = i+1; %Increment Counter for each iteration. while(true) j = j+1; % Initialize Counter for each iteration. dist = (sqrt((array-seed).^2)); % Find distance between Seed and Gray Value. distth = (sqrt(sum((array-seed).^2)/numel(array)));% Find bandwidth for Cluster Center. % distth = max(dist(:))/5; qualified = dist<distth;% Check values are in selected Bandwidth or not. newseed = mean(array(qualified));% Update mean. if isnan(newseed) % Check mean is not a NaN value. break; end if seed == newseed || j>10 % Condition for convergence and maximum iteration. j=0; array(qualified) = [];% Remove values which have assigned to a cluster. center(i) = newseed; % Store center of cluster. break; end seed = newseed;% Update seed. end if isempty(array) || i>10 % Check maximum number of clusters. i = 0; % Reset Counter. break; end end toc center = sort(center); % Sort Centers. newcenter = diff(center);% Find out Difference between two consecutive Centers. intercluster = (max(gray(:)/10));% Findout Minimum distance between two cluster Centers. center(newcenter<=intercluster)=[];% Discard Cluster centers less than distance. % Make a clustered image using these centers. vector = repmat(gray(:),[1,numel(center)]); % Replicate vector for parallel operation. centers = repmat(center,[numel(gray),1]); distance = ((vector-centers).^2);% Find distance between center and pixel value. [~,lb] = min(distance,[],2);% Choose cluster index of minimum distance. lb = reshape(lb,size(gray));% Reshape the labelled index vector. function [lb,center] = ColorClustering(im) im = double(im); red = im(:,:,1); green = im(:,:,2); blue = im(:,:,3); array = [red(:),green(:),blue(:)]; % distth = 25; i = 0;j=0; tic while(true) seed(1) = mean(array(:,1)); seed(2) = mean(array(:,2)); seed(3) = mean(array(:,3)); i = i+1; while(true) j = j+1; seedvec = repmat(seed,[size(array,1),1]); dist = sum((sqrt((array-seedvec).^2)),2); distth = 0.25*max(dist); qualified = dist<distth; newred = array(:,1); newgreen = array(:,2); newblue = array(:,3); newseed(1) = mean(newred(qualified)); newseed(2) = mean(newgreen(qualified)); newseed(3) = mean(newblue(qualified)); if isnan(newseed) break; end if (seed == newseed) | j>10 j=0; array(qualified,:) = []; center(i,:) = newseed; % center(2,i) = nnz(qualified); break; end seed = newseed; end if isempty(array) || i>10 i = 0; break; end end toc centers = sqrt(sum((center.^2),2)); [centers,idx]= sort(centers); while(true) newcenter = diff(centers); intercluster =25; %(max(gray(:)/10)); a = (newcenter<=intercluster); % center(a,:)=[]; % centers = sqrt(sum((center.^2),2)); centers(a,:) = []; idx(a,:)=[]; % center(a,:)=0; if nnz(a)==0 break; end end center1 = center; center =center1(idx,:); % [~,idxsort] = sort(centers) ; vecred = repmat(red(:),[1,size(center,1)]); vecgreen = repmat(green(:),[1,size(center,1)]); vecblue = repmat(blue(:),[1,size(center,1)]); distred = (vecred - repmat(center(:,1)',[numel(red),1])).^2; distgreen = (vecgreen - repmat(center(:,2)',[numel(red),1])).^2; distblue = (vecblue - repmat(center(:,3)',[numel(red),1])).^2; distance = sqrt(distred+distgreen+distblue); [~,label_vector] = min(distance,[],2); lb = reshape(label_vector,size(red)); %
github
jacksky64/imageProcessing-master
CoherenceFilter.m
.m
imageProcessing-master/segmentation/Image Segmentation & Edge Detection Toolbox/Bc project/GraphSeg/coherenceFilter/CoherenceFilter.m
9,898
utf_8
a3aca1656b08e401f9082f5159c4d930
function u = CoherenceFilter(u,Options) % This function COHERENCEFILTER will perform Anisotropic Diffusion of a % 2D gray/color image or 3D image volume, Which will reduce the noise in % an image while preserving the region edges, and will smooth along % the image edges removing gaps due to noise. % % Don't forget to compile the c-code by executing compile_c_files.m % % Iout = CoherenceFilter(Iin, Options) % % inputs, % Iin : 2D gray/color image or 3D image volume. Use double datatype in 2D % and single data type in 3D. Range of image data must be % approximately [0 1], for default constants. % Options : Struct with filtering options % % outputs, % Iout : The anisotropic diffusion filtered image % % Options, % Options.Scheme : The numerical diffusion scheme used % 'R', Rotation Invariant, Standard Discretization % (implicit) 5x5 kernel (Default) % 'I', Implicit Discretization (only works in 2D) % 'S', Standard Discretization % 'N', Non-negativity Discretization % Options.T : The total diffusion time (default 5) % Options.dt : Diffusion time stepsize, in case of scheme R or I % defaults to 1, in case of scheme S or N defaults to % 0.1. % Options.sigma : Sigma of gaussian smoothing before calculation of the % image Hessian, default 1. % Options.rho : Rho gives the sigma of the Gaussian smoothing of the % Hessian, default 1. % Options.verbose : Show information about the filtering, values : % 'none', 'iter' (default) , 'full' % % Constants which determine the amplitude of the diffusion smoothing in % Weickert equation % Options.C : Default 1e-10 % Options.m : Default 1 % Options.alpha : Default 0.001 % % The basis of the method used is the one introduced by Weickert: % 1, Calculate Hessian from every pixel of the gaussian smoothed input image % 2, Gaussian Smooth the Hessian, and calculate its eigenvectors and values % (Image edges give large eigenvalues, and the eigenvectors corresponding % to those large eigenvalues describe the direction of the edge) % 3, The eigenvectors are used as diffusion tensor directions. The % amplitude of the diffusion in those 3 directions is determined % by equations below. % 4, An Finite Difference scheme is used to do the diffusion % 5, Back to step 1, till a certain diffusion time is reached. % % Weickert equation 2D: % lambda1 = alpha + (1 - alpha)*exp(-C/(mu1-mu2).^(2*m)); % lambda2 = alpha; % Weickert extended to 3D: % lambda1 = alpha + (1 - alpha)*exp(-C/(mu1-mu3).^(2*m)); % lambda2 = alpha; % lambda3 = alpha; % (with mu1 the largest eigenvalue and mu3 the smallest) % % Notes: % - If the time step is choosing to large the scheme becomes unstable, this % can be seen by setting verbose to 'full'. The image variance has to % decrease every itteration if the scheme is stable. % - Weickert's equation can be found in several code files. But this is % only one of the possible diffusion equations, you can for instance % do plane smoothing instead of line smoothing by edditing "lambda2 = alpha" % to "lambda2 = alpha + (1 - alpha)*exp(-C/(mu2-mu3).^(2*m)); ", or % use the equation of Siham Tabik. % % Literature used: % - Weickert : "A Scheme for Coherence-Enhancing Diffusion Filtering % with Optimized Rotation Invariance" % - Weickert : "Anisotropic Diffusion in Image Processing", Thesis 1996 % - Laura Fritz : "Diffusion-Based Applications for Interactive Medical % Image Segmentation" % - Siham Tabik, et al. : "Multiprocessing of Anisotropic Nonlinear % Diffusion for filtering 3D image" % % example 2d, % I = im2double(imread('images/sync_noise.png')); % JR = CoherenceFilter(I,struct('T',4,'rho',10,'Scheme','R')); % JI = CoherenceFilter(I,struct('T',4,'rho',10,'Scheme','I')); % JS = CoherenceFilter(I,struct('T',4,'rho',10,'Scheme','N')); % figure, % subplot(2,2,1), imshow(I), title('Before Filtering'); % subplot(2,2,2), imshow(JR), title('Rotation Invariant Scheme'); % subplot(2,2,3), imshow(JI), title('Implicit Scheme'); % subplot(2,2,4), imshow(JI), title('Non Negative Scheme'); % % example 3d, % % First compile the c-code by executing compile_c_files.m % load('images/sphere'); % showcs3(V); % JR = CoherenceFilter(V,struct('T',50,'dt',2,'Scheme','R')); % showcs3(JR); % % Written by D.Kroon University of Twente (September 2009) % add all needed function paths try functionname='CoherenceFilter.m'; functiondir=which(functionname); functiondir=functiondir(1:end-length(functionname)); addpath([functiondir '/functions2D']) addpath([functiondir '/functions3D']) addpath([functiondir '/functions']) catch me disp(me.message); end % Default parameters defaultoptions=struct('T',2,'dt',[],'sigma', 1, 'rho', 1, 'TensorType', 1, 'C', 1e-10, 'm',1,'alpha',0.001,'C2',0.3,'m2',8,'alpha2',1,'RealDerivatives',false,'Scheme','R','verbose','iter'); if(~exist('Options','var')), Options=defaultoptions; else tags = fieldnames(defaultoptions); for i=1:length(tags) if(~isfield(Options,tags{i})), Options.(tags{i})=defaultoptions.(tags{i}); end end if(length(tags)~=length(fieldnames(Options))), warning('CoherenceFilter:unknownoption','unknown options found'); end end if(isempty(Options.dt)) switch lower(Options.Scheme) case 'r', Options.dt=1; case 'i', Options.dt=1; case 's', Options.dt=0.1; case 'n', Options.dt=0.1; otherwise error('CoherenceFilter:unknownoption','unknown scheme'); end end % Initialization dt_max = Options.dt; t = 0; % In case of 3D use single precision to save memory if(size(u,3)<4), u=double(u); else u=single(u); end % Process time %process_time=tic; tic; % Show information switch lower(Options.verbose(1)) case 'i' disp('Diffusion time Sec. Elapsed'); case 'f' disp('Diffusion time Sec. Elapsed Image mean Image variance'); end % Anisotropic diffusion main loop while (t < (Options.T-0.001)) % Update time, adjust last time step to exactly finish at the wanted % diffusion time Options.dt = min(dt_max,Options.T-t); t = t + Options.dt; tn=toc; switch lower(Options.verbose(1)) case 'n' case 'i' s=sprintf(' %5.0f %5.0f ',t,round(tn)); disp(s); case 'f' s=sprintf(' %5.0f %5.0f %13.6g %13.6g ',t,round(tn), mean(u(:)), var(u(:))); disp(s); end if(size(u,3)<4) % Check if 2D or 3D % Do a diffusion step if(strcmpi(Options.Scheme,'R@')) u=CoherenceFilterStep2D(u,Options); else u=Anisotropic_step2D(u,Options); end else % Do a diffusion step if(strcmpi(Options.Scheme,'R')) u=CoherenceFilterStep3D(u,Options); else u=Anisotropic_step3D(u,Options); end end end function u=Anisotropic_step2D(u,Options) % Perform tensor-driven diffusion filtering update % Gaussian smooth the image, for better gradients usigma=imgaussian(u,Options.sigma,4*Options.sigma); % Calculate the gradients switch lower(Options.Scheme) case 'r' ux=derivatives(usigma,'x'); uy=derivatives(usigma,'y'); case 'i' ux=derivatives(usigma,'x'); uy=derivatives(usigma,'y'); case 's' [uy,ux]=gradient(usigma); case 'n' [uy,ux]=gradient(usigma); otherwise error('CoherenceFilter:unknownoption','unknown scheme'); end % Compute the 2D structure tensors J of the image [Jxx, Jxy, Jyy] = StructureTensor2D(ux,uy,Options.rho); % Compute the eigenvectors and values of the strucure tensors, v1 and v2, mu1 and mu2 [mu1,mu2,v1x,v1y,v2x,v2y]=EigenVectors2D(Jxx,Jxy,Jyy); % Construct the edge preserving diffusion tensors D = [Dxx,Dxy;Dxy,Dyy] [Dxx,Dxy,Dyy]=ConstructDiffusionTensor2D(mu1,mu2,v1x,v1y,v2x,v2y,Options); % Do the image diffusion switch lower(Options.Scheme) case 'r' u=diffusion_scheme_2D_rotation_invariant(u,Dxx,Dxy,Dyy,Options.dt); case 'i' u=diffusion_scheme_2D_implicit(u,Dxx,Dxy,Dyy,Options.dt); case 's' u=diffusion_scheme_2D_standard(u,Dxx,Dxy,Dyy,Options.dt); case 'n' u=diffusion_scheme_2D_non_negativity(u,Dxx,Dxy,Dyy,Options.dt); otherwise error('CoherenceFilter:unknownoption','unknown scheme'); end function u=Anisotropic_step3D(u,Options) % Perform tensor-driven diffusion filtering update % Gaussian smooth the image, for better gradients usigma=imgaussian(u,Options.sigma,4*Options.sigma); % Calculate the gradients ux=derivatives(usigma,'x'); uy=derivatives(usigma,'y'); uz=derivatives(usigma,'z'); % Compute the 3D structure tensors J of the image [Jxx, Jxy, Jxz, Jyy, Jyz, Jzz] = StructureTensor3D(ux,uy,uz, Options.rho); % Free memory clear ux; clear uy; clear uz; % Compute the eigenvectors and eigenvalues of the hessian and directly % use the equation of Weickert to convert them to diffusion tensors [Dxx,Dxy,Dxz,Dyy,Dyz,Dzz]=StructureTensor2DiffusionTensor3DWeickert(Jxx,Jxy,Jxz,Jyy,Jyz,Jzz,Options); % Free memory clear J*; % Do the image diffusion switch lower(Options.Scheme) case 'r' u=diffusion_scheme_3D_rotation_invariant(u,Dxx,Dxy,Dxz,Dyy,Dyz,Dzz,Options.dt); case 'i' u=diffusion_scheme_3D_implicit(u,Dxx,Dxy,Dxz,Dyy,Dyz,Dzz,Options.dt); case 's' u=diffusion_scheme_3D_standard(u,Dxx,Dxy,Dxz,Dyy,Dyz,Dzz,Options.dt); case 'n' u=diffusion_scheme_3D_non_negativity(u,Dxx,Dxy,Dxz,Dyy,Dyz,Dzz,Options.dt); otherwise error('CoherenceFilter:unknownoption','unknown scheme'); end
github
jacksky64/imageProcessing-master
showcs3.m
.m
imageProcessing-master/segmentation/Image Segmentation & Edge Detection Toolbox/Bc project/GraphSeg/coherenceFilter/functions/showcs3.m
8,626
utf_8
34593633a0794db73b412179ff1ca339
function varargout = showcs3(varargin) % SHOWCS3 M-file for showcs3.fig % SHOWCS3, by itself, creates a new SHOWCS3 or raises the existing % singleton*. % % H = SHOWCS3 returns the handle to a new SHOWCS3 or the handle to % the existing singleton*. % % SHOWCS3('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in SHOWCS3.M with the given input arguments. % % SHOWCS3('Property','Value',...) creates a new SHOWCS3 or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before showcs3_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to showcs3_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help showcs3 % Last Modified by GUIDE v2.5 02-Apr-2008 10:10:49 % Begin initialization code - DO NOT EDIT gui_Singleton = 0; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @showcs3_OpeningFcn, ... 'gui_OutputFcn', @showcs3_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before showcs3 is made visible. function showcs3_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to showcs3 (see VARARGIN) % Choose default command line output for showcs3 handles.output = hObject; % Update handles structure guidata(hObject, handles); data.HandleWindow=gcf; set(data.HandleWindow, 'Renderer', 'opengl') hold on; axis equal; axis xy; if((~isempty(varargin))&&(numel(varargin{1})>8)) data.voxelvolume=varargin{1}; if((length(varargin)>=2)&&(length(varargin{2})==3)) data.scales=varargin{2}; else data.scales=[1 1 1]; end data.sizes=size(data.voxelvolume); data.posx=0.5; data.posy=0.5; data.posz=0.5; set(handles.slider_x,'value',data.posx); set(handles.slider_y,'value',data.posy); set(handles.slider_z,'value',data.posz); daspect(data.scales) data=showslices(data); setMyData(data); rotate3d on; view(3) else disp('Voxel volume not found'); end % UIWAIT makes showcs3 wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = showcs3_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on slider movement. function slider_x_Callback(hObject, eventdata, handles) % hObject handle to slider_x (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider data=getMyData(); data.posx=get(handles.slider_x,'value'); data=showslices(data); setMyData(data); % --- Executes during object creation, after setting all properties. function slider_x_CreateFcn(hObject, eventdata, handles) % hObject handle to slider_x (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end % --- Executes on slider movement. function slider_y_Callback(hObject, eventdata, handles) % hObject handle to slider_y (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider data=getMyData(); data.posy=get(handles.slider_y,'value'); data=showslices(data); setMyData(data); % --- Executes during object creation, after setting all properties. function slider_y_CreateFcn(hObject, eventdata, handles) % hObject handle to slider_y (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end % --- Executes on slider movement. function slider_z_Callback(hObject, eventdata, handles) % hObject handle to slider_z (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider data=getMyData(); data.posz=get(handles.slider_z,'value'); data=showslices(data); setMyData(data); % --- Executes during object creation, after setting all properties. function slider_z_CreateFcn(hObject, eventdata, handles) % hObject handle to slider_z (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end function data=showslices(data) try delete(data.h1); delete(data.h2); delete(data.h3); catch end posx=max(min(round(data.sizes(1)*data.posx),data.sizes(1)),1); posy=max(min(round(data.sizes(2)*data.posy),data.sizes(2)),1); posz=max(min(round(data.sizes(3)*data.posz),data.sizes(3)),1); if(ndims(data.voxelvolume)==3) slicexg = im2uint8(squeeze(data.voxelvolume(posx,:,:)))'; sliceyg = im2uint8(squeeze(data.voxelvolume(:,posy,:)))'; slicezg = im2uint8(squeeze(data.voxelvolume(:,:,posz)))'; slicex=ind2rgb(slicexg,gray(256)); slicey=ind2rgb(sliceyg,gray(256)); slicez=ind2rgb(slicezg,gray(256)); else slicexs = im2uint8(squeeze(data.voxelvolume(posx,:,:,:))); sliceys = im2uint8(squeeze(data.voxelvolume(:,posy,:,:))); slicezs = im2uint8(squeeze(data.voxelvolume(:,:,posz,:))); slicex=uint8(zeros([size(slicexs,2) size(slicexs,1) 3])); slicey=uint8(zeros([size(sliceys,2) size(sliceys,1) 3])); slicez=uint8(zeros([size(slicezs,2) size(slicezs,1) 3])); for i=1:3, slicex(:,:,i)=slicexs(:,:,i)'; slicey(:,:,i)=sliceys(:,:,i)'; slicez(:,:,i)=slicezs(:,:,i)'; end end slicex_x=[posx posx;posx posx]; slicex_y=[0 (data.sizes(2)-1);0 (data.sizes(2)-1)]; slicex_z=[0 0;(data.sizes(3)-1) (data.sizes(3)-1)]; slicey_x=[0 (data.sizes(1)-1);0 (data.sizes(1)-1)]; slicey_y=[posy posy;posy posy]; slicey_z=[0 0;(data.sizes(3)-1) (data.sizes(3)-1)]; slicez_x=[0 (data.sizes(1)-1);0 (data.sizes(1)-1)]; slicez_y=[0 0;(data.sizes(2)-1) (data.sizes(2)-1)]; slicez_z=[posz posz;posz posz]; data.h1=surface(slicex_x,slicex_y,slicex_z, slicex,'FaceColor','texturemap', 'EdgeColor','none', 'CDataMapping','direct','FaceAlpha',1); data.h2=surface(slicey_x,slicey_y,slicey_z, slicey,'FaceColor','texturemap', 'EdgeColor','none', 'CDataMapping','direct','FaceAlpha',1); data.h3=surface(slicez_x,slicez_y,slicez_z, slicez,'FaceColor','texturemap', 'EdgeColor','none', 'CDataMapping','direct','FaceAlpha',1); function data=getMyData() data=getappdata(gcf,'showcsdata'); function setMyData(data) setappdata(data.HandleWindow,'showcsdata',data);
github
jacksky64/imageProcessing-master
StructureTensor2DiffusionTensor3DWeickert.m
.m
imageProcessing-master/segmentation/Image Segmentation & Edge Detection Toolbox/Bc project/GraphSeg/coherenceFilter/functions3D/StructureTensor2DiffusionTensor3DWeickert.m
1,567
utf_8
1e02eb447c16d2e5c366e997f1bca437
function [Dxx,Dxy,Dxz,Dyy,Dyz,Dzz]=StructureTensor2DiffusionTensor3DWeickert(Jxx,Jxy,Jxz,Jyy,Jyz,Jzz,Options) % From Structure Tensor to Diffusion Tensor, a 3D implementation of the 2D % equations by Weickert % % [Dxx,Dxy,Dxz,Dyy,Dyz,Dzz]=StructureTensor2DiffusionTensor3DWeickert(Jxx,Jxy,Jxz,Jyy,Jyz,Jzz,Options) % % Function is written by D.Kroon University of Twente (September 2009) % Compute the eigenvectors and values of the structure tensors, v1, v2 % and v3, mu1, mu2 and mu3 [mu1,mu2,mu3,v3x,v3y,v3z,v2x,v2y,v2z,v1x,v1y,v1z]=EigenVectors3D(Jxx, Jxy, Jxz, Jyy, Jyz, Jzz); [Dxx,Dxy,Dxz,Dyy,Dyz,Dzz]=ConstructDiffusionTensor3D(v1x,v1y,v1z,v2x,v2y,v2z,v3x,v3y,v3z,mu1,mu2,mu3,Options); function [Dxx,Dxy,Dxz,Dyy,Dyz,Dzz]=ConstructDiffusionTensor3D(v1x,v1y,v1z,v2x,v2y,v2z,v3x,v3y,v3z,mu1,mu2,mu3,Options) % Construct the edge preserving diffusion tensors D = [Dxx,Dxy,Dxz;Dxy,Dyy,Dyz;Dxz,Dyz,Dzz] % Scaling of diffusion tensors di=(mu1-mu3); di((di<1e-15)&(di>-1e-15))=1e-15; lambda1 = Options.alpha + (1 - Options.alpha)*exp(-Options.C./di.^(2*Options.m)); lambda2 = Options.alpha; lambda3 = Options.alpha; % Construct the tensors Dxx = lambda1.*v1x.^2 + lambda2.*v2x.^2 + lambda3.*v3x.^2; Dyy = lambda1.*v1y.^2 + lambda2.*v2y.^2 + lambda3.*v3y.^2; Dzz = lambda1.*v1z.^2 + lambda2.*v2z.^2 + lambda3.*v3z.^2; Dxy = lambda1.*v1x.*v1y + lambda2.*v2x.*v2y + lambda3.*v3x.*v3y; Dxz = lambda1.*v1x.*v1z + lambda2.*v2x.*v2z + lambda3.*v3x.*v3z; Dyz = lambda1.*v1y.*v1z + lambda2.*v2y.*v2z + lambda3.*v3y.*v3z;
github
jacksky64/imageProcessing-master
drawEdge.m
.m
imageProcessing-master/computationalGeometry/geom2d/geom2d/drawEdge.m
3,439
utf_8
6bd3883bf488326d6364143f61f8ae42
function varargout = drawEdge(varargin) %DRAWEDGE Draw an edge given by 2 points % % drawEdge(x1, y1, x2, y2); % draw an edge between the points (x1 y1) and (x2 y2). % % drawEdge([x1 y1 x2 y2]) ; % drawEdge([x1 y1], [x2 y2]); % specify data either as bundled edge, or as 2 points % % The function supports 3D edges: % drawEdge([x1 y1 z1 x2 y2 z2]); % drawEdge([x1 y1 z1], [x2 y2 z2]); % drawEdge(x1, y1, z1, x2, y2, z2); % % Arguments can be single values or array of size [N*1]. In this case, % the function draws multiple edges. % % H = drawEdge(..., OPT), with OPT being a set of pairwise options, can % specify color, line width and so on... % % H = drawEdge(...) return handle(s) to created edges(s) % % See also: % edges2d, drawCenteredEdge, drawLine % % --------- % author : David Legland % INRA - TPV URPOI - BIA IMASTE % created the 31/10/2003. % % HISTORY % 19/02/2004 add support for arrays of edges. % 31/03/2004 change format of edges to [P1 P2] and variants. % 28/11/2004 add support for 3D edges % 01/08/2005 add support for drawing options % 31/05/2007 update doc, and code makeup % 03/08/2010 re-organize code % separate edge and optional arguments [ax edge options] = parseInputArguments(varargin{:}); % draw the edges if size(edge, 2) == 4 h = drawEdge_2d(ax, edge, options); else h = drawEdge_3d(ax, edge, options); end % eventually return handle to created edges if nargout > 0 varargout = {h}; end function h = drawEdge_2d(ax, edge, options) h = -1 * ones(size(edge, 1), 1); for i = 1:size(edge, 1) if isnan(edge(i,1)) continue; end h(i) = plot(ax, edge(i, [1 3]), edge(i, [2 4]), options{:}); end function h = drawEdge_3d(ax, edge, options) h = -1 * ones(size(edge, 1), 1); for i = 1:size(edge, 1) if isnan(edge(i,1)) continue; end h(i) = plot3(ax, edge(i, [1 4]), edge(i, [2 5]), edge(i, [3 6]), options{:}); end function [ax edge options] = parseInputArguments(varargin) % extract handle of axis to draw on if isAxisHandle(varargin{1}) ax = varargin{1}; varargin(1) = []; else ax = gca; end % find the number of arguments defining edges nbVal = 0; for i = 1:length(varargin) if isnumeric(varargin{i}) nbVal = nbVal+1; else % stop at the first non-numeric value break; end end % extract drawing options options = varargin(nbVal+1:end); % ensure drawing options have correct format if length(options) == 1 options = [{'color'}, options]; end % extract edges characteristics switch nbVal case 1 % all parameters in a single array edge = varargin{1}; case 2 % parameters are two points, or two arrays of points, of size N*2. p1 = varargin{1}; p2 = varargin{2}; edge = [p1 p2]; case 4 % parameters are 4 parameters of the edge : x1 y1 x2 and y2 edge = [varargin{1} varargin{2} varargin{3} varargin{4}]; case 6 % parameters are 6 parameters of the edge : x1 y1 z1 x2 y2 and z2 edge = [varargin{1} varargin{2} varargin{3} varargin{4} varargin{5} varargin{6}]; otherwise error('drawEdge:WrongNumberOfParameters', 'Wrong number of parameters'); end
github
jacksky64/imageProcessing-master
enclosingCircle.m
.m
imageProcessing-master/computationalGeometry/geom2d/geom2d/enclosingCircle.m
1,890
utf_8
1ee6df61c95316d1cf6c7fac10c49dc4
function circle = enclosingCircle(pts) %ENCLOSINGCIRCLE Find the minimum circle enclosing a set of points. % % CIRCLE = enclosingCircle(POINTS); % compute cirlce CIRCLE=[xc yc r] which enclose all points POINTS given % as an [Nx2] array. % % % Rewritten from a file from % Yazan Ahed ([email protected]) % % which was rewritten from a Java applet by Shripad Thite: % http://heyoka.cs.uiuc.edu/~thite/mincircle/ % % See also: % circles2d, points2d, boxes2d, circumCircle % % --------- % author : David Legland % INRA - TPV URPOI - BIA IMASTE % created the 07/07/2005. % % works on convex hull : it is faster pts = pts(convhull(pts(:,1), pts(:,2)), :); circle = recurseCircle(size(pts, 1), pts, 1, zeros(3, 2)); function circ = recurseCircle(n, p, m, b) % n: number of points given % m: an argument used by the function. Always use 1 for m. % bnry: an argument (3x2 array) used by the function to set the points that % determines the circle boundry. You have to be careful when choosing this % array's values. I think the values should be somewhere outside your points % boundary. For my case, for example, I know the (x,y) I have will be something % in between (-5,-5) and (5,5), so I use bnry as: % [-10 -10 % -10 -10 % -10 -10] if m==4 circ = createCircle(b(1,:), b(2,:), b(3,:)); return; end circ = [Inf Inf 0]; if m == 2 circ = [b(1,1:2) 0]; elseif m == 3 c = (b(1,:) + b(2,:))/2; circ = [c distancePoints(b(1,:), c)]; end for i = 1:n if distancePoints(p(i,:), circ(1:2)) > circ(3) if sum(b(:,1)==p(i,1) & b(:,2)==p(i,2)) == 0 b(m,:) = p(i,:); circ = recurseCircle(i, p, m+1, b); end end end
github
jacksky64/imageProcessing-master
polynomialCurveSetFit.m
.m
imageProcessing-master/computationalGeometry/geom2d/polynomialCurves2d/polynomialCurveSetFit.m
6,539
utf_8
7dca1c7b8d6bdf724a0298ab6004b13f
function varargout = polynomialCurveSetFit(seg, varargin) %POLYNOMIALCURVESETFIT Fit a set of polynomial curves to a segmented image % % COEFS = polynomialCurveSetFit(IMG); % COEFS = polynomialCurveSetFit(IMG, DEG); % Result is a cell array of matrices. Each matrix is DEG+1-by-2, and % contains coefficients of polynomial curve for each coordinate. % IMG is first binarised, then skeletonized. Each cure % % [COEFS LBL] = polynomialCurveSetFit(...); % also returns an image of labels for the segmented curves. The max label % is the number of curves, and the length of COEFS. % % Requires the toolboxes: % - Optimization % - Image Processing % % Example % % Fit a set of curves to a binary skeleton % img = imread('circles.png'); % % compute skeleton, and ensure one-pixel thickness % skel = bwmorph(img, 'skel', 'Inf'); % skel = bwmorph(skel, 'shrink'); % figure; imshow(skel==0) % coeffs = polynomialCurveSetFit(skel, 2); % % Display segmented image with curves % figure; imshow(~img); hold on; % for i = 1:length(coeffs) % hc = drawPolynomialCurve([0 1], coeffs{i}); % set(hc, 'linewidth', 2, 'color', 'g'); % end % % See also % polynomialCurves2d, polynomialCurveFit % % ------ % Author: David Legland % e-mail: [email protected] % Created: 2007-03-21 % Copyright 2007 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas. %% Initialisations % default degree for curves deg = 2; if ~isempty(varargin) deg = varargin{1}; end % ensure image is binary seg = seg > 0; %% Extract branching points and terminating points % compute image of end points imgEndPoints = imfilter(double(seg), ones([3 3])) .* seg == 2; % compute centroids of end points lblEndPoints = bwlabel(imgEndPoints, 4); regEndPoints = bwconncomp(imgEndPoints, 4); struct = regionprops(regEndPoints, 'Centroid'); endPoints = cat(1, struct.Centroid); % compute image of multiple points (intersections between curves) imgBranching = imfilter(double(seg), ones([3 3])) .* seg > 3; % compute coordinate of nodes, as centroids of the multiple points lblBranching = bwlabel(imgBranching, 4); regBranching = bwconncomp(imgBranching, 4); struct = regionprops(regBranching, 'Centroid'); branchPoints = cat(1, struct.Centroid); % list of nodes (all categories) nodes = [branchPoints; endPoints]; % image of node labels lblNodes = lblBranching; lblNodes(lblEndPoints > 0) = lblEndPoints(lblEndPoints > 0) + size(branchPoints, 1); % isolate branches imgBranches = seg & ~imgBranching & ~imgEndPoints; lblBranches = bwlabel(imgBranches, 8); % number of curves nBranches = max(lblBranches(:)); % allocate memory coefs = cell(nBranches, 1); % For each curve, find interpolated polynomial curve for i = 1:nBranches %disp(i); % extract points corresponding to current curve imgBranch = lblBranches == i; points = chainPixels(imgBranch); % if number of points is not sufficient, simply create a line segment if size(points, 1) < max(deg+1-2, 2) % find labels of nodes inds = unique(lblNodes(imdilate(imgBranch, ones(3,3)))); inds = inds(inds~=0); if length(inds)<2 disp(['Could not find extremities of branch number ' num2str(i)]); coefs{i} = [0 0;0 0]; continue; end % consider extremity nodes node0 = nodes(inds(1),:); node1 = nodes(inds(2),:); % use only a linear approximation xc = zeros(1, deg+1); yc = zeros(1, deg+1); xc(1) = node0(1); yc(1) = node0(2); xc(2) = node1(1)-node0(1); yc(2) = node1(2)-node0(2); % assigne au tableau de courbes coefs{i} = [xc;yc]; % next branch continue; end % find nodes closest to first and last points of the current curve [dist, ind0] = minDistancePoints(points(1, :), nodes); %#ok<*ASGLU> [dist, ind1] = minDistancePoints(points(end, :), nodes); % add nodes to the curve. points = [nodes(ind0,:); points; nodes(ind1,:)]; %#ok<AGROW> % parametrization of the polyline t = parametrize(points); t = t/max(t); % fit a polynomial curve to the set of points [xc yc] = polynomialCurveFit(... t, points, deg, ... 0, {points(1,1), points(1,2)},... 1, {points(end,1), points(end,2)}); % stores result coefs{i} = [xc ; yc]; end %% Post-processing % manage outputs if nargout == 1 varargout = {coefs}; elseif nargout == 2 varargout = {coefs, lblBranches}; end function points = chainPixels(img, varargin) %CHAINPIXELS return the list of points which constitute a curve on image % output = chainPixels(input) % % Example % chainPixels % % See also % % ------ % Author: David Legland % e-mail: [email protected] % Created: 2007-03-21 % Copyright 2007 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas. conn = 8; if ~isempty(varargin) conn = varargin{1}; end % matrice de voisinage if conn==4 f = [0 1 0;1 1 1;0 1 0]; elseif conn==8 f = ones([3 3]); end % find extremity points nb = imfilter(double(img), f).*img; imgEnding = nb==2 | nb==1; [yi xi] = find(imgEnding); % extract coordinates of points [y x] = find(img); % index of first point if isempty(xi) % take arbitrary point ind = 1; else ind = find(x==xi(1) & y==yi(1)); end % allocate memory points = zeros(length(x), 2); if conn==8 for i=1:size(points, 1) % avoid multiple neighbors (can happen in loops) ind = ind(1); % add current point to chained curve points(i,:) = [x(ind) y(ind)]; % remove processed coordinate x(ind) = []; y(ind) = []; % find next candidate ind = find(abs(x-points(i,1))<=1 & abs(y-points(i,2))<=1); end else for i=1:size(points, 1) % avoid multiple neighbors (can happen in loops) ind = ind(1); % add current point to chained curve points(i,:) = [x(ind) y(ind)]; % remove processed coordinate x(ind) = []; y(ind) = []; % find next candidate ind = find(abs(x-points(i,1)) + abs(y-points(i,2)) <=1 ); end end
github
jacksky64/imageProcessing-master
polynomialCurvePosition.m
.m
imageProcessing-master/computationalGeometry/geom2d/polynomialCurves2d/polynomialCurvePosition.m
2,965
utf_8
e8933d9b90e0b043fc8392746e0be496
function pos = polynomialCurvePosition(tBounds, varargin) %POLYNOMIALCURVEPOSITION Compute position on a curve for a given length % % POS = polynomialCurvePosition(T, XCOEF, YCOEF, L) % XCOEF and YCOEF are row vectors of coefficients, in the form: % [a0 a1 a2 ... an] % T is a 1x2 row vector, containing the bounds of the parametrization % variable: T = [T0 T1], with T taking all values between T0 and T1. % L is the geodesic length corresponding to the searched position. % POS is a scalar, verifying relation: % L = polynomialCurveLength([T(1) POS], XCOEF, YCOEF); % % POS = polynomialCurvePosition(T, COEFS, L) % COEFS is either a 2xN matrix (one row for the coefficients of each % coordinate), or a cell array. % % POS = polynomialCurvePosition(..., TOL) % TOL is the tolerance fo computation (absolute). % % See also % polynomialCurves2d % % ------ % Author: David Legland % e-mail: [email protected] % Created: 2007-02-26 % Copyright 2007 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas. % parametrization bounds t0 = tBounds(1); t1 = tBounds(end); % polynomial coefficients for each coordinate var = varargin{1}; if iscell(var) xCoef = var{1}; yCoef = var{2}; varargin(1) = []; elseif size(var, 1)==1 xCoef = varargin{1}; yCoef = varargin{2}; varargin(1:2)=[]; else xCoef = var(1,:); yCoef = var(2,:); varargin(1)=[]; end % geodesic length corresponding to searched position L = varargin{1}; varargin(1)=[]; % tolerance tol = 1e-6; if ~isempty(varargin) tol = varargin{1}; end % compute derivative of the polynomial dx = polynomialDerivate(xCoef); dy = polynomialDerivate(yCoef); % convert to format of polyval dx = dx(end:-1:1); dy = dy(end:-1:1); % avoid warning for t=0 warning off 'MATLAB:quad:MinStepSize' % set up precision for t options = optimset('TolX', tol); % starting point, located in the middle of the paramtrization domain ts = (t0+t1)/2; % compute parameter corresponding to geodesic position by solving g(t)-tg=0 pos = fzero(@(t)funCurveLength(t0, t, dx, dy, tol)- L, ts, options); function res = funCurveLength(t0, t1, c1, c2, varargin) %FUNCURVELENGTH return the length of polynomial curve arc % output = funCurveLength(t0, t1, c1, c2) % t0 and t1 are the limits of the integral % c1 and c2 are derivative polynoms of each coordinate parametrization, % given from greater order to lower order (polyval convention). % c1 = [an a_n-1 ... a2 a1 a0]. % % Example % funCurveLength(0, 1, C2, C2); % funCurveLength(0, 1, C2, C2, RES); % RES is the resolution (ex: 1e-6). % % See also % % % ------ % Author: David Legland % e-mail: [email protected] % Created: 2007-02-14 % Copyright 2007 INRA - BIA PV Nantes - MIAJ Jouy-en-Josas. res = quad(@(t)sqrt(polyval(c1, t).^2+polyval(c2, t).^2), t0, t1, varargin{:});
github
jacksky64/imageProcessing-master
ShowLRImages.m
.m
imageProcessing-master/SuperResolution/Visualization/ShowLRImages.m
1,991
utf_8
0ddc97784ff38d0ac6eaf73615d4e62a
% Author: Victor May % Contact: mayvic(at)gmail(dot)com % $Date: 2011-11-19 $ % $Revision: $ % % Copyright 2011, Victor May % % All Rights Reserved % % All commercial use of this software, whether direct or indirect, is % strictly prohibited including, without limitation, incorporation into in % a commercial product, use in a commercial service, or production of other % artifacts for commercial purposes. % % Permission to use, copy, modify, and distribute this software and its % documentation for research purposes is hereby granted without fee, % provided that the above copyright notice appears in all copies and that % both that copyright notice and this permission notice appear in % supporting documentation, and that the name of the author % not be used in advertising or publicity pertaining to % distribution of the software without specific, written prior permission. % % For commercial uses contact the author. % % THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO % THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND % FITNESS FOR ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE % LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL % DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR % PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS % ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF % THIS SOFTWARE. % This function displays a set of low-resolution images, provided in a cell % array. function ShowLRImages(images) numCols = ceil(sqrt(numel(images))); numRows = numCols; for i = 1 : numRows for j = 1 : numCols imageInd = (i - 1) * numCols + j; subplot(numCols, numRows, imageInd); imshow(images{imageInd}); hold on; title(sprintf('Low-Res Image No.%d', imageInd)); end end end
github
jacksky64/imageProcessing-master
SynthDataset.m
.m
imageProcessing-master/SuperResolution/TestUtils/SynthDataset.m
2,989
utf_8
9bf1d7906f16583abaee6e20996e96e9
% Author: Victor May % Contact: mayvic(at)gmail(dot)com % $Date: 2011-11-19 $ % $Revision: $ % % Copyright 2011, Victor May % % All Rights Reserved % % All commercial use of this software, whether direct or indirect, is % strictly prohibited including, without limitation, incorporation into in % a commercial product, use in a commercial service, or production of other % artifacts for commercial purposes. % % Permission to use, copy, modify, and distribute this software and its % documentation for research purposes is hereby granted without fee, % provided that the above copyright notice appears in all copies and that % both that copyright notice and this permission notice appear in % supporting documentation, and that the name of the author % not be used in advertising or publicity pertaining to % distribution of the software without specific, written prior permission. % % For commercial uses contact the author. % % THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO % THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND % FITNESS FOR ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE % LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL % DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR % PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS % ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF % THIS SOFTWARE. % This function creates a synthetic dataset for test the SR algorithm. % It's inputs are a reference image, a blur sigma, and a number of low-res % images to be generated. % The outputs are a set of randomly translated low-res images, their % translation offsets, and the original image cropped to the frame that can % be restored from the low-res image set (their common area). function [ images offsets croppedOriginal ] = SynthDataset(im, numImages, blurSigma) padRatio = 0.2; workingRowSub = round(0.5 * padRatio * size(im, 1)) : round((1 - 0.5 * padRatio) * size(im, 1)); workingColSub = round(0.5 * padRatio * size(im, 2)) : round((1 - 0.5 * padRatio) * size(im, 2)); croppedOriginal = im(workingRowSub, workingColSub); offsets(1, :) = [ 0 0 ]; images{1} = im(workingRowSub, workingColSub); for i = 2 : numImages offsets(i, :) = 2 * rand - 1; offsetRowSub = workingRowSub - offsets(i, 2); offsetColSub = workingColSub - offsets(i, 1); [ x y ] = meshgrid(1 : size(im, 2), 1 : size(im, 1)); [ x2 y2 ] = meshgrid(offsetColSub, offsetRowSub); images{i} = interp2(x, y, im, x2, y2); end blurKernel = fspecial('gaussian', 3, blurSigma); for i = 1 : numImages images{i} = conv2(images{i}, blurKernel, 'same'); curIm = images{i}; images{i} = curIm(2 : 2 : end - 1, 2 : 2 : end - 1); end end
github
jacksky64/imageProcessing-master
SREquations.m
.m
imageProcessing-master/SuperResolution/Algorithm/SREquations.m
4,605
utf_8
46a4c282949824aa944ff5b3431b2778
% Author: Victor May % Contact: mayvic(at)gmail(dot)com % $Date: 2011-11-19 $ % $Revision: $ % % Copyright 2011, Victor May % % All Rights Reserved % % All commercial use of this software, whether direct or indirect, is % strictly prohibited including, without limitation, incorporation into in % a commercial product, use in a commercial service, or production of other % artifacts for commercial purposes. % % Permission to use, copy, modify, and distribute this software and its % documentation for research purposes is hereby granted without fee, % provided that the above copyright notice appears in all copies and that % both that copyright notice and this permission notice appear in % supporting documentation, and that the name of the author % not be used in advertising or publicity pertaining to % distribution of the software without specific, written prior permission. % % For commercial uses contact the author. % % THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO % THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND % FITNESS FOR ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE % LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL % DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR % PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS % ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF % THIS SOFTWARE. % Creates the Super-Resolution linear equations for the given data. % The imaging model implemented here is spatial translation->blur->decimation. % The boundary conditions are circular. % The output arguments lhs and rhs are the left-hand side and right-hand % sides of a linear system whose solution is the super-resolution image. function [ lhs rhs ] = SREquations(images, offsets, blurSigma) lhs = []; rhs = []; superSize = 2 * size(images{1}) + [ 1 1 ]; for i = 1 : numel(images) transMat = TransMat(superSize, offsets(i, :)); blurMat = BlurMat(superSize, blurSigma); decMat = DecMat(superSize); curLhs = decMat * blurMat * transMat; curRhs = images{i}; lhs = [ lhs ; curLhs ]; rhs = [ rhs ; curRhs(:) ]; end end % Creates a translation operator. function transMat = TransMat(superSize, offsets) transposeMat = TransposeMat(superSize); transMat = ... transposeMat * TransMatY(superSize, offsets(1)) ... * transposeMat * TransMatY(superSize, offsets(2)); end % Creates a translation operator for the image Y axis. function transMatX = TransMatY(superSize, offset) row1 = zeros(1, prod(superSize)); nzInd = floor(1 - offset) : ceil(1 - offset); filterValues = LinearKernel(1 - offset - nzInd); nzInd(nzInd < 1) = prod(superSize) - nzInd(nzInd < 1); row1(nzInd) = filterValues; col1 = zeros(1, prod(superSize)); col1(1) = row1(1); col1(2) = row1(end); transMatX = sptoeplitz(col1, row1); end % Creates a matrix transposition operator. function transposeMat = TransposeMat(superSize) [ row col ] = meshgrid(1 : superSize(1), 1 : superSize(2)); inputPixInd = sub2ind(superSize, row, col); outputPixInd = sub2ind(superSize, col, row); transposeMat = sparse(outputPixInd, inputPixInd, ones(size(outputPixInd))); end % Creates a blurring operator. function blurMat = BlurMat(superSize, blurSigma) transposeMat = TransposeMat(superSize); blurMat = ... transposeMat * BlurMatY(superSize, blurSigma) ... * transposeMat * BlurMatY(superSize, blurSigma); end % Creates a blurring operator for the Y axis. function blurMatY = BlurMatY(superSize, blurSigma) blurKernel = GaussianKernel(-1 : 1, blurSigma); blurKernel = blurKernel ./ sum(blurKernel(:)); row1 = zeros(1, prod(superSize)); row1([ end 1 2 ] ) = blurKernel; col1 = zeros(1, prod(superSize)); col1(1) = row1(1); col1(2) = row1(2); blurMatY = sptoeplitz(col1, row1); end % Creates a decimation operator. function decMat = DecMat(superSize) sampledSize = 0.5 * (superSize - 1); [ outputRow outputCol ] = meshgrid(1 : sampledSize(1), 1 : sampledSize(2)); inputRow = 2 * outputRow; inputCol = 2 * outputCol; inputInd = sub2ind(superSize, inputRow, inputCol); outputInd = sub2ind(sampledSize, outputRow, outputCol); decMat = sparse(outputInd, inputInd, ones(numel(outputInd), 1), prod(sampledSize), prod(superSize)); end
github
jacksky64/imageProcessing-master
GaussianKernel.m
.m
imageProcessing-master/SuperResolution/Algorithm/GaussianKernel.m
1,580
utf_8
4008eefe6d6a055b98ddb93a345ea20c
% Author: Victor May % Contact: mayvic(at)gmail(dot)com % $Date: 2011-11-19 $ % $Revision: $ % % Copyright 2011, Victor May % % All Rights Reserved % % All commercial use of this software, whether direct or indirect, is % strictly prohibited including, without limitation, incorporation into in % a commercial product, use in a commercial service, or production of other % artifacts for commercial purposes. % % Permission to use, copy, modify, and distribute this software and its % documentation for research purposes is hereby granted without fee, % provided that the above copyright notice appears in all copies and that % both that copyright notice and this permission notice appear in % supporting documentation, and that the name of the author % not be used in advertising or publicity pertaining to % distribution of the software without specific, written prior permission. % % For commercial uses contact the author. % % THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO % THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND % FITNESS FOR ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE % LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL % DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR % PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS % ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF % THIS SOFTWARE. function y = GaussianKernel(x, sigma) y = exp(-(x.^2) ./ (2 * sigma^2)); end
github
jacksky64/imageProcessing-master
LinearKernel.m
.m
imageProcessing-master/SuperResolution/Algorithm/LinearKernel.m
1,651
utf_8
faa46fcf18cc9d76810196cb3030e3fb
% Author: Victor May % Contact: mayvic(at)gmail(dot)com % $Date: 2011-11-19 $ % $Revision: $ % % Copyright 2011, Victor May % % All Rights Reserved % % All commercial use of this software, whether direct or indirect, is % strictly prohibited including, without limitation, incorporation into in % a commercial product, use in a commercial service, or production of other % artifacts for commercial purposes. % % Permission to use, copy, modify, and distribute this software and its % documentation for research purposes is hereby granted without fee, % provided that the above copyright notice appears in all copies and that % both that copyright notice and this permission notice appear in % supporting documentation, and that the name of the author % not be used in advertising or publicity pertaining to % distribution of the software without specific, written prior permission. % % For commercial uses contact the author. % % THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO % THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND % FITNESS FOR ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE % LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL % DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR % PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS % ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF % THIS SOFTWARE. function y = LinearKernel(x) aboveThresh = abs(x) >= 1; y(aboveThresh) = 0; y(~aboveThresh) = 1 - abs(x(~aboveThresh)); end
github
jacksky64/imageProcessing-master
GradientDescent.m
.m
imageProcessing-master/SuperResolution/Algorithm/GradientDescent.m
2,025
utf_8
aa5a1f6cd526eb796b6ee62be58549d1
% Author: Victor May % Contact: mayvic(at)gmail(dot)com % $Date: 2011-11-19 $ % $Revision: $ % % Copyright 2011, Victor May % % All Rights Reserved % % All commercial use of this software, whether direct or indirect, is % strictly prohibited including, without limitation, incorporation into in % a commercial product, use in a commercial service, or production of other % artifacts for commercial purposes. % % Permission to use, copy, modify, and distribute this software and its % documentation for research purposes is hereby granted without fee, % provided that the above copyright notice appears in all copies and that % both that copyright notice and this permission notice appear in % supporting documentation, and that the name of the author % not be used in advertising or publicity pertaining to % distribution of the software without specific, written prior permission. % % For commercial uses contact the author. % % THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO % THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND % FITNESS FOR ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHOR BE % LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL % DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR % PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS % ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF % THIS SOFTWARE. % A simple implementation of a gradient descent optimization. function x = GradientDescent(lhs, rhs, initialGuess) maxIter = 100; iter = 0; eps = 0.01; x = initialGuess; res = lhs' * (rhs - lhs * x); mse = res' * res; mse0 = mse; while (iter < maxIter && mse > eps^2 * mse0) res = lhs' * (rhs - lhs * x); x = x + res; mse = res' * res; fprintf(1, 'Gradient Descent Iteration %d mean-square error %3.3f\n', iter, mse); iter = iter + 1; end end
github
jacksky64/imageProcessing-master
xml_write.m
.m
imageProcessing-master/xmlIO/xml_write.m
18,772
utf_8
4f952d9ca0351040dbffeb946e877bb0
function DOMnode = xml_write(filename, tree, RootName, Pref) %XML_WRITE Writes Matlab data structures to XML file % % DESCRIPTION % xml_write( filename, tree) Converts Matlab data structure 'tree' containing % cells, structs, numbers and strings to Document Object Model (DOM) node % tree, then saves it to XML file 'filename' using Matlab's xmlwrite % function. Optionally one can also use alternative version of xmlwrite % function which directly calls JAVA functions for XML writing without % MATLAB middleware. This function is provided as a patch to existing % bugs in xmlwrite (in R2006b). % % xml_write(filename, tree, RootName, Pref) allows you to specify % additional preferences about file format % % DOMnode = xml_write([], tree) same as above except that DOM node is % not saved to the file but returned. % % INPUT % filename file name % tree Matlab structure tree to store in xml file. % RootName String with XML tag name used for root (top level) node % Optionally it can be a string cell array storing: Name of % root node, document "Processing Instructions" data and % document "comment" string % Pref Other preferences: % Pref.ItemName - default 'item' - name of a special tag used to % itemize cell or struct arrays % Pref.XmlEngine - let you choose the XML engine. Currently default is % 'Xerces', which is using directly the apache xerces java file. % Other option is 'Matlab' which uses MATLAB's xmlwrite and its % XMLUtils java file. Both options create identical results except in % case of CDATA sections where xmlwrite fails. % Pref.CellItem - default 'true' - allow cell arrays to use 'item' % notation. See below. % Pref.RootOnly - default true - output variable 'tree' corresponds to % xml file root element, otherwise it correspond to the whole file. % Pref.StructItem - default 'true' - allow arrays of structs to use % 'item' notation. For example "Pref.StructItem = true" gives: % <a> % <b> % <item> ... <\item> % <item> ... <\item> % <\b> % <\a> % while "Pref.StructItem = false" gives: % <a> % <b> ... <\b> % <b> ... <\b> % <\a> % % % Several special xml node types can be created if special tags are used % for field names of 'tree' nodes: % - node.CONTENT - stores data section of the node if other fields % (usually ATTRIBUTE are present. Usually data section is stored % directly in 'node'. % - node.ATTRIBUTE.name - stores node's attribute called 'name'. % - node.COMMENT - create comment child node from the string. For global % comments see "RootName" input variable. % - node.PROCESSING_INSTRUCTIONS - create "processing instruction" child % node from the string. For global "processing instructions" see % "RootName" input variable. % - node.CDATA_SECTION - stores node's CDATA section (string). Only works % if Pref.XmlEngine='Xerces'. For more info, see comments of F_xmlwrite. % - other special node types like: document fragment nodes, document type % nodes, entity nodes and notation nodes are not being handled by % 'xml_write' at the moment. % % OUTPUT % DOMnode Document Object Model (DOM) node tree in the format % required as input to xmlwrite. (optional) % % EXAMPLES: % MyTree=[]; % MyTree.MyNumber = 13; % MyTree.MyString = 'Hello World'; % xml_write('test.xml', MyTree); % type('test.xml') % %See also xml_tutorial.m % % See also % xml_read, xmlread, xmlwrite % % Written by Jarek Tuszynski, SAIC, jaroslaw.w.tuszynski_at_saic.com %% Check Matlab Version v = ver('MATLAB'); v = str2double(regexp(v.Version, '\d.\d','match','once')); if (v<7) error('Your MATLAB version is too old. You need version 7.0 or newer.'); end %% default preferences DPref.TableName = {'tr','td'}; % name of a special tags used to itemize 2D cell arrays DPref.ItemName = 'item'; % name of a special tag used to itemize 1D cell arrays DPref.StructItem = true; % allow arrays of structs to use 'item' notation DPref.CellItem = true; % allow cell arrays to use 'item' notation DPref.StructTable= 'Html'; DPref.CellTable = 'Html'; DPref.XmlEngine = 'Matlab'; % use matlab provided XMLUtils %DPref.XmlEngine = 'Xerces'; % use Xerces xml generator directly DPref.PreserveSpace = false; % Preserve or delete spaces at the beggining and the end of stings? RootOnly = true; % Input is root node only GlobalProcInst = []; GlobalComment = []; GlobalDocType = []; %% read user preferences if (nargin>3) if (isfield(Pref, 'TableName' )), DPref.TableName = Pref.TableName; end if (isfield(Pref, 'ItemName' )), DPref.ItemName = Pref.ItemName; end if (isfield(Pref, 'StructItem')), DPref.StructItem = Pref.StructItem; end if (isfield(Pref, 'CellItem' )), DPref.CellItem = Pref.CellItem; end if (isfield(Pref, 'CellTable')), DPref.CellTable = Pref.CellTable; end if (isfield(Pref, 'StructTable')), DPref.StructTable= Pref.StructTable; end if (isfield(Pref, 'XmlEngine' )), DPref.XmlEngine = Pref.XmlEngine; end if (isfield(Pref, 'RootOnly' )), RootOnly = Pref.RootOnly; end if (isfield(Pref, 'PreserveSpace')), DPref.PreserveSpace = Pref.PreserveSpace; end end if (nargin<3 || isempty(RootName)), RootName=inputname(2); end if (isempty(RootName)), RootName='ROOT'; end if (iscell(RootName)) % RootName also stores global text node data rName = RootName; RootName = char(rName{1}); if (length(rName)>1), GlobalProcInst = char(rName{2}); end if (length(rName)>2), GlobalComment = char(rName{3}); end if (length(rName)>3), GlobalDocType = char(rName{4}); end end if(~RootOnly && isstruct(tree)) % if struct than deal with each field separatly fields = fieldnames(tree); for i=1:length(fields) field = fields{i}; x = tree(1).(field); if (strcmp(field, 'COMMENT')) GlobalComment = x; elseif (strcmp(field, 'PROCESSING_INSTRUCTION')) GlobalProcInst = x; elseif (strcmp(field, 'DOCUMENT_TYPE')) GlobalDocType = x; else RootName = field; t = x; end end tree = t; end %% Initialize jave object that will store xml data structure RootName = varName2str(RootName); if (~isempty(GlobalDocType)) % n = strfind(GlobalDocType, ' '); % if (~isempty(n)) % dtype = com.mathworks.xml.XMLUtils.createDocumentType(GlobalDocType); % end % DOMnode = com.mathworks.xml.XMLUtils.createDocument(RootName, dtype); warning('xml_io_tools:write:docType', ... 'DOCUMENT_TYPE node was encountered which is not supported yet. Ignoring.'); end DOMnode = com.mathworks.xml.XMLUtils.createDocument(RootName); %% Use recursive function to convert matlab data structure to XML root = DOMnode.getDocumentElement; struct2DOMnode(DOMnode, root, tree, DPref.ItemName, DPref); %% Remove the only child of the root node root = DOMnode.getDocumentElement; Child = root.getChildNodes; % create array of children nodes nChild = Child.getLength; % number of children if (nChild==1) node = root.removeChild(root.getFirstChild); while(node.hasChildNodes) root.appendChild(node.removeChild(node.getFirstChild)); end while(node.hasAttributes) % copy all attributes root.setAttributeNode(node.removeAttributeNode(node.getAttributes.item(0))); end end %% Save exotic Global nodes if (~isempty(GlobalComment)) DOMnode.insertBefore(DOMnode.createComment(GlobalComment), DOMnode.getFirstChild()); end if (~isempty(GlobalProcInst)) n = strfind(GlobalProcInst, ' '); if (~isempty(n)) proc = DOMnode.createProcessingInstruction(GlobalProcInst(1:(n(1)-1)),... GlobalProcInst((n(1)+1):end)); DOMnode.insertBefore(proc, DOMnode.getFirstChild()); end end % Not supported yet as the code below does not work % if (~isempty(GlobalDocType)) % n = strfind(GlobalDocType, ' '); % if (~isempty(n)) % dtype = DOMnode.createDocumentType(GlobalDocType); % DOMnode.insertBefore(dtype, DOMnode.getFirstChild()); % end % end %% save java DOM tree to XML file if (~isempty(filename)) if (strcmpi(DPref.XmlEngine, 'Xerces')) xmlwrite_xerces(filename, DOMnode); else xmlwrite(filename, DOMnode); end end %% ======================================================================= % === struct2DOMnode Function =========================================== % ======================================================================= function [] = struct2DOMnode(xml, parent, s, TagName, Pref) % struct2DOMnode is a recursive function that converts matlab's structs to % DOM nodes. % INPUTS: % xml - jave object that will store xml data structure % parent - parent DOM Element % s - Matlab data structure to save % TagName - name to be used in xml tags describing 's' % Pref - preferenced % OUTPUT: % parent - modified 'parent' % perform some conversions if (ischar(s) && min(size(s))>1) % if 2D array of characters s=cellstr(s); % than convert to cell array end % if (strcmp(TagName, 'CONTENT')) % while (iscell(s) && length(s)==1), s = s{1}; end % unwrap cell arrays of length 1 % end TagName = varName2str(TagName); %% == node is a 2D cell array == % convert to some other format prior to further processing nDim = nnz(size(s)>1); % is it a scalar, vector, 2D array, 3D cube, etc? if (iscell(s) && nDim==2 && strcmpi(Pref.CellTable, 'Matlab')) s = var2str(s, Pref.PreserveSpace); end if (nDim==2 && (iscell (s) && strcmpi(Pref.CellTable, 'Vector')) || ... (isstruct(s) && strcmpi(Pref.StructTable, 'Vector'))) s = s(:); end if (nDim>2), s = s(:); end % can not handle this case well nItem = numel(s); nDim = nnz(size(s)>1); % is it a scalar, vector, 2D array, 3D cube, etc? %% == node is a cell == if (iscell(s)) % if this is a cell or cell array if ((nDim==2 && strcmpi(Pref.CellTable,'Html')) || (nDim< 2 && Pref.CellItem)) % if 2D array of cells than can use HTML-like notation or if 1D array % than can use item notation if (strcmp(TagName, 'CONTENT')) % CONTENT nodes already have <TagName> ... </TagName> array2DOMnode(xml, parent, s, Pref.ItemName, Pref ); % recursive call else node = xml.createElement(TagName); % <TagName> ... </TagName> array2DOMnode(xml, node, s, Pref.ItemName, Pref ); % recursive call parent.appendChild(node); end else % use <TagName>...<\TagName> <TagName>...<\TagName> notation array2DOMnode(xml, parent, s, TagName, Pref ); % recursive call end %% == node is a struct == elseif (isstruct(s)) % if struct than deal with each field separatly if ((nDim==2 && strcmpi(Pref.StructTable,'Html')) || (nItem>1 && Pref.StructItem)) % if 2D array of structs than can use HTML-like notation or % if 1D array of structs than can use 'items' notation node = xml.createElement(TagName); array2DOMnode(xml, node, s, Pref.ItemName, Pref ); % recursive call parent.appendChild(node); elseif (nItem>1) % use <TagName>...<\TagName> <TagName>...<\TagName> notation array2DOMnode(xml, parent, s, TagName, Pref ); % recursive call else % otherwise save each struct separatelly fields = fieldnames(s); node = xml.createElement(TagName); for i=1:length(fields) % add field by field to the node field = fields{i}; x = s.(field); switch field case {'COMMENT', 'CDATA_SECTION', 'PROCESSING_INSTRUCTION'} if iscellstr(x) % cell array of strings -> add them one by one array2DOMnode(xml, node, x(:), field, Pref ); % recursive call will modify 'node' elseif ischar(x) % single string -> add it struct2DOMnode(xml, node, x, field, Pref ); % recursive call will modify 'node' else % not a string - Ignore warning('xml_io_tools:write:badSpecialNode', ... ['Struct field named ',field,' encountered which was not a string. Ignoring.']); end case 'ATTRIBUTE' % set attributes of the node if (isempty(x)), continue; end if (isstruct(x)) attName = fieldnames(x); % get names of all the attributes for k=1:length(attName) % attach them to the node att = xml.createAttribute(varName2str(attName(k))); att.setValue(var2str(x.(attName{k}),Pref.PreserveSpace)); node.setAttributeNode(att); end else warning('xml_io_tools:write:badAttribute', ... 'Struct field named ATTRIBUTE encountered which was not a struct. Ignoring.'); end otherwise % set children of the node struct2DOMnode(xml, node, x, field, Pref ); % recursive call will modify 'node' end end % end for i=1:nFields parent.appendChild(node); end %% == node is a leaf node == else % if not a struct and not a cell than it is a leaf node switch TagName % different processing depending on desired type of the node case 'COMMENT' % create comment node com = xml.createComment(s); parent.appendChild(com); case 'CDATA_SECTION' % create CDATA Section cdt = xml.createCDATASection(s); parent.appendChild(cdt); case 'PROCESSING_INSTRUCTION' % set attributes of the node OK = false; if (ischar(s)) n = strfind(s, ' '); if (~isempty(n)) proc = xml.createProcessingInstruction(s(1:(n(1)-1)),s((n(1)+1):end)); parent.insertBefore(proc, parent.getFirstChild()); OK = true; end end if (~OK) warning('xml_io_tools:write:badProcInst', ... ['Struct field named PROCESSING_INSTRUCTION need to be',... ' a string, for example: xml-stylesheet type="text/css" ', ... 'href="myStyleSheet.css". Ignoring.']); end case 'CONTENT' % this is text part of already existing node txt = xml.createTextNode(var2str(s, Pref.PreserveSpace)); % convert to text parent.appendChild(txt); otherwise % I guess it is a regular text leaf node txt = xml.createTextNode(var2str(s, Pref.PreserveSpace)); node = xml.createElement(TagName); node.appendChild(txt); parent.appendChild(node); end end % of struct2DOMnode function %% ======================================================================= % === array2DOMnode Function ============================================ % ======================================================================= function [] = array2DOMnode(xml, parent, s, TagName, Pref) % Deal with 1D and 2D arrays of cell or struct. Will modify 'parent'. nDim = nnz(size(s)>1); % is it a scalar, vector, 2D array, 3D cube, etc? switch nDim case 2 % 2D array for r=1:size(s,1) subnode = xml.createElement(Pref.TableName{1}); for c=1:size(s,2) v = s(r,c); if iscell(v), v = v{1}; end struct2DOMnode(xml, subnode, v, Pref.TableName{2}, Pref ); % recursive call end parent.appendChild(subnode); end case 1 %1D array for iItem=1:numel(s) v = s(iItem); if iscell(v), v = v{1}; end struct2DOMnode(xml, parent, v, TagName, Pref ); % recursive call end case 0 % scalar -> this case should never be called if ~isempty(s) if iscell(s), s = s{1}; end struct2DOMnode(xml, parent, s, TagName, Pref ); end end %% ======================================================================= % === var2str Function ================================================== % ======================================================================= function str = var2str(object, PreserveSpace) % convert matlab variables to a string switch (1) case isempty(object) str = ''; case (isnumeric(object) || islogical(object)) if ndims(object)>2, object=object(:); end % can't handle arrays with dimention > 2 str=mat2str(object); % convert matrix to a string % mark logical scalars with [] (logical arrays already have them) so the xml_read % recognizes them as MATLAB objects instead of strings. Same with sparse % matrices if ((islogical(object) && isscalar(object)) || issparse(object)), str = ['[' str ']']; end if (isinteger(object)), str = ['[', class(object), '(', str ')]']; end case iscell(object) if ndims(object)>2, object=object(:); end % can't handle cell arrays with dimention > 2 [nr nc] = size(object); obj2 = object; for i=1:length(object(:)) str = var2str(object{i}, PreserveSpace); if (ischar(object{i})), object{i} = ['''' object{i} '''']; else object{i}=str; end obj2{i} = [object{i} ',']; end for r = 1:nr, obj2{r,nc} = [object{r,nc} ';']; end obj2 = obj2.'; str = ['{' obj2{:} '}']; case isstruct(object) str=''; warning('xml_io_tools:write:var2str', ... 'Struct was encountered where string was expected. Ignoring.'); case isa(object, 'function_handle') str = ['[@' char(object) ']']; case ischar(object) str = object; otherwise str = char(object); end %% string clean-up str=str(:); str=str.'; % make sure this is a row vector of char's if (~isempty(str)) str(str<32|str==127)=' '; % convert no-printable characters to spaces if (~PreserveSpace) str = strtrim(str); % remove spaces from begining and the end str = regexprep(str,'\s+',' '); % remove multiple spaces end end %% ======================================================================= % === var2Namestr Function ============================================== % ======================================================================= function str = varName2str(str) % convert matlab variable names to a sting str = char(str); p = strfind(str,'0x'); if (~isempty(p)) for i=1:length(p) before = str( p(i)+(0:3) ); % string to replace after = char(hex2dec(before(3:4))); % string to replace with str = regexprep(str,before,after, 'once', 'ignorecase'); p=p-3; % since 4 characters were replaced with one - compensate end end str = regexprep(str,'_COLON_',':', 'once', 'ignorecase'); str = regexprep(str,'_DASH_' ,'-', 'once', 'ignorecase');
github
jacksky64/imageProcessing-master
xml_read.m
.m
imageProcessing-master/xmlIO/xml_read.m
24,408
utf_8
4931c3d512db336d744ec43f7fa0b368
function [tree, RootName, DOMnode] = xml_read(xmlfile, Pref) %XML_READ reads xml files and converts them into Matlab's struct tree. % % DESCRIPTION % tree = xml_read(xmlfile) reads 'xmlfile' into data structure 'tree' % % tree = xml_read(xmlfile, Pref) reads 'xmlfile' into data structure 'tree' % according to your preferences % % [tree, RootName, DOMnode] = xml_read(xmlfile) get additional information % about XML file % % INPUT: % xmlfile URL or filename of xml file to read % Pref Preferences: % Pref.ItemName - default 'item' - name of a special tag used to itemize % cell arrays % Pref.ReadAttr - default true - allow reading attributes % Pref.ReadSpec - default true - allow reading special nodes % Pref.Str2Num - default 'smart' - convert strings that look like numbers % to numbers. Options: "always", "never", and "smart" % Pref.KeepNS - default true - keep or strip namespace info % Pref.NoCells - default true - force output to have no cell arrays % Pref.Debug - default false - show mode specific error messages % Pref.NumLevels- default infinity - how many recursive levels are % allowed. Can be used to speed up the function by prunning the tree. % Pref.RootOnly - default true - output variable 'tree' corresponds to % xml file root element, otherwise it correspond to the whole file. % Pref.CellItem - default 'true' - leave 'item' nodes in cell notation. % OUTPUT: % tree tree of structs and/or cell arrays corresponding to xml file % RootName XML tag name used for root (top level) node. % Optionally it can be a string cell array storing: Name of % root node, document "Processing Instructions" data and % document "comment" string % DOMnode output of xmlread % % DETAILS: % Function xml_read first calls MATLAB's xmlread function and than % converts its output ('Document Object Model' tree of Java objects) % to tree of MATLAB struct's. The output is in format of nested structs % and cells. In the output data structure field names are based on % XML tags, except in cases when tags produce illegal variable names. % % Several special xml node types result in special tags for fields of % 'tree' nodes: % - node.CONTENT - stores data section of the node if other fields are % present. Usually data section is stored directly in 'node'. % - node.ATTRIBUTE.name - stores node's attribute called 'name'. % - node.COMMENT - stores node's comment section (string). For global % comments see "RootName" output variable. % - node.CDATA_SECTION - stores node's CDATA section (string). % - node.PROCESSING_INSTRUCTIONS - stores "processing instruction" child % node. For global "processing instructions" see "RootName" output variable. % - other special node types like: document fragment nodes, document type % nodes, entity nodes, notation nodes and processing instruction nodes % will be treated like regular nodes % % EXAMPLES: % MyTree=[]; % MyTree.MyNumber = 13; % MyTree.MyString = 'Hello World'; % xml_write('test.xml', MyTree); % [tree treeName] = xml_read ('test.xml'); % disp(treeName) % gen_object_display() % % See also xml_examples.m % % See also: % xml_write, xmlread, xmlwrite % % Written by Jarek Tuszynski, SAIC, jaroslaw.w.tuszynski_at_saic.com % References: % - Function inspired by Example 3 found in xmlread function. % - Output data structures inspired by xml_toolbox structures. %% default preferences DPref.TableName = {'tr','td'}; % name of a special tags used to itemize 2D cell arrays DPref.ItemName = 'item'; % name of a special tag used to itemize 1D cell arrays DPref.CellItem = false; % leave 'item' nodes in cell notation DPref.ReadAttr = true; % allow reading attributes DPref.ReadSpec = true; % allow reading special nodes: comments, CData, etc. DPref.KeepNS = true; % Keep or strip namespace info DPref.Str2Num = 'smart';% convert strings that look like numbers to numbers DPref.NoCells = true; % force output to have no cell arrays DPref.NumLevels = 1e10; % number of recurence levels DPref.PreserveSpace = false; % Preserve or delete spaces at the beggining and the end of stings? RootOnly = true; % return root node with no top level special nodes Debug = false; % show specific errors (true) or general (false)? tree = []; RootName = []; %% Check Matlab Version v = ver('MATLAB'); version = str2double(regexp(v.Version, '\d.\d','match','once')); if (version<7.1) error('Your MATLAB version is too old. You need version 7.1 or newer.'); end %% read user preferences if (nargin>1) if (isfield(Pref, 'TableName')), DPref.TableName = Pref.TableName; end if (isfield(Pref, 'ItemName' )), DPref.ItemName = Pref.ItemName; end if (isfield(Pref, 'CellItem' )), DPref.CellItem = Pref.CellItem; end if (isfield(Pref, 'Str2Num' )), DPref.Str2Num = Pref.Str2Num ; end if (isfield(Pref, 'NoCells' )), DPref.NoCells = Pref.NoCells ; end if (isfield(Pref, 'NumLevels')), DPref.NumLevels = Pref.NumLevels; end if (isfield(Pref, 'ReadAttr' )), DPref.ReadAttr = Pref.ReadAttr; end if (isfield(Pref, 'ReadSpec' )), DPref.ReadSpec = Pref.ReadSpec; end if (isfield(Pref, 'KeepNS' )), DPref.KeepNS = Pref.KeepNS; end if (isfield(Pref, 'RootOnly' )), RootOnly = Pref.RootOnly; end if (isfield(Pref, 'Debug' )), Debug = Pref.Debug ; end if (isfield(Pref, 'PreserveSpace')), DPref.PreserveSpace = Pref.PreserveSpace; end end if ischar(DPref.Str2Num), % convert from character description to numbers DPref.Str2Num = find(strcmpi(DPref.Str2Num, {'never', 'smart', 'always'}))-1; if isempty(DPref.Str2Num), DPref.Str2Num=1; end % 1-smart by default end %% read xml file using Matlab function if isa(xmlfile, 'org.apache.xerces.dom.DeferredDocumentImpl'); % if xmlfile is a DOMnode than skip the call to xmlread try try DOMnode = xmlfile; catch ME error('Invalid DOM node: \n%s.', getReport(ME)); end catch %#ok<CTCH> catch for mablab versions prior to 7.5 error('Invalid DOM node. \n'); end else % we assume xmlfile is a filename if (Debug) % in debuging mode crashes are allowed DOMnode = xmlread(xmlfile); else % in normal mode crashes are not allowed try try DOMnode = xmlread(xmlfile); catch ME error('Failed to read XML file %s: \n%s',xmlfile, getReport(ME)); end catch %#ok<CTCH> catch for mablab versions prior to 7.5 error('Failed to read XML file %s\n',xmlfile); end end end Node = DOMnode.getFirstChild; %% Find the Root node. Also store data from Global Comment and Processing % Instruction nodes, if any. GlobalTextNodes = cell(1,3); GlobalProcInst = []; GlobalComment = []; GlobalDocType = []; while (~isempty(Node)) if (Node.getNodeType==Node.ELEMENT_NODE) RootNode=Node; elseif (Node.getNodeType==Node.PROCESSING_INSTRUCTION_NODE) data = strtrim(char(Node.getData)); target = strtrim(char(Node.getTarget)); GlobalProcInst = [target, ' ', data]; GlobalTextNodes{2} = GlobalProcInst; elseif (Node.getNodeType==Node.COMMENT_NODE) GlobalComment = strtrim(char(Node.getData)); GlobalTextNodes{3} = GlobalComment; % elseif (Node.getNodeType==Node.DOCUMENT_TYPE_NODE) % GlobalTextNodes{4} = GlobalDocType; end Node = Node.getNextSibling; end %% parse xml file through calls to recursive DOMnode2struct function if (Debug) % in debuging mode crashes are allowed [tree RootName] = DOMnode2struct(RootNode, DPref, 1); else % in normal mode crashes are not allowed try try [tree RootName] = DOMnode2struct(RootNode, DPref, 1); catch ME error('Unable to parse XML file %s: \n %s.',xmlfile, getReport(ME)); end catch %#ok<CTCH> catch for mablab versions prior to 7.5 error('Unable to parse XML file %s.',xmlfile); end end %% If there were any Global Text nodes than return them if (~RootOnly) if (~isempty(GlobalProcInst) && DPref.ReadSpec) t.PROCESSING_INSTRUCTION = GlobalProcInst; end if (~isempty(GlobalComment) && DPref.ReadSpec) t.COMMENT = GlobalComment; end if (~isempty(GlobalDocType) && DPref.ReadSpec) t.DOCUMENT_TYPE = GlobalDocType; end t.(RootName) = tree; tree=t; end if (~isempty(GlobalTextNodes)) GlobalTextNodes{1} = RootName; RootName = GlobalTextNodes; end %% ======================================================================= % === DOMnode2struct Function =========================================== % ======================================================================= function [s TagName LeafNode] = DOMnode2struct(node, Pref, level) %% === Step 1: Get node name and check if it is a leaf node ============== [TagName LeafNode] = NodeName(node, Pref.KeepNS); s = []; % initialize output structure %% === Step 2: Process Leaf Nodes (nodes with no children) =============== if (LeafNode) if (LeafNode>1 && ~Pref.ReadSpec), LeafNode=-1; end % tags only so ignore special nodes if (LeafNode>0) % supported leaf node types try try % use try-catch: errors here are often due to VERY large fields (like images) that overflow java memory s = char(node.getData); if (isempty(s)), s = ' '; end % make it a string % for some reason current xmlread 'creates' a lot of empty text % fields with first chatacter=10 - those will be deleted. if (~Pref.PreserveSpace || s(1)==10) if (isspace(s(1)) || isspace(s(end))), s = strtrim(s); end % trim speces is any end if (LeafNode==1), s=str2var(s, Pref.Str2Num, 0); end % convert to number(s) if needed catch ME % catch for mablab versions 7.5 and higher warning('xml_io_tools:read:LeafRead', ... 'This leaf node could not be read and was ignored. '); getReport(ME) end catch %#ok<CTCH> catch for mablab versions prior to 7.5 warning('xml_io_tools:read:LeafRead', ... 'This leaf node could not be read and was ignored. '); end end if (LeafNode==3) % ProcessingInstructions need special treatment target = strtrim(char(node.getTarget)); s = [target, ' ', s]; end return % We are done the rest of the function deals with nodes with children end if (level>Pref.NumLevels+1), return; end % if Pref.NumLevels is reached than we are done %% === Step 3: Process nodes with children =============================== if (node.hasChildNodes) % children present Child = node.getChildNodes; % create array of children nodes nChild = Child.getLength; % number of children % --- pass 1: how many children with each name ----------------------- f = []; for iChild = 1:nChild % read in each child [cname cLeaf] = NodeName(Child.item(iChild-1), Pref.KeepNS); if (cLeaf<0), continue; end % unsupported leaf node types if (~isfield(f,cname)), f.(cname)=0; % initialize first time I see this name end f.(cname) = f.(cname)+1; % add to the counter end % end for iChild % text_nodes become CONTENT & for some reason current xmlread 'creates' a % lot of empty text fields so f.CONTENT value should not be trusted if (isfield(f,'CONTENT') && f.CONTENT>2), f.CONTENT=2; end % --- pass 2: store all the children as struct of cell arrays ---------- for iChild = 1:nChild % read in each child [c cname cLeaf] = DOMnode2struct(Child.item(iChild-1), Pref, level+1); if (cLeaf && isempty(c)) % if empty leaf node than skip continue; % usually empty text node or one of unhandled node types elseif (nChild==1 && cLeaf==1) s=c; % shortcut for a common case else % if normal node if (level>Pref.NumLevels), continue; end n = f.(cname); % how many of them in the array so far? if (~isfield(s,cname)) % encountered this name for the first time if (n==1) % if there will be only one of them ... s.(cname) = c; % than save it in format it came in else % if there will be many of them ... s.(cname) = cell(1,n); s.(cname){1} = c; % than save as cell array end f.(cname) = 1; % initialize the counter else % already have seen this name s.(cname){n+1} = c; % add to the array f.(cname) = n+1; % add to the array counter end end end % for iChild end % end if (node.hasChildNodes) %% === Step 4: Post-process struct's created for nodes with children ===== if (isstruct(s)) fields = fieldnames(s); nField = length(fields); % Detect structure that looks like Html table and store it in cell Matrix if (nField==1 && strcmpi(fields{1},Pref.TableName{1})) tr = s.(Pref.TableName{1}); fields2 = fieldnames(tr{1}); if (length(fields2)==1 && strcmpi(fields2{1},Pref.TableName{2})) % This seems to be a special structure such that for % Pref.TableName = {'tr','td'} 's' corresponds to % <tr> <td>M11</td> <td>M12</td> </tr> % <tr> <td>M12</td> <td>M22</td> </tr> % Recognize it as encoding for 2D struct nr = length(tr); for r = 1:nr row = tr{r}.(Pref.TableName{2}); Table(r,1:length(row)) = row; %#ok<AGROW> end s = Table; end end % --- Post-processing: convert 'struct of cell-arrays' to 'array of structs' % Example: let say s has 3 fields s.a, s.b & s.c and each field is an % cell-array with more than one cell-element and all 3 have the same length. % Then change it to array of structs, each with single cell. % This way element s.a{1} will be now accessed through s(1).a vec = zeros(size(fields)); for i=1:nField, vec(i) = f.(fields{i}); end if (numel(vec)>1 && vec(1)>1 && var(vec)==0) % convert from struct of s = cell2struct(struct2cell(s), fields, 1); % arrays to array of struct end % if anyone knows better way to do above conversion please let me know. end %% === Step 5: Process nodes with attributes ============================= if (node.hasAttributes && Pref.ReadAttr) if (~isstruct(s)), % make into struct if is not already ss.CONTENT=s; s=ss; end Attr = node.getAttributes; % list of all attributes for iAttr = 1:Attr.getLength % for each attribute name = char(Attr.item(iAttr-1).getName); % attribute name name = str2varName(name, Pref.KeepNS); % fix name if needed value = char(Attr.item(iAttr-1).getValue); % attribute value value = str2var(value, Pref.Str2Num, 1); % convert to number if possible s.ATTRIBUTE.(name) = value; % save again end % end iAttr loop end % done with attributes if (~isstruct(s)), return; end %The rest of the code deals with struct's %% === Post-processing: fields of "s" % convert 'cell-array of structs' to 'arrays of structs' fields = fieldnames(s); % get field names nField = length(fields); for iItem=1:length(s) % for each struct in the array - usually one for iField=1:length(fields) field = fields{iField}; % get field name % if this is an 'item' field and user want to leave those as cells % than skip this one if (strcmpi(field, Pref.ItemName) && Pref.CellItem), continue; end x = s(iItem).(field); if (iscell(x) && all(cellfun(@isstruct,x(:))) && numel(x)>1) % it's cell-array of structs % numel(x)>1 check is to keep 1 cell-arrays created when Pref.CellItem=1 try % this operation fails sometimes % example: change s(1).a{1}.b='jack'; s(1).a{2}.b='john'; to % more convinient s(1).a(1).b='jack'; s(1).a(2).b='john'; s(iItem).(field) = [x{:}]'; %#ok<AGROW> % converted to arrays of structs catch %#ok<CTCH> % above operation will fail if s(1).a{1} and s(1).a{2} have % different fields. If desired, function forceCell2Struct can force % them to the same field structure by adding empty fields. if (Pref.NoCells) s(iItem).(field) = forceCell2Struct(x); %#ok<AGROW> end end % end catch end end end %% === Step 4: Post-process struct's created for nodes with children ===== % --- Post-processing: remove special 'item' tags --------------------- % many xml writes (including xml_write) use a special keyword to mark % arrays of nodes (see xml_write for examples). The code below converts % s.item to s.CONTENT ItemContent = false; if (isfield(s,Pref.ItemName)) s.CONTENT = s.(Pref.ItemName); s = rmfield(s,Pref.ItemName); ItemContent = Pref.CellItem; % if CellItem than keep s.CONTENT as cells end % --- Post-processing: clean up CONTENT tags --------------------- % if s.CONTENT is a cell-array with empty elements at the end than trim % the length of this cell-array. Also if s.CONTENT is the only field than % remove .CONTENT part and store it as s. if (isfield(s,'CONTENT')) if (iscell(s.CONTENT) && isvector(s.CONTENT)) x = s.CONTENT; for i=numel(x):-1:1, if ~isempty(x{i}), break; end; end if (i==1 && ~ItemContent) s.CONTENT = x{1}; % delete cell structure else s.CONTENT = x(1:i); % delete empty cells end end if (nField==1) if (ItemContent) ss = s.CONTENT; % only child: remove a level but ensure output is a cell-array s=[]; s{1}=ss; else s = s.CONTENT; % only child: remove a level end end end %% ======================================================================= % === forceCell2Struct Function ========================================= % ======================================================================= function s = forceCell2Struct(x) % Convert cell-array of structs, where not all of structs have the same % fields, to a single array of structs %% Convert 1D cell array of structs to 2D cell array, where each row % represents item in original array and each column corresponds to a unique % field name. Array "AllFields" store fieldnames for each column AllFields = fieldnames(x{1}); % get field names of the first struct CellMat = cell(length(x), length(AllFields)); for iItem=1:length(x) fields = fieldnames(x{iItem}); % get field names of the next struct for iField=1:length(fields) % inspect all fieldnames and find those field = fields{iField}; % get field name col = find(strcmp(field,AllFields),1); if isempty(col) % no column for such fieldname yet AllFields = [AllFields; field]; %#ok<AGROW> col = length(AllFields); % create a new column for it end CellMat{iItem,col} = x{iItem}.(field); % store rearanged data end end %% Convert 2D cell array to array of structs s = cell2struct(CellMat, AllFields, 2); %% ======================================================================= % === str2var Function ================================================== % ======================================================================= function val=str2var(str, option, attribute) % Can this string 'str' be converted to a number? if so than do it. val = str; len = numel(str); if (len==0 || option==0), return; end % Str2Num="never" of empty string -> do not do enything if (len>10000 && option==1), return; end % Str2Num="smart" and string is very long -> probably base64 encoded binary digits = '(Inf)|(NaN)|(pi)|[\t\n\d\+\-\*\.ei EI\[\]\;\,]'; s = regexprep(str, digits, ''); % remove all the digits and other allowed characters if (~all(~isempty(s))) % if nothing left than this is probably a number if (~isempty(strfind(str, ' '))), option=2; end %if str has white-spaces assume by default that it is not a date string if (~isempty(strfind(str, '['))), option=2; end % same with brackets str(strfind(str, '\n')) = ';';% parse data tables into 2D arrays, if any if (option==1) % the 'smart' option try % try to convert to a date, like 2007-12-05 datenum(str); % if successful than leave it as string catch %#ok<CTCH> % if this is not a date than ... option=2; % ... try converting to a number end end if (option==2) if (attribute) num = str2double(str); % try converting to a single number using sscanf function if isnan(num), return; end % So, it wasn't really a number after all else num = str2num(str); %#ok<ST2NM> % try converting to a single number or array using eval function end if(isnumeric(num) && numel(num)>0), val=num; end % if convertion to a single was succesful than save end elseif ((str(1)=='[' && str(end)==']') || (str(1)=='{' && str(end)=='}')) % this looks like a (cell) array encoded as a string try val = eval(str); catch %#ok<CTCH> val = str; end elseif (~attribute) % see if it is a boolean array with no [] brackets str1 = lower(str); str1 = strrep(str1, 'false', '0'); str1 = strrep(str1, 'true' , '1'); s = regexprep(str1, '[01 \;\,]', ''); % remove all 0/1, spaces, commas and semicolons if (~all(~isempty(s))) % if nothing left than this is probably a boolean array num = str2num(str1); %#ok<ST2NM> if(isnumeric(num) && numel(num)>0), val = (num>0); end % if convertion was succesful than save as logical end end %% ======================================================================= % === str2varName Function ============================================== % ======================================================================= function str = str2varName(str, KeepNS) % convert a sting to a valid matlab variable name if(KeepNS) str = regexprep(str,':','_COLON_', 'once', 'ignorecase'); else k = strfind(str,':'); if (~isempty(k)) str = str(k+1:end); end end str = regexprep(str,'-','_DASH_' ,'once', 'ignorecase'); if (~isvarname(str)) && (~iskeyword(str)) str = genvarname(str); end %% ======================================================================= % === NodeName Function ================================================= % ======================================================================= function [Name LeafNode] = NodeName(node, KeepNS) % get node name and make sure it is a valid variable name in Matlab. % also get node type: % LeafNode=0 - normal element node, % LeafNode=1 - text node % LeafNode=2 - supported non-text leaf node, % LeafNode=3 - supported processing instructions leaf node, % LeafNode=-1 - unsupported non-text leaf node switch (node.getNodeType) case node.ELEMENT_NODE Name = char(node.getNodeName);% capture name of the node Name = str2varName(Name, KeepNS); % if Name is not a good variable name - fix it LeafNode = 0; case node.TEXT_NODE Name = 'CONTENT'; LeafNode = 1; case node.COMMENT_NODE Name = 'COMMENT'; LeafNode = 2; case node.CDATA_SECTION_NODE Name = 'CDATA_SECTION'; LeafNode = 2; case node.DOCUMENT_TYPE_NODE Name = 'DOCUMENT_TYPE'; LeafNode = 2; case node.PROCESSING_INSTRUCTION_NODE Name = 'PROCESSING_INSTRUCTION'; LeafNode = 3; otherwise NodeType = {'ELEMENT','ATTRIBUTE','TEXT','CDATA_SECTION', ... 'ENTITY_REFERENCE', 'ENTITY', 'PROCESSING_INSTRUCTION', 'COMMENT',... 'DOCUMENT', 'DOCUMENT_TYPE', 'DOCUMENT_FRAGMENT', 'NOTATION'}; Name = char(node.getNodeName);% capture name of the node warning('xml_io_tools:read:unkNode', ... 'Unknown node type encountered: %s_NODE (%s)', NodeType{node.getNodeType}, Name); LeafNode = -1; end
github
jacksky64/imageProcessing-master
imwritesc.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/imwritesc.m
1,398
utf_8
68650e74e308c991970251d3bed6b85f
% IMWRITESC - Writes an image to file, rescaling if necessary. % % Usage: imwritesc(im,name) % % Floating point image values are rescaled to the range 0-1 so that no % overflow occurs when writing 8-bit intensity values. The image format to % use is determined by MATLAB from the file ending. % If the image type is of uint8 no rescaling is performed. % Copyright (c) 1999-2005 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % October 1999 - Original version % March 2004 - Modified to allow colour images of class 'double' % August 2005 - Octave compatibility % January 2013 - Separate Octave code path no longer needed function imwritesc(im,name) if strcmp(class(im), 'double') im = im - min(im(:)); % Offset so that min value is 0. im = im./max(im(:)); % Rescale so that max is 1. end imwrite(im,name);
github
jacksky64/imageProcessing-master
circlesineramp.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/circlesineramp.m
5,528
utf_8
07bd0de1d4131398674bfe94cce19c1d
% CIRCLESINERAMP Generates test image for evaluating cyclic colour maps % % Usage: [im, alpha] = circlesineramp(sze, amp, wavelen, p, hole); % [im, alpha] = circlesineramp; % % Arguments: sze - Size of test image. Defaults to 512x512. % amp - Amplitude of sine wave. Defaults to pi/10 % wavelen - Wavelength of sine wave at half radius of the % circular test image. Defaults to 8 pixels. % p - Power to which the linear attenuation of amplitude, % from outside edge to centre, is raised. For no % attenuation use p = 0. For linear attenuation use a % value of 1. The default value is 2, quadratic % attenuation. % hole - Flag 0/1 indicating whether the test image should have % a 'hole' in its centre. The default is 1, to have a % hole, this removes the distraction of the orientation % singularlity at the centre. % Returns: % im - The test image. % alpha - Alpha mask matching the regions outside of of the % circular test image that are set to NaN. Used if you % want to write an image with these regions transparent. % % The test image is a circular pattern consistsing of a sine wave superimposed % on a spiral ramp function. The spiral ramp starts at a value of 0 pointing % right, increasing anti-clockwise to a value of 2*pi as it completes the full % circle. This gives a 2*pi discontinuity on the right side of the image. The % amplitude of the superimposed sine wave is modulated from its full value at % the outside of the circular pattern to 0 at the centre. The default sine wave % amplitude of pi/10 means that the overall size of the sine wave from peak to % trough represents 2*(pi/10)/(2*pi) = 10% of the total spiral ramp of 2*pi. If % you are testing your colour map over a cycle of pi you should use amp = pi/20 % to obtain an equivalent ratio of sine wave to circular ramp. % % The image is designed for evaluating the effectiveness of cyclic colour maps. % It is the cyclic companion to SINERAMP. Ideally the sine wave pattern should % be equally discernible over all angles around the test image. In practice % many colourmaps have uneven perceptual contrast over their range and often % include 'flat spots' of no perceptual contrast that can hide significant % features. Try MATLAB's hsv colour map. % % Ideally the test image should be rendered with a cyclic colour map using % SHOWANGULARIM though, in this case, rendering the image with SHOW or IMAGESC % will also be fine because all image values lie within, and use the full range % of, 0-2*pi. However, in general, default display methods typically do not % respect data values directly and can perform inappropriate offsetting and % normalisation of the angular data before display and rendering with a colour % map. % % For angular data to be rendered correctly it is important that the data values % are respected so that data values are correctly assigned to specific entries % in a cyclic colour map. The assignment of values to colours also depends on % whether the data is cyclic over pi, or 2*pi. SHOWANGULARIM supports this. % % See also: SHOWANGULARIM, SINERAMP, CHIRPLIN, CHIRPEXP, EQUALISECOLOURMAP, CMAP % Copyright (c) 2014 Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % September 2014 Original version. % October 2014 Number of cycles calculated from wave length rather than % being specified directly. function [im, alpha] = circlesineramp(sze, amp, wavelen, p, hole) if ~exist('sze','var'), sze = 512; end if ~exist('amp','var'), amp = pi/10; end if ~exist('wavelen','var'), wavelen = 8; end if ~exist('p','var'), p = 2; end if ~exist('hole','var'), hole = 1; end % Set values for inner and outer radii of test pattern maxr = sze/2 * 0.9; if hole minr = 0.15*sze; else minr = 0; end % Determine number of cycles to achieve desired wavelength at half radius meanr = (maxr + minr)/2; circum = 2*pi*meanr; cycles = round(circum/wavelen); % Angles are +ve anticlockwise and mod 2*pi [x,y] = meshgrid([0:sze-1]-sze/2); theta = mod(atan2(-y,x), 2*pi); rad = sqrt(x.^2 + y.^2); % Normalise radius so that it varies 0-1 over minr to maxr rad = (rad-minr)/(maxr-minr); % Form the image im = amp*rad.^p .* sin(cycles*theta) + theta; % Ensure all values are within 0-2*pi so that a simple default display % with a cyclic colour map will render the image correctly. im = mod(im, 2*pi); % 'Nanify' values outside normalised radius values of 0-1 alpha = ones(size(im)); im(rad > 1) = NaN; alpha(rad > 1) = 0; if hole im(rad < 0) = NaN; alpha(rad < 0 ) = 0; end
github
jacksky64/imageProcessing-master
showsurf.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/showsurf.m
3,887
utf_8
1f50f8abbac642a925b579a58b8e724d
% SHOWSURF - shows parametric surface in a convenient way % % This function wraps up the commands I usually use to display a surface. % % The surface is displayed using SURFL with interpolated shading, in my % favourite colormap of 'copper', with rotate3d on, and axis vis3d set. % % Usage can be any of the following % showsurf(Z) % showsurf(Z, figNo) % showsurf(Z, title) % showsurf(Z, figNo, title) % showsurf(X, Y, Z) % showsurf(X, Y, Z, figNo) % showsurf(X, Y, Z, title) % showsurf(X, Y, Z, figNo, title) % % If no figure number is specified a new figure is created. If you want the % current figure or subplot to be used specify 0 as the figure number. % % See also: SHOW % Copyright (c) 2009 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk at csse uwa edu au % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % PK May 2009 function showsurf(varargin) [X,Y,Z,figNo,titleString] = checkargs(varargin(:)); if figNo == -1 figure elseif figNo > 0 figure(figNo), clf end surfl(X,Y,Z), shading interp, colormap(copper) rotate3d on, axis vis3d, title(titleString); %------------------------------------------------ function [X,Y,Z,figNo,title] = checkargs(args) nArgs = length(args); sze = cell(nArgs,1); for n = 1:nArgs sze{n} = size(args{n}); end % default values figNo = -1; % Value to indicate create new window title = ''; if nArgs == 1 % Assume we user has only supplied Z [X,Y] = meshgrid(1:sze{1}(2),1:sze{1}(1)); Z = args{1}; elseif nArgs == 2 % We have Z,figNo or Z,title if strcmp(class(args{2}),'char') title = args{2}; else figNo = args{2}; end [X,Y] = meshgrid(1:sze{1}(2),1:sze{1}(1)); Z = args{1}; elseif nArgs == 3 % We have Z,figNo,title or X,Y,Z if strcmp(class(args{3}),'char') [X,Y] = meshgrid(1:sze{1}(2),1:sze{1}(1)); Z = args{1}; figNo = args{2}; title = args{3}; else X = args{1}; Y = args{2}; Z = args{3}; end elseif nArgs == 4 % We have X,Y,Z,figNo or X,Y,Z,title if strcmp(class(args{4}),'char') title = args{4}; else figNo = args{4}; end X = args{1}; Y = args{2}; Z = args{3}; elseif nArgs == 5 % We have X,Y,Z,figNo,title X = args{1}; Y = args{2}; Z = args{3}; figNo = args{4}; title = args{5}; else error('Wrong number of arguments'); end % Final sanity check because the code above made quite a few assumptions % about the validity of the supplied arguments if ~all(size(X)==size(Y)) || ~all(size(X)==size(Z)) error('X,Y,Z must have the same dimensions'); end if ~strcmp(class(title),'char') error('Expecting a string for the figure title'); end if length(figNo) ~= 1 || ~isnumeric(figNo) error('Figure number should be a single numeric value'); end
github
jacksky64/imageProcessing-master
randmap.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/randmap.m
731
utf_8
620b6965c1e7db6de65c332753df18f4
% RANDMAP Generates a colourmap of random colours % % Useful for displaying a labeled segmented image % % map = randmap(N) % % Argument: N - Number of elements in the colourmap. Default = 1024. % This ensures images that have been segmented up to 1024 % regions will (well, are more likely to) have a unique % colour for each region. % % See also: HSVMAP, LABMAP, GRAYMAP, BILATERALMAP, HSV, GRAY % Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % February 2013 function map = randmap(N) if ~exist('N', 'var'), N = 1024; end map = rand(N, 3); map(1,:) = [0 0 0]; % Make first entry black
github
jacksky64/imageProcessing-master
viewlabspace2.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/viewlabspace2.m
5,039
utf_8
27e0e43cd469627a1e9eefb0e5ad2119
% VIEWLABSPACE2 Visualisation of L*a*b* space % % Usage: viewlabspace2(dtheta) % % Argument: dtheta - Optional specification of increment in angle of plane % through L*a*b* space. Defaults to pi/30 % % Function allows interactive viewing of a sequence of images corresponding to % different vertical slices in L*a*b* space. % Initially a vertical slice in the a* direction is displayed. % Pressing arrow up/right will rotate the plane +dtheta % Pressing arrow down/left will rotate the plane by -dtheta % Press 'x' to exit. % % See also: VIEWLABSPACE, CMAP % To Do: Should be integrated with VIEWLABSPACE so that we get both views % Copyright (c) 2013 Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % March 2013 function viewlabspace2(dtheta) if ~exist('dtheta', 'var'), dtheta = pi/30; end % Define some reference colours in rgb rgb = [1 0 0 0 1 0 0 0 1 1 1 0 0 1 1 1 0 1]; colours = {'red ' 'green ' 'blue ' 'yellow ' 'cyan ' 'magenta'}; % ... and convert them to lab labv = applycform(rgb, makecform('srgb2lab')); % Obtain cylindrical coordinates in lab space labradius = sqrt(labv(:,2).^2+labv(:,3).^2); labtheta = atan2(labv(:,3), labv(:,2)); % Define lightness - radius grid for image scale = 2; [rad, L] = meshgrid([-140:1/scale:140], [0:1/scale:100]); [rows,cols] = size(rad); % Scale and offset lab coords to fit image coords labc = zeros(size(labv)); labc(:,1) = round(labv(:,1)); labc(:,2) = round(scale*labv(:,2) + cols/2); labc(:,3) = round(scale*labv(:,3) + rows/2); % Print out lab values labv = round(labv); fprintf('\nCoordinates of standard colours in L*a*b* space\n\n'); for n = 1:length(labv) fprintf('%s L%3d a %4d b %4d angle %4.1f radius %4d\n',... colours{n}, ... labv(n,1), labv(n,2), ... labv(n,3), labtheta(n), round(labradius(n))); end fprintf('\n\n') % Generate axis tick values tickval = [-100 -50 0 50 100]; tickcoords = scale*tickval + cols/2; ticklabels = {'-100'; '-50'; '0'; '50'; '100'}; ytickval = [0 20 40 60 80 100]; ytickcoords = scale*ytickval; yticklabels = {'0'; '20'; '40'; '60'; '80'; '100'}; fprintf('Place cursor within figure\n'); fprintf('Use arrow keys to rotate the plane through L*a*b* space\n'); fprintf('''x'' to exit\n'); ch = 'l'; theta = 0; while ch ~= 'x' % Build image in lab space lab = zeros(rows,cols,3); lab(:,:,1) = L; lab(:,:,2) = rad.*cos(theta); lab(:,:,3) = rad.*sin(theta); % Generate rgb values from lab rgb = applycform(lab, makecform('lab2srgb')); % Invert to reconstruct the lab values lab2 = applycform(rgb, makecform('srgb2lab')); % Where the reconstructed lab values differ from the specified values is % an indication that we have gone outside of the rgb gamut. Apply a % mask to the rgb values accordingly mask = max(abs(lab-lab2),[],3); for n = 1:3 rgb(:,:,n) = rgb(:,:,n).*(mask<2); % tolerance of 1 end figure(2), image(rgb), title(sprintf('Angle %d', round(theta/pi*180))); axis square, axis xy set(gca, 'xtick', tickcoords); set(gca, 'ytick', ytickcoords); set(gca, 'xticklabel', ticklabels); set(gca, 'yticklabel', yticklabels); xlabel('a*b* radius'); ylabel('L*'); impixelinfo hold on, plot(cols/2, rows/2, 'r+'); % Centre point for reference %{ % Plot reference colour positions for n = 1:length(labc) plot(labc(n,2), labc(n,3), 'w+') text(labc(n,2), labc(n,3), ... sprintf(' %s\n %d %d %d ',colours{n},... labv(n,1), labv(n,2), labv(n,3)),... 'color', [1 1 1]) end %} hold off % Handle keypresses within the figure pause ch = lower(get(gcf,'CurrentCharacter')); if ch == 29 || ch == 30 theta = mod(theta + dtheta, 2*pi); elseif ch == 28 || ch == 31 theta = mod(theta - dtheta, 2*pi); end end
github
jacksky64/imageProcessing-master
chirplin.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/chirplin.m
2,163
utf_8
c6a50bf097f1b12fc8896b68dc94130b
% CHIRPLIN Generates linear chirp test image % % The test image consists of a linear chirp signal in the horizontal direction % with the amplitude of the chirp being modulated from 1 at the top of the image % to 0 at the bottom. % % Usage: im = chirplin(sze, w0, w1, p) % % Arguments: sze - [rows cols] specifying size of test image. If a % single value is supplied the image is square. % w0, w1 - Initial and final wavelengths of the chirp pattern. % p - Power to which the linear attenuation of amplitude, % from top to bottom, is raised. For no attenuation use % p = 0. For contrast sensitivity experiments use larger % values of p. The default value is 4. % % Example: im = chirplin(500, 40, 2, 4) % % I have used this test image to evaluate the effectiveness of different % colourmaps, and sections of colourmaps, over varying spatial frequencies and % contrast. % % See also: CHIRPEXP, SINERAMP % Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % % March 2012 % February 2015 Changed the arguments so that the chirp is specifeied in % terms of the initial and final wavelengths. function im = chirplin(sze, w0, w1, p) if length(sze) == 1 rows = sze; cols = sze; elseif length(sze) == 2 rows = sze(1); cols = sze(2); else error('size must be a 1 or 2 element vector'); end if ~exist('p', 'var'), p = 4; end if w1 > w0 tmp = w1; w1 = w0; w0 = tmp; flip = 1; else flip = 0; end x = 0:cols-1; % Spatial frequency varies from f0 = 1/w0 to f1 = 1/w1 over the width of the % image following the expression f(x) = f0*(k*x+1) % We need to compute k given w0, w1 and width of the image. f0 = 1/w0; f1 = 1/w1; k = (f1/f0 - 1)/(cols-1); fx = sin(f0*(k.*x+1).*x); A = ([(rows-1):-1:0]/(rows-1)).^p; if flip im = fliplr(A'*fx); else im = A'*fx; end
github
jacksky64/imageProcessing-master
supertorus.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/supertorus.m
2,444
utf_8
91c1e7e27c0219d233582240dcb7c17e
% SUPERTORUS - generates a 'supertorus' surface % % Usage: % [x,y,z] = supertorus(xscale, yscale, zscale, rad, e1, e2, n) % % Arguments: % xscale, yscale, zscale - Scaling in the x, y and z directions. % e1, e2 - Exponents of the x and y coords. % rad - Mean radius of torus. % n - Number of subdivisions of logitude and latitude on % the surface. % % Returns: x,y,z - matrices defining paramteric surface of superquadratic % % If the result is not assigned to any output arguments the function % plots the surface for you, otherwise the x, y and z parametric % coordinates are returned for subsequent display using, say, SURFL. % % If rad is set to 0 the surface becomes a superquadratic % % Examples: % supertorus(1, 1, 1, 2, 1, 1, 100) - classical torus 100 subdivisions % supertorus(1, 1, 1, .8, 1, 1, 100) - an 'orange' % supertorus(1, 1, 1, 2, .1, 1, 100) - a round 'washer' % supertorus(1, 1, 1, 2, .1, 2, 100) - a square 'washer' % % See also: SUPERQUAD % Copyright (c) 2000 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk at csse uwa edu au % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % September 2000 function [x,y,z] = supertorus(xscale,yscale,zscale,rad,e1,e2, n) long = ones(n,1)*[-pi:2*pi/(n-1):pi]; lat = [-pi:2*pi/(n-1): pi]'*ones(1,n); x = xscale * (rad + pow(cos(lat),e1)) .* pow(cos(long),e2); y = yscale * (rad + pow(cos(lat),e1)) .* pow(sin(long),e2); z = zscale * pow(sin(lat),e1); if nargout == 0 surfl(x,y,z), shading interp, colormap(copper), axis equal clear x y z % suppress output end %-------------------------------------------------------------------- % Internal function providing a modified definition of power whereby the % sign of the result always matches the sign of the input value. function r = pow(a,p) r = sign(a).* abs(a.^p);
github
jacksky64/imageProcessing-master
cmyk2rgb.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/cmyk2rgb.m
890
utf_8
6d12e2501c39dec555e670c4190cf6e7
% CMYK2RGB Basic conversion of CMYK colour table to RGB % % Usage: map = cmyk2rgb(cmyk) % % Argument: cmyk - N x 4 table of cmyk values (assumed 0 - Returns) % 1: map - N x 3 table of RGB values % % Note that you can use MATLAB's functions MAKECFORM and APPLYCFORM to % perform the conversion. However I find that either the gamut mapping, or % my incorrect use of these functions does not result in a reversable % CMYK->RGB->CMYK conversion. Hence this simple function and its companion % RGB2CMYK % % See also: RGB2CMYK, MAP2GEOSOFTTBL, GEOSOFTTBL2MAP % Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % PK July 2013 function map = cmyk2rgb(cmyk) c = cmyk(:,1); m = cmyk(:,2); y = cmyk(:,3); k = cmyk(:,4); r = (1-c).*(1-k); g = (1-m).*(1-k); b = (1-y).*(1-k); map = [r g b];
github
jacksky64/imageProcessing-master
graymap.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/graymap.m
865
utf_8
b4f07ef527be1d1937f6ade25c5c67ac
% GRAYMAP Generates a gray colourmap over a specified range % % Usage: map = graymap(gmin, gmax, N) % % Arguments: gmin, gmax - Minimum and maximum gray values desired in % colourmap. Defaults are 0 and 1 % N - Number of elements in the colourmap. Default = 256. % % See also: HSVMAP, LABMAP, RANDMAP, BILATERALMAP, HSV, GRAY % Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % March 2012 function map = graymap(gmin, gmax, N) if ~exist('gmin', 'var'), gmin = 0; end if ~exist('gmax', 'var'), gmax = 1; end if ~exist('N', 'var'), N = 256; end assert(gmin < gmax & gmin >= 0 & gmax <= 1, ... 'gmin and gmax must be between 0 and 1'); g = (0:N-1)'/(N-1) * (gmax-gmin) + gmin; map = [g g g];
github
jacksky64/imageProcessing-master
findimages.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/findimages.m
801
utf_8
20b68f3c818e0bc36b576390784e740c
% FINDIMAGES - invokes image dialog box for multiple image loading % % Usage: [im, filename] = findimages % % Returns: % im - Cell array of images % filename - Cell arrauy of filenames of images % % See Also: FINDIMAGE % Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % % March 2013 function [im, filename] = findimages [filename, pathname] = uigetfile({'*.*'}, ... 'Select images' ,'multiselect','on'); if ~iscell(filename) % Assume canceled im = {}; filename = {}; return; end for n = 1:length(filename) filename{n} = [pathname filename{n}]; im{n} = imread(filename{n}); end
github
jacksky64/imageProcessing-master
showlogfft.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/showlogfft.m
1,718
utf_8
8bf452f34bee6609519ee61053657aa2
% SHOWLOGFFT - Displays log amplitude spectrum of an fft. % % Usage: showlogfft(ft, figNo) % % Arguments: ft - Fourier transform to be displayed % figNo - Optional figure number to display image in. % % The fft is quadrant shifted to place zero frequency at the centre and the % log of the amplitude displayed (to compress grey values). An offset of 1 % is added to avoid log(0) % % If figNo is omitted a new figure window is created. If figNo is supplied, % and the figure exists, the existing window is reused to display the image, % otherwise a new window is created. % Copyright (c) 1999 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % October 1999 % September 2008 Octave compatible function showlogfft(im, figNo) Octave = exist('OCTAVE_VERSION', 'builtin') == 5; % Are we running under Octave Title = inputname(1); % Get variable name of image data if nargin == 2 figure(figNo); % Reuse or create a figure window with this number else figNo = figure; % Create new figure window end imagesc(log(fftshift(abs(im))+1)); colormap(gray); title(Title), axis('image') if ~Octave; truesize(figNo), end
github
jacksky64/imageProcessing-master
polyfit2d.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/polyfit2d.m
2,438
utf_8
a05847f0b684d1549e8bf19c81e011eb
% POLYFIT2D Fits 2D polynomial surface to data % % Usage: c = polyfit2d(x, y, z, degree) % % Arguments: x, y, z - coordinates of data points % degree - degree of polynomial surface % % Returns: c - The coefficients of polynomial surface. % There will be (degree+1)*(degree+2)/2 % coefficients. % % For a degree 3 surface the coefficients progress in the form % 00 01 02 03 10 11 12 20 21 30 % where the first digit is the y exponent and the 2nd the x exponent % % 0 0 0 1 0 2 0 3 1 0 1 1 1 2 % c1 x y + c2 x y + c3 x y + c4 x y + c5 x y + c6 x y + c7 x y + ... % % To reduce numerical problems this function rescales the values of x and y to a % maximum magnitude of 1. The calculated coefficients are then rescaled to % account for this. Ideally the values of x and y would also be centred to have % zero mean. However, the correction that would then have to be applied to the % coefficients is not so simply done. If you do find that you have numerical % problems you could try centering x and y prior to calling this function. % % See also: POLYVAL2D % Peter Kovesi 2014 % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % PK July 2014 function c = polyfit2d(x, y, z, degree) % Ensure input are column vectors x = x(:); y = y(:); z = z(:); % To reduce numerical problems we perform normalisation of the data to keep % the maximum magnitude of x and y to 1. scale = max(abs([x; y])); x = x/scale; y = y/scale; nData = length(x); ncoeff = (degree+1)*(degree+2)/2; % Build Vandermonde matrix. p1 is the x exponent and p2 is the y exponent V = zeros(nData, ncoeff); col = 1; for p2 = 0:degree for p1 = 0:(degree-p2) V(:,col) = x.^p1 .* y.^p2; col = col+1; end end [Q,R] = qr(V,0); % Solution via QR decomposition c = R\(Q'*z); if condest(R) > 1e10 warning('Solution is ill conditioned. Coefficient values will be suspect') end % Scale coefficients to account for the earlier normalisation of x and y. col = 1; for p2 = 0:degree for p1 = 0:(degree-p2) c(col) = c(col)/scale^(p1+p2); col = col+1; end end
github
jacksky64/imageProcessing-master
rgb2lab.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/rgb2lab.m
1,063
utf_8
29f5354eef11a490d28c05d752252407
% RGB2LAB - RGB to L*a*b* colour space % % Usage: Lab = rgb2lab(im, wp) % % Arguments: im - RGB image or Nx3 colourmap for conversion % wp - Optional string specifying the adapted white point. % This defaults to 'D65'. % % Returns: Lab - The converted image or colourmap. % % This function wraps up calls to MAKECFORM and APPLYCFORM in a convenient % form. Note that if the image is of type uint8 this function casts it to % double and divides by 255 so that RGB values are in the range 0-1 and the % transformed image can have the proper negative values for a and b. % % See also: LAB2RGB, RGB2NRGB, RGB2CMYK % Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % PK May 2009 function Lab = rgb2lab(im, wp) if ~exist('wp', 'var'), wp = 'D65'; end cform = makecform('srgb2lab',... 'adaptedwhitepoint', whitepoint(wp)); if strcmp(class(im),'uint8') im = double(im)/255; end Lab = applycform(im, cform);
github
jacksky64/imageProcessing-master
pathlist.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/pathlist.m
1,202
utf_8
2551671f5f3c9a17293d82ed6aee8167
% PATHLIST Produces a cell array of directories along a directory path % % Usage: plist = pathlist(fullpath) % % Example: If fullpath = '/Users/pk/Matlab/Spatial' % plist = % '/' '/Users/' '/Users/pk/' '/Users/pk/Matlab/' '/Users/pk/Matlab/Spatial' % % plist{end} is always fullpath % plist{end-1} is the parent directory % etc % % Not sure if this works appropriately under Windows % Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % % September 2010 function plist = pathlist(fullpath) % Find locations of a forward or back slash in the full file name ind = find(fullpath == '/' | fullpath =='\'); % If there were no / or \ in the full path just return fullpath if isempty(ind) plist{1} = fullpath; else % Step along the path and extract each incremental part for n = 1:length(ind) plist{n} = fullpath(1:ind(n)); end % If there is no / or \ at the end of the full path make fullpath the % final entry in the list if ind(end) ~= length(fullpath) plist{n+1} = fullpath; end end
github
jacksky64/imageProcessing-master
superquad.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/superquad.m
2,798
utf_8
2dfc95eb41c2bf03bb78f5f0bb8b7c07
% SUPERQUAD - generates a superquadratic surface % % Usage: [x,y,z] = superquad(xscale, yscale, zscale, e1, e2, n) % % Arguments: % xscale, yscale, zscale - Scaling in the x, y and z directions. % e1, e2 - Exponents of the x and y coords. % n - Number of subdivisions of logitude and latitude on % the surface. % % Returns: x,y,z - matrices defining paramteric surface of superquadratic % % If the result is not assigned to any output arguments the function % plots the surface for you, otherwise the x, y and z parametric % coordinates are returned for subsequent display using, say, SURFL. % % Examples: % superquad(1, 1, 1, 1, 1, 100) - sphere of radius 1 with 100 subdivisions % superquad(1, 1, 1, 2, 2, 100) - octahedron of radius 1 % superquad(1, 1, 1, 3, 3, 100) - 'pointy' octahedron % superquad(1, 1, 1, .1, .1, 100) - cube (with rounded edges) % superquad(1, 1, .2, 1, .1, 100) - 'square cushion' % superquad(1, 1, .2, .1, 1, 100) - cylinder % % See also: SUPERTORUS % Copyright (c) 2000 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk at csse uwa edu au % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % September 2000 function [x,y,z] = superquad(xscale, yscale, zscale, e1, e2, n) % Set up parameters of the parametric surface, in this case matrices % corresponding to longitude and latitude on our superquadratic sphere. long = ones(n,1)*[-pi:2*pi/(n-1):pi]; lat = [-pi/2:pi/(n-1): pi/2]'*ones(1,n); x = xscale * pow(cos(lat),e1) .* pow(cos(long),e2); y = yscale * pow(cos(lat),e1) .* pow(sin(long),e2); z = zscale * pow(sin(lat),e1); % Ensure top and bottom ends are closed. If we do not do this you find % that due to numerical errors the ends may not be perfectly closed. x(1,:) = 0; y(1,:) = 0; x(end,:) = 0; y(end,:) = 0; if nargout == 0 surfl(x,y,z), shading interp, colormap(copper), axis equal clear x y z % suppress output end %-------------------------------------------------------------------- % Internal function providing a modified definition of power whereby the % sign of the result always matches the sign of the input value. function r = pow(a, p) r = sign(a).* abs(a).^p;
github
jacksky64/imageProcessing-master
hsvmap.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/hsvmap.m
1,842
utf_8
ec6d79772fe1bba81deabf0312847a24
% HSVMAP Generates an HSV colourmap over a specified range of hues % % The function generates colours over a specified range of hues from the HSV % colourtmap % % map = hsvmap(hmin, hmax, N) % % Arguments: hmin - Minimum hue value 0 - 1. Default = 0 % hmax - Maximum hue value 0 - 2. Default = 1 % N - Number of elements in the colourmap. Default = 256 % % Note that hue values range from 0 to 1 in a cyclic manner. hmax can be set to % a value greater than one to allow one to specify a hue range that straddles % the 0 point. The resulting map is modulus 1. For example using % hmin = 0.9; % hmax = 1.1; % Will generate hues ranging from 0.9 up to 1.0, followed by hues 0.0 to 0.1 % % hsvmap(0, 1, 256) will generate a colourmap that is identical to MATLAB's hsv % colourmap. % % See also: LABMAP, GRAYMAP, RANDMAP, BILATERALMAP, HSV, GRAY % Copyright (c) 2012 Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % March 2012 function map = hsvmap(hmin, hmax, N) if ~exist('N', 'var'), N = 256; end if ~exist('hmin', 'var'), hmin = 0; end if ~exist('hmax', 'var'), hmax = 1; end assert(hmax<2, 'hmax must be less than 2'); h = [0:(N-1)]'/(N-0)*(hmax-hmin)+hmin; h(h>1) = h(h>1)-1; % Enforce hue wraparound 0-1 map = hsv2rgb([h ones(N,2)]);
github
jacksky64/imageProcessing-master
rgb2nrgb.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/rgb2nrgb.m
1,125
utf_8
743c25dcc6996a893f06243bfc96fa8e
% RGB2NRGB - RGB to normalised RGB % % Usage: nrgb = rgb2nrgb(im, offset) % % Arguments: im - Colour image to be normalised % offset - Optional value added to (R+G+B) to discount low % intensity colour values. Defaults to 1 % % r = R / (R + G + B) etc % Copyright (c) 2009 Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % http://www.csse.uwa.edu.au/~pk/research/matlabfns/ % May 2009 function nrgb = rgb2nrgb(im, offset) if ndims(im) ~= 3; error('Image must be a colour image'); end % Convert to double if needed and define an offset = 1/255 max value to % be used in the normalization to avoid division by zero if ~strcmp(class(im), 'double') im = double(im); if ~exist('offset', 'var'), offset = 1; end else % Assume we have doubles in range 0..1 if ~exist('offset', 'var'), offset = 1/255; end end nrgb = zeros(size(im)); gim = sum(im,3) + offset; nrgb(:,:,1) = im(:,:,1)./gim; nrgb(:,:,2) = im(:,:,2)./gim; nrgb(:,:,3) = im(:,:,3)./gim;
github
jacksky64/imageProcessing-master
bbspline.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/bbspline.m
2,976
utf_8
104e9e1224ddb3f6d34b0cca8a1f5bfa
% BBSPLINE - Basic B-spline % % Usage: S = bbspline(P, k, N) % % Arguments: P - [dim x Npts] array of control points % k - order of spline (>= 2). % k = 2: Linear % k = 3: Quadratic, etc % N - Optional number of points to evaluate along % spline. Defaults to 100. % % Returns: S - spline curve [dim x N] spline points % % See also: PBSPLINE % PK Jan 2014 % Nov 2015 Made basis calculation slightly less wasteful function S = bbspline(P, k, N) if ~exist('N', 'var'), N = 100; end [dim, np1] = size(P); n = np1-1; assert(k >= 2, 'Spline order must be 2 or greater'); assert(np1 >= k, 'No of control points must be >= k'); assert(N >= 2, 'Spline must be evaluated at 2 or more points'); % Set up open uniform knot vector from 0 - 1. % There are k repeated knots at each end. ti = 0:(k+n - 2*(k-1)); ti = ti/ti(end); ti = [repmat(ti(1), 1, k-1), ti, repmat(ti(end), 1, k-1)]; nK = length(ti); % Generate values of t that the spline will be evaluated at dt = (ti(end)-ti(1))/(N-1); t = ti(1):dt:ti(end); % Build complete array of basis functions. We maintain two % arrays, one storing the basis functions at the current level of % recursion, and one storing the basis functions from the previous % level of recursion B = cell(1,nK-1); Blast = cell(1,nK-1); % 1st level of recursive construction for i = 1:nK-1 Blast{i} = t >= ti(i) & t < ti(i+1) & ti(i) < ti(i+1); end % Subsequent levels of recursive basis construction. Note the logic to % handle repeated knot values where ti(i) == ti(i+1) for ki = 2:k for i = 1:nK-ki if (ti(i+ki-1) - ti(i)) < eps V1 = 0; else V1 = (t - ti(i))/(ti(i+ki-1) - ti(i)) .* Blast{i}; end if (ti(i+ki) - ti(i+1)) < eps V2 = 0; else V2 = (ti(i+ki) - t)/(ti(i+ki) - ti(i+1)) .* Blast{i+1}; end B{i} = V1 + V2; % This is the ideal equation that the code above implements % B{i,ki} = (t - ti(i))/(ti(i+ki-1) - ti(i)) .* B{i,ki-1} + ... % (ti(i+ki) - t)/(ti(i+ki) - ti(i+1)) .* B{i+1,ki-1}; end % Swap B and Blast, but only if this is not the last iteration if ki < k tmp = Blast; Blast = B; B = tmp; end end % Apply basis functions to the control points S = zeros(dim, length(t)); for d = 1:dim for i = 1:np1 S(d,:) = S(d,:) + P(d,i)*B{i}; end end % Set the last point of the spline. This is not evaluated by the code above % because the basis functions are defined from ti(i) <= t < ti(i+1) S(:,end) = P(:,end);
github
jacksky64/imageProcessing-master
weightedhistc.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/weightedhistc.m
1,498
utf_8
b474157c0a9fa58fc7eb358c7c7ccc37
% WEIGHTEDHISTC Weighted histogram count % % This function provides a basic equivalent to MATLAB's HISTC function for % weighted data. % % Usage: h = weightedhistc(vals, weights, edges) % % Arguments: % vals - vector of values. % weights - vector of weights associated with each element in vals. vals % and weights must be vectors of the same length. % edges - vector of bin boundaries to be used in the weighted histogram. % % Returns: % h - The weighted histogram % h(k) will count the weighted value vals(i) % if edges(k) <= vals(i) < edges(k+1). % The last bin will count any values of vals that match % edges(end). Values outside the values in edges are not counted. % % Use bar(edges,h) to display histogram % % See also: HISTC % Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % % November 2010 function h = weightedhistc(vals, weights, edges) if ~isvector(vals) || ~isvector(weights) || length(vals)~=length(weights) error('vals and weights must be vectors of the same size'); end Nedge = length(edges); h = zeros(size(edges)); for n = 1:Nedge-1 ind = find(vals >= edges(n) & vals < edges(n+1)); if ~isempty(ind) h(n) = sum(weights(ind)); end end ind = find(vals == edges(end)); if ~isempty(ind) h(Nedge) = sum(weights(ind)); end
github
jacksky64/imageProcessing-master
bilateralmap.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/bilateralmap.m
2,549
utf_8
c9a16e3cdc46d415b9bb829195bb212e
% BILATERALMAP Generates a bilateral colourmap % % This function generate a colourmap where the first half has one hue and the % second half has another hue. Saturation varies linearly from 0 in the middle % to 1 at ech end. This gives a colourmap which varies from white at the middle % to an increasing saturation of the different hues as one moves to the ends. % This colourmap is useful where your data has a clear origin. The hue % indicates the polarity of your data, and saturation indicate amplitude. % % Usage: map = bilateralmap(H1, H2, V, N) % % Arguments: % H1 - Hue value for 1st half of map. This must be a value between % 0 and 1, defaults to 0.65 (blue). % H2 - Hue value for 2nd half of map, defaults to 1.0 (red). % V - Value as in 'V' in 'HSV', defaults to 1. Reduce this if you % want a darker map. % N - Number of elements in colourmap, defaults to 256. % % Returns: % map - N x 3 colourmap of RGB values. % % Some nominal hue values: % 0 - red % 0.07 - orange % 0.17 - yellow % 0.3 - green % 0.5 - cyan % 0.65 - blue % 0.85 - magenta % 1.0 - red % % See also: LABMAP, HSVMAP, GRAYMAP, RANDMAP % Copyright (c) 2012 Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % October 2012 function map = bilateralmap(H1, H2, V, N) % Default colourmap values if ~exist('H1','var'), H1 = 0.65; end % blue if ~exist('H2','var'), H2 = 1.00; end % red if ~exist('V' ,'var'), V = 1; end % 'value' of 1 if ~exist('N', 'var'), N = 256; end % Construct map in HSV then convert to RGB at end Non2 = round(N/2); map = zeros(N,3); % First half of map has hue H1 and 2nd half H2 map(1:Non2, 1) = H1; map(1+Non2 : end, 1) = H2; % Saturation varies linearly from 0 in the middle to 1 at each end map(1:Non2, 2) = (Non2-1:-1:0)'/Non2; map(1+Non2 : end, 2) = (1:N-Non2)'/(N-Non2); % Value is constant throughout map(:,3) = V; map = hsv2rgb(map);
github
jacksky64/imageProcessing-master
clouds.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/clouds.m
2,219
utf_8
55889e6ed17ca0979b08f7fb102f76e6
% CLOUDS % % Function to create a movie of noise images having 1/f amplitude spectum properties % % Usage: clouds(size, factor, meandev, stddev, lowvel, velfactor, nframes) % % size - size of image to produce % factor - controls spectrum = 1/(f^factor) % meandev - mean change in phaseangle per frame % stddev - stddev of change in phaseangle per frame % lowvel - phase velocity at 0 frequency % velfactor - phase velocity = freq^velfactor % nframes - no of frames in movie % % factor = 0 - raw Gaussian noise image % = 1 - gives the 1/f `standard' drop-off for `natural' images % = 1.5 - seems to give the most intersting `cloud patterns' % = 2 or greater - produces `blobby' images % PK 18-4-00 % function clouds(size, factor, meandev, stddev, lowvel, velfactor, nframes) rows = size; cols = size; phase = 2*pi*rand(size,size); % Random uniform distribution 0 - 2pi % Create two matrices, x and y. All elements of x have a value equal to its % x coordinate relative to the centre, elements of y have values equal to % their y coordinate relative to the centre. From these two matrices produce % a radius matrix that gives distances from the middle x = ones(rows,1) * (-cols/2 : (cols/2 - 1)); y = (-rows/2 : (rows/2 - 1))' * ones(1,cols); x = x/(cols/2); y = y/(rows/2); radius = sqrt(x.^2 + y.^2); % Matrix values contain radius from centre. radius(rows/2+1,cols/2+1) = 1; % .. avoid division by zero. filter = 1./(radius.^factor); % Construct the filter. filter = fftshift(filter); phasemod = fftshift(radius.^velfactor + lowvel); % Construct fft of noise image with the specified amplitude spectrum for n = 1:nframes if ~mod(n,10), fprintf('\r %d', n); end dphase = meandev + stddev*randn(size,size); dphase = dphase.*phasemod; phase = phase + dphase; newfft = filter .* exp(i*phase); im = real(ifft2(newfft)); % Invert to obtain final noise image show(im,1), colormap(gray); axis('equal'), axis('off'); if n==1 CloudMovie = moviein(nframes); end CloudMovie(:,n) = getframe; end movie(CloudMovie,-4,12); save('CloudMovie','CloudMovie');
github
jacksky64/imageProcessing-master
matprint.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/matprint.m
1,453
utf_8
bb847e0506584e9e043482b7a69bcbb4
% MATPRINT - prints a matrix with specified format string % % Usage: matprint(a, fmt, fid) % % a - Matrix to be printed. % fmt - C style format string to use for each value. % fid - Optional file id. % % Eg. matprint(a,'%3.1f') will print each entry to 1 decimal place % Copyright (c) 2002 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % March 2002 function matprint(a, fmt, fid) if nargin < 3 fid = 1; end [rows,cols] = size(a); % Construct a format string for each row of the matrix consisting of % 'cols' copies of the number formating specification fmtstr = []; for c = 1:cols fmtstr = [fmtstr, ' ', fmt]; end fmtstr = [fmtstr '\n']; % Add a line feed fprintf(fid, fmtstr, a'); % Print the transpose of the matrix because % fprintf runs down the columns of a matrix.
github
jacksky64/imageProcessing-master
noiseonf.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/noiseonf.m
2,320
utf_8
fad84fc70d1aff602b459ef9097309a4
% NOISEONF - Creates 1/f spectrum noise images. % % Function to create noise images having 1/f amplitude spectum properties. % When displayed as a surface these images also generate great landscape % terrain. % % Usage: im = noiseonf(size, factor) % % size - A 1 or 2-vector specifying size of image to produce [rows cols] % factor - controls spectrum = 1/(f^factor) % % factor = 0 - raw Gaussian noise image % = 1 - gives the 1/f 'standard' drop-off for 'natural' images % = 1.5 - seems to give the most interesting 'cloud patterns' % = 2 or greater - produces 'blobby' images % Copyright (c) 1996-2014 Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % The Software is provided "as is", without warranty of any kind. % December 1996 % March 2009 Arbitrary image size % September 2011 Code tidy up % April 2014 Fixed to work with odd dimensioned images function im = noiseonf(sze, factor) if length(sze) == 2 rows = sze(1); cols = sze(2); elseif length(sze) == 1 rows = sze; cols = sze; else error('size must be a 1 or 2-vector'); end % Generate an image of random Gaussian noise, mean 0, std dev 1. im = randn(rows,cols); imfft = fft2(im); mag = abs(imfft); % Get magnitude phase = imfft./mag; % and phase % Construct the amplitude spectrum filter % Add 1 to avoid divide by 0 problems later radius = filtergrid(rows,cols)*max(rows,cols) + 1; filter = 1./(radius.^factor); % Reconstruct fft of noise image, but now with the specified amplitude % spectrum newfft = filter .* phase; im = real(ifft2(newfft)); %caption = sprintf('noise with 1/(f^%2.1f) amplitude spectrum',factor); %imagesc(im), axis('equal'), axis('off'), title(caption);
github
jacksky64/imageProcessing-master
fillnan.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/fillnan.m
1,968
utf_8
d3651b29d884e867d1804ea9c4dc1fd7
% FILLNAN - fills NaN values in an image with closest non Nan value % % NaN values in an image are replaced with the value in the closest pixel that % is not a NaN. This can be used as a crude (but quick) 'inpainting' function % to allow a FFT to be computed on an image containing NaN values. While the % 'inpainting' is very crude it is typically good enough to remove most of the % edge effects one might get at the boundaries of the NaN regions. The NaN % regions should then be remasked out of the final processed image. % % Usage: [newim, mask] = fillnan(im); % % Argument: im - Image to be 'filled' % Returns: newim - Filled image % mask - Binary image indicating NaN regions in the original % image. % % See Also: REMOVENAN % Copyright (c) 2007 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk at csse uwa edu au % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. function [newim, mask] = fillnan(im); % Generate distance transform from non NaN regions of the image. % L will contain indices of closest non NaN points in the image mask = ~isnan(im); if all(isnan(im(:))) newim = im; warning('All elements are NaN, no filling possible\n'); return end [~,L] = bwdist(mask); ind = find(isnan(im)); % Indices of points that are NaN % Fill NaN locations with value of closest non NaN pixel newim = im; newim(ind) = im(L(ind));
github
jacksky64/imageProcessing-master
testdbscan.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/testdbscan.m
2,247
utf_8
aa690910417795cfda803d2e25a271c2
% TESTDBSCAN Program to test/demonstrate the DBSCAN clustering algorithm % % Simple usage: testdbscan; % % Full usage: [C, ptsC] = testdbscan(E, minPts) % % % Arguments: % E - Distance threshold for clustering. Defaults to 0.3 % minPts - Minimum number of points required to form a cluster. % Defaults to 3 % % Returns: % C - Cell array of length Nc listing indices of points associated with % each cluster. % ptsC - Array of length Npts listing the cluster number associated with % each point. If a point is denoted as noise (not enough nearby % elements to form a cluster) its cluster number is 0. % % See also: DBSCAN % Copyright (c) 2013 Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % % Jan 2013 function [C, ptsC, centres] = testdbscan(E, minPts) if ~exist('E', 'var'), E = 0.3; end; if ~exist('minPts', 'var'), minPts = 3; end; figure(1), clf, axis([-1 1 -1 1]); fprintf('Digitise a series of points that form some clusters. Right-click to finish\n'); [x,y] = digipts; hold on % Perform clustering P = [x'; y']; [C, ptsC, centres] = dbscan(P, E, minPts); for n = 1:length(x) text(x(n),y(n)+.04, sprintf('%d',ptsC(n)), 'color', [0 0 1]); end title('Points annotated by cluster number') hold off %-------------------------------------------------------------------------- % DIGIPTS - digitise points in an image % % Function to digitise points in an image. Points are digitised by clicking % with the left mouse button. Clicking any other button terminates the % function. Each location digitised is marked with a red '+'. % % Usage: [u,v] = digipts % % where u and v are nx1 arrays of x and y coordinate values digitised in % the image. % % This function uses the cross-hair cursor provided by GINPUT. This is % much more useable than IMPIXEL function [u,v] = digipts hold on u = []; v = []; but = 1; while but == 1 [x y but] = ginput(1); if but == 1 u = [u;x]; v = [v;y]; plot(u,v,'r+'); end end hold off
github
jacksky64/imageProcessing-master
polartrans.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/polartrans.m
3,367
utf_8
9aed63869d7ac444d0e2198fcd91e306
% POLARTRANS - Transforms image to polar coordinates % % Usage: pim = polartrans(im, nrad, ntheta, cx, cy, linlog, shape) % % Arguments: % im - image to be transformed. % nrad - number of radius values. % ntheta - number of theta values. % cx, cy - optional specification of origin. If this is not % specified it defaults to the centre of the image. % linlog - optional string 'linear' or 'log' to obtain a % transformation with linear or logarithmic radius % values. linear is the default. % shape - optional string 'full' or 'valid' % 'full' results in the full polar transform being % returned (the circle that fully encloses the original % image). This is the default. % 'valid' returns the polar transform of the largest % circle that can fit within the image. % % Returns pim - image in polar coordinates with radius increasing % down the rows and theta along the columns. The size % of the image is nrad x ntheta. Note that theta is % +ve clockwise as x is considered +ve along the % columns and y +ve down the rows. % % When specifying the origin it is assumed that the top left pixel has % coordinates (1,1). % Copyright (c) 2002 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % December 2002 % November 2006 Correction to calculation of maxlogr (thanks to Chang Lei) function pim = polartrans(im, nrad, ntheta, cx, cy, linlog, shape) [rows, cols] = size(im); if nargin==3 % Set origin to centre. cx = cols/2+.5; % Add 0.5 because indexing starts at 1 cy = rows/2+.5; end if nargin < 7, shape = 'full'; end if nargin < 6, linlog = 'linear'; end if strcmp(shape,'full') % Find maximum radius value dx = max([cx-1, cols-cx]); dy = max([cy-1, rows-cy]); rmax = sqrt(dx^2+dy^2); elseif strcmp(shape,'valid') % Find minimum radius value rmax = min([cx-1, cols-cx, cy-1, rows-cy]); else error('Invalid shape specification'); end % Increments in radius and theta deltatheta = 2*pi/ntheta; if strcmp(linlog,'linear') deltarad = rmax/(nrad-1); [theta, radius] = meshgrid([0:ntheta-1]*deltatheta, [0:nrad-1]*deltarad); elseif strcmp(linlog,'log') maxlogr = log(rmax); deltalogr = maxlogr/(nrad-1); [theta, radius] = meshgrid([0:ntheta-1]*deltatheta, exp([0:nrad-1]*deltalogr)); else error('Invalid radial transformtion (must be linear or log)'); end xi = radius.*cos(theta) + cx; % Locations in image to interpolate data yi = radius.*sin(theta) + cy; % from. [x,y] = meshgrid([1:cols],[1:rows]); pim = interp2(x, y, double(im), xi, yi);
github
jacksky64/imageProcessing-master
labmap.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/labmap.m
8,483
utf_8
e7cda593bf59d9e52b88e7ef4e13bb57
% LABMAP - Generates a colourmap based on L*a*b* space % % This function can generate a wide range of colourmaps but it can be a bit % difficult to drive... % % The idea: Create a spiral path within in L*a*b* space to use as a % colourmap. L*a*b* space is designed to be perceptually uniform so, in % principle, it should be a good space in which to design colourmaps. % % L*a*b* space is treated (a bit inappropriately) as a cylindrical colourspace. % The spiral path is created by specifying linear ramps in: the angular value % around the origin of the a*b* plane; the Lightness variation; and the % saturation (the radius out from the centre of the a*b* plane). % % As an alternative an option is available to use a simple straight line % interpolation from the first colour, through the colourspace, to the final % colour. One is much less likely to go outside of the rgb gamut but the % variety of colourmaps will be limited % % Usage: map = labmap(theta, L, saturation, N, linear, debug) % % Arguments: % theta - 2-vector specifyinhg start and end angles in the a*b* % plane over which to define the colourmap (radians). % These angles specify a +ve or -ve ramp of values over % which opponent colour values vary. If you want % values to straddle the origin use theta values > 2pi % or < 0 as needed. % L - 2-vector specifying the lightness variation from % start to end over the colourmap. Values are in the % range 0-100. (You normally want a lightness % variation over the colourmap) % saturation - 2-vector specifying the saturation variation from % start to end over the colourmap. This specifies the % radius out from the centre of the a*b* plane where % the colours are defined. Values are in the range 0-127. % N - Number of elements in the colourmap. Default = 256. % linear - Flag 0/1. If this flag is set a simple straight line % interpolation, from the first to last colour, through % the colourspace is used. Default value is 0. % debug - Optional flag 0/1. If debug is set a plot of the % colourmap is displayed along with a diagnostic plot % of the specified L*a*b* values is generated along % with the values actually achieved. These are usually % quite different due to gamut limitations. However, % as long as the lightness varies in a near linear % fashion the colourmap is probably ok. % % theta, L and saturation can be specified as single values in which case % they are assumed to be specifying a 'ramp' of constant value. % % The colourmap is generated from a* and b* values that form a spiral about % the point (0, 0). a* = saturation*cos(theta) and b* = saturation*sin(theta) % while Lightness varies along the specified ramp. % a* +ve indicates magenta, a* -ve indicates cyan % b* +ve indicates yellow, b* -ve indicates blue % % Changing lightness values can change things considerably and you will need % some experimentation to get the colours you want. It is often useful to try % reversing the lightness ramp on your coloumap to see what it does. Note also % it is quite possible (quite common) to end up specifying L*a*b* values that % are outside the gamut of RGB space. Run the function with the debug flag % set to monitor this. % % A weakness of this simple cylindrical coordinate approach used here is that it % generates colours that are out of gamut far too readily. To do: A better approach % might be to show the allowable colours for a set of lightness values, allow % the user to specify 3 colours, and then fit some kind of spline through these % colours in lab space. % % L*a*b* space is more perceptually uniform than, say, HSV space. HSV and other % rainbow-like colourmaps can be quite problematic, especially around yellow % because lightness varies in a non-linear way along the colourmap. Personally I % find you can generate some rather nice colourmaps with LABMAP. % % % Coordinates of standard colours in L*a*b* space and in cylindrical coordinates % % red L 54 a 81 b 70 theta 0.7 radius 107 % green L 88 a -79 b 81 theta 2.3 radius 113 % blue L 30 a 68 b -112 theta -1.0 radius 131 % yellow L 98 a -16 b 93 theta 1.7 radius 95 % cyan L 91 a -51 b -15 theta -2.9 radius 53 % magenta L 60 a 94 b -61 theta -0.6 radius 111 % % Example colourmaps: % % labmap([pi pi/2], [20 100], [60 127]); % Dark green to yellow colourmap % labmap([3*pi/2 pi/3], [10 100], [60 127]); % Blue to yellow % labmap([3*pi/2 9*pi/4], [10 60], [60 127]); % Blue to red % lapmap( 0, [0 100], 0); % Lightness greyscale % % See also: VIEWLABSPACE, HSVMAP, GRAYMAP, HSV, GRAY, RANDMAP, BILATERALMAP % Copyright (c) 2012-2013 Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % March 2012 % March 2013 Allow theta, lightness and saturation to vary as a ramps. Allow % cylindrical and linear interpolation across the colour space function map = labmap(theta, L, sat, N, linear, debug) if ~exist('theta', 'var'), theta = [0 2*pi]; end if ~exist('L', 'var'), L = 60; end if ~exist('sat', 'var'), sat = 127; end if ~exist('N', 'var'), N = 256; end if ~exist('linear', 'var'), linear = 0; end if ~exist('debug', 'var'), debug = 0; end if length(theta) == 1, theta = [theta theta]; end if length(L) == 1, L = [L L]; end if length(sat) == 1, sat = [sat sat]; end if ~linear % Use cylindrical interpolation % Generate linear ramps in theta, lightness and saturation thetar = [0:N-1]'/(N-1) * (theta(2)-theta(1)) + theta(1); Lr = [0:N-1]'/(N-1) * (L(2)-L(1)) + L(1); satr = [0:N-1]'/(N-1) * (sat(2)-sat(1)) + sat(1); lab = [Lr satr.*cos(thetar) satr.*sin(thetar)]; map = applycform(lab, makecform('lab2srgb')); else % Interpolate a straight line between start and end colours c1 = [L(1) sat(1)*cos(theta(1)) sat(1)*sin(theta(1))]; c2 = [L(2) sat(2)*cos(theta(2)) sat(2)*sin(theta(2))]; dc = c2-c1; lab = [[0:N-1]'/(N-1).*dc(:,1)+c1(:,1) [0:N-1]'/(N-1).*dc(:,2)+c1(:,2)... [0:N-1]'/(N-1).*dc(:,3)+c1(:,3)]; map = applycform(lab, makecform('lab2srgb')); end if debug % Display colourmap ramp = repmat(0:0.5:255, 100, 1); show(ramp,1), colormap(map); % Test 'integrity' of colourmap. Convert rgb back to lab. If this is % significantly different from the original lab map then we have gone % outside the rgb gamut labmap = applycform(map, makecform('srgb2lab')); diff = lab-labmap; R = 1:N; figure(2), plot(R,lab(:,1),'k-',R,lab(:,2),'r-',R,lab(:,3),'b-',... R,labmap(:,1),'k--',R,labmap(:,2),'r--',R,labmap(:,3),'b--') legend('Specified L', 'Specified a*', 'Specified b*',... 'Achieved L', 'Achieved a*', 'Achieved b*') title('Specified and achieved L*a*b* values in colourmap') % Crude threshold on adherance to specified lab values if max(diff(:)) > 10 warning(sprintf(['Colormap is probably out of gamut. \nMaximum difference' ... ' between desired and achieved lab values is %d'], ... round(max(diff(:))))); end end
github
jacksky64/imageProcessing-master
basename.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/basename.m
549
utf_8
619048021d1d621f2344798ad8fec477
% BASENAME Trims off the .ending of a filename % % Usage: bname = basename(name) % % Argument: name - Name of a file with a .ending % Returns: bname - Name with the suffix trimmed % Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % % August 2010 function bname = basename(name) % Find last instance of a '.' in the file name ind = find(name == '.', 1, 'last'); if isempty(ind) bname = name; else bname = name(1:ind(end)-1); end
github
jacksky64/imageProcessing-master
showfft.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/showfft.m
1,588
utf_8
a10b28024b7bb20f06be15f948efa5b2
% SHOWFFT - Displays amplitude spectrum of an fft. % % Usage: showfft(ft, figNo) % % Arguments: ft - Fourier transform to be displayed % figNo - Optional figure number to display image in. % % The fft is quadrant shifted to place zero frequency at the centre. % % If figNo is omitted a new figure window is created. If figNo is supplied, % and the figure exists, the existing window is reused to display the image, % otherwise a new window is created. % Copyright (c) 1999 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % October 1999 % September 2008 Octave compatible function showfft(im, figNo) Octave = exist('OCTAVE_VERSION', 'builtin') == 5; % Are we running under Octave Title = inputname(1); % Get variable name of image data if nargin == 2 figure(figNo); % Reuse or create a figure window with this number else figNo = figure; % Create new figure window end imagesc(fftshift(abs(im))); colormap(gray); title(Title), axis('image') if ~Octave; truesize(figNo) end
github
jacksky64/imageProcessing-master
deres.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/deres.m
525
utf_8
013e5ac5596abe1811cec7954e1abca0
% DERES - Deresolves an image. % % Usage: im2 = deres(im, s) % % Arguments: im - image to be deresolved % s = deresolution factor % % Returns the deresolved image % PK October 2000 function im2 = deres(im, s) if ndims(im) == 3 % Assume colour image im2 = zeros(size(im)); im2(:,:,1) = blkproc(im(:,:,1),[s s], 'mean2(x)'); im2(:,:,2) = blkproc(im(:,:,2),[s s], 'mean2(x)'); im2(:,:,3) = blkproc(im(:,:,3),[s s], 'mean2(x)'); else im2 = blkproc(im,[s s], 'mean2(x)'); end
github
jacksky64/imageProcessing-master
showangularim.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/showangularim.m
5,543
utf_8
75afab7bd1c9c526602370d0b685a282
% SHOWANGULARIM - Displays image of angular data % % For angular data to be rendered correctly it is important that the data values % are respected so that data values are correctly assigned to specific entries % in a cyclic colour map. The assignment of values to colours also depends on % whether the data is cyclic over pi, or 2*pi. % % In contrast, default display methods typically do not respect data values % directly and can perform inappropriate offsetting and normalisation of the % angular data before display and rendering with a colour map. % % The rendering of the angular data with a specified colour map can be modulated % as a function of an associated image amplitude. This allows the colour map % encoding of the angular information to be modulated to represent the % amplitude/reliability/coherence of the angular data. % % Usage: rgbim = showangularim(ang, map); % rgbim = showangularim(ang, map, param_name, value, ...); % % Arguments: % ang - Image of angular data to be displayed. % map - Colour map to render the angular data with, ideally a % cyclic colour map. % % Possible param_name - value options % % 'amp' - Amplitude image used to modulate the mapped colours of the % angular data. If not supplied no modulation of colours is % performed. % 'bw' - Flag 0/1 indicating whether the amplitude image is used to % modulate the colour mapped image values towards black, 0 % or white, 1. The default is 0, towards black. % 'cycle' - The cycle length of the angular data. Use a value of pi % if the data represents orientations, or 2*pi if the data % represents phase values. If the input data is in degrees % simply set cycle in degrees and the data will be % rendered appropriately. Default is 2*pi. % 'fig' - Optional figure number to use. If not specified a new % figure is created. If set to 0 the function runs % 'silently' returning rgbim without displaying the image. % % Returns: rgbim - The rendered image. % % Parameter name strings can be abbreviated to their first letter except for % 'amp' which can only be abbreviated to 'am' % % For a list of all cyclic colour maps that can be generated by LABMAPLIB use: % >> labmaplib('cyclic') % % See also: SCALOGRAM, RIDGEORIENT, LABMAPLIB, APPLYCOLOURMAP % Copyright (c) 2014 Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % September 2014 % October 2014 Changed optional argument handling to param_name - value pairs %function rgbim = showangularim(ang, amp, map, cycle, bw, fig) function rgbim = showangularim(varargin) [ang, amp, map, cycle, bw, fig] = parseinputs(varargin{:}); % Apply colour map to angular data. Some care is needed with this. Unlike % normal 'linear' data one cannot apply shifts and/or rescale values to % normalise them. The raw angular data values have to be respected. ang = mod(ang, cycle); % Ensure data values are within range 0 - cycle rgbim = applycolourmap(ang, map, [0 cycle]); if ~isempty(amp) % Display image with rgb values modulated by amplitude amp = normalise(amp); % Enforce amplitude 0 - 1 if ~bw % Modulate rgb values by amplitude fading to black for n = 1:3 rgbim(:,:,n) = rgbim(:,:,n).*amp; end else % Modulate rgb values by amplitude fading to white for n = 1:3 rgbim(:,:,n) = 1 - (1 - rgbim(:,:,n)).*amp; end end end if fig show(rgbim,fig) end % If function was not called with any output arguments clear rgbim so that % it is not printed on the screen. if ~nargout clear('rgbim') end %----------------------------------------------------------------------- % Function to parse the input arguments and set defaults function [ang, amp, map, cycle, bw, fig] = parseinputs(varargin) p = inputParser; numericORlogical = @(x) isnumeric(x) || islogical(x); % The first arguments are the image of angular data and the colour map. addRequired(p, 'ang', @isnumeric); addRequired(p, 'map', @isnumeric); % Optional parameter-value pairs and their defaults addParameter(p, 'amp', [], @isnumeric); addParameter(p, 'cycle', 2*pi, @isnumeric); addParameter(p, 'bw', 0, numericORlogical); addParameter(p, 'fig', -1, @isnumeric); parse(p, varargin{:}); ang = p.Results.ang; map = p.Results.map; amp = p.Results.amp; cycle = p.Results.cycle; bw = p.Results.bw; fig = p.Results.fig; if fig < 0, fig = figure; end if ~isempty(amp) && ~all(size(amp)==size(ang)) error('Amplitude data must be same size as angular data'); end
github
jacksky64/imageProcessing-master
sineramp.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/sineramp.m
6,455
utf_8
05497c013c694f1734bc5d8f1a51fe4a
% SINERAMP - Generates sine on a ramp colour map test image % % The test image consists of a sine wave superimposed on a ramp function The % amplitude of the sine wave is modulated from its full value at the top of the % image to 0 at the bottom. % % The image is useful for evaluating the effectiveness of different colour maps. % Ideally the sine wave pattern should be equally discernible over the full % range of the colour map. In addition, across the bottom of the image, one % should not see any identifiable features as the underlying signal is a smooth % ramp. In practice many colour maps have uneven perceptual contrast over their % range and often include 'flat spots' of no perceptual contrast that can hide % significant features. % % Usage: im = sineramp(sze, amp, wavelen, p) % im = sineramp; % % Arguments: sze - [rows cols] specifying size of test image. If a % single value is supplied the image is square. % Defaults to [256 512]; Note the number of columns is % nominal and will be ajusted so that there are an % integer number of sine wave cycles across the image. % amp - Amplitude of sine wave. Defaults to 12.5 % wavelen - Wavelength of sine wave in pixels. Defaults to 8. % p - Power to which the linear attenuation of amplitude, % from top to bottom, is raised. For no attenuation use % p = 0. For linear attenuation use a value of 1. For % contrast sensitivity experiments use larger values of % p. The default value is 2. % % The ramp function that the sine wave is superimposed on is adjusted slightly % for each row so that each row of the image spans the full data range of 0 to % 255. Thus using a large sine wave amplitude will result in the ramp at the % top of the test image being reduced relative to the slope of the ramp at % the bottom of the image. % % To start with try % >> im = sineramp; % % This is equivalent to % >> im = sineramp([256 512], 12.5, 8, 2); % % View it under 'gray' then try the 'jet', 'hsv', 'hot' etc colour maps. The % results may cause you some concern! % % If you are wishing to evaluate a cyclic colour map, say hsv, it is suggested % that you use the test image generated CIRCLESINERAMP. However you can use % this function to perform a basic evaluation of a cyclic colour map by % displaying two copies of the SINERAMP test image concatenated side-by-side. % % >> show([sineramp sineramp]), colour map(map_to_be_tested) % % However, note that despite there being an integer number of sine wave cycles % across the image and that each row has been adjusted to span the full data % range there will be a slight cyclic discontinuity at the top of the image, % though this is progressively removed as you move down the test image. % % See source code comments for more details on the default wavelength and amplitude. % % See also: CIRCLESINERAMP, CHIRPLIN, CHIRPEXP, EQUALISECOLOURMAP, CMAP % The Default Wavelength: % The default wavelength is 8 pixels. On a computer monitor with a nominal % pixel pitch of 0.25mm this corresponds to a wavelength of 2mm. With a monitor % viewing distance of 600mm this corresponds to 0.19 degrees of viewing angle or % approximately 5.2 cycles per degree. This falls within the range of spatial % frequencies (3-7 cycles per degree ) at which most people have maximal % contrast sensitivity to a sine wave grating (this varies with mean luminance). % A wavelength of 8 pixels is also sufficient to provide a reasonable discrete % representation of a sine wave. The aim is to present a stimulus that is well % matched to the performance of the human visual system so that what we are % primarily evaluating is the colour map's perceptual contrast and not the visual % performance of the viewer. % % The Default Amplitude: % This is set at 12.5 so that from peak to trough we have a local feature of % magnitude 25. This is approximately 10% of the 256 levels in a standard % colour map. It is not uncommon for colour maps to have perceptual flat spots % that can hide features of this magnitude. % Copyright (c) 2013-2014 Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % July 2013 Original version. % March 2014 Adjustments to make it better for evaluating cyclic colour maps. % June 2014 Default wavelength changed from 10 to 8. function im = sineramp2(sze, amp, wavelen, p) if ~exist('sze','var'), sze = [256 512]; end if ~exist('amp','var'), amp = 12.5; end if ~exist('wavelen','var'), wavelen = 8; end if ~exist('p','var'), p = 2; end if length(sze) == 1 rows = sze; cols = sze; elseif length(sze) == 2 rows = sze(1); cols = sze(2); else error('size must be a 1 or 2 element vector'); end % Adjust width of image so that we have an integer number of cycles of % the sinewave. This is helps should one be using the test image to % evaluate a cyclic colour map. However you will still see a slight % cyclic discontinuity at the top of the image, though this will % disappear at the bottom of the test image cycles = round(cols/wavelen); cols = cycles*wavelen; % Sine wave x = 0:cols-1; fx = amp*sin( 1/wavelen * 2*pi*x); % Vertical modulating function A = ([(rows-1):-1:0]/(rows-1)).^p; im = A'*fx; % Add ramp ramp = meshgrid(0:(cols-1), 1:rows)/(cols-1); im = im + ramp*(255 - 2*amp); % Now normalise each row so that it spans the full data range from 0 to 255. % Again, this is important for evaluation of cyclic colour maps though a % small cyclic discontinuity will remain at the top of the test image. for r = 1:rows im(r,:) = normalise(im(r,:)); end im = im * 255;
github
jacksky64/imageProcessing-master
pbspline.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/pbspline.m
3,825
utf_8
dc440d359c84c00b130be8c1b75884a8
% PBSPLINE - Basic Periodic B-spline % % Usage: S = pbspline(P, k, N) % % Arguments: P - [dim x Npts] array of control points % k - order of spline (>= 2). % k = 2: Linear % k = 3: Quadratic, etc % N - Optional number of points to evaluate along % spline. Defaults to 100. % % Returns: S - spline curve [dim x N] spline points % % See also: BBSPLINE % PK March 2014 % Nov 2015 Made basis calculation slightly less wasteful % Needs a bit of tidying up and checking on domain of curve. Should be % merged with BBSPLINE function S = pbspline(P, k, N) if ~exist('N', 'var'), N = 100; end % For a closed spline check if 1st and last control points match. If not % add another control point so that they do match if norm(P(:,1) - P(:,end)) > 0.01 P = [P P(:,1)]; end % Now add k - 1 control points that wrap over the first control points P = [P P(:,2:2+k-1)]; [dim, np1] = size(P); n = np1-1; assert(k >= 2, 'Spline order must be 2 or greater'); assert(np1 >= k, 'No of control points must be >= k'); assert(N >= 2, 'Spline must be evaluated at 2 or more points'); % Form a uniform sequence. Number of knot points is m + 1 where m = n + k + 1 ti = [0:(n+k+1)]/(n+k+1); nK = length(ti); % Domain of curve is [ti_k to ti_n] or [ti_(k+1) to ti_(n+1)] ??? tstart = ti(k); tend = ti(n); dt = (tend-tstart)/(N-1); t = tstart:dt:tend; % Build complete array of basis functions. We maintain two % arrays, one storing the basis functions at the current level of % recursion, and one storing the basis functions from the previous % level of recursion B = cell(1,nK-1); Blast = cell(1,nK-1); % 1st level of recursive construction for i = 1:nK-1 Blast{i} = t >= ti(i) & t < ti(i+1) & ti(i) < ti(i+1); end % Subsequent levels of recursive basis construction. Note the logic to % handle repeated knot values where ti(i) == ti(i+1) for ki = 2:k for i = 1:nK-ki if (ti(i+ki-1) - ti(i)) < eps V1 = 0; else V1 = (t - ti(i))/(ti(i+ki-1) - ti(i)) .* Blast{i}; end if (ti(i+ki) - ti(i+1)) < eps V2 = 0; else V2 = (ti(i+ki) - t)/(ti(i+ki) - ti(i+1)) .* Blast{i+1}; end B{i} = V1 + V2; % This is the ideal equation that the code above implements % N{i,ki} = (t - ti(i))/(ti(i+ki-1) - ti(i)) .* N{i,ki-1} + ... % (ti(i+ki) - t)/(ti(i+ki) - ti(i+1)) .* N{i+1,ki-1}; end % Swap B and Blast, but only if this is not the last iteration if ki < k tmp = Blast; Blast = B; B = tmp; end end % Apply basis functions to the control points S = zeros(dim, length(t)); for d = 1:dim for i = 1:np1 S(d,:) = S(d,:) + P(d,i)*B{i}; end end % Finally, because of the knot arrangements, the start of the spline may not % be close to the first control point if the spline order is 3 or greater. % Normally for a closed spline this is irrelevant. However for our purpose % of using closed bplines to form paths in a colourspace this is important to % us. The simple brute force solution used here is to search through the % spline points for the point that is closest to the 1st control point and % then rotate the spline points accordingly distsqrd = 0; for d = 1:dim distsqrd = distsqrd + (S(d,:) - P(d,1)).^2; end [~,ind] = min(distsqrd); S = circshift(S, [0, -ind+1]);
github
jacksky64/imageProcessing-master
cloud9.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/cloud9.m
3,590
utf_8
3ce5e64cce1547247f3b914e7a6fc5c8
% CLOUD9 - Cloud movie of 1/f noise. % % Function to create a movie of noise images having 1/f amplitude spectum % properties. % % Usage: CloudMovie = cloud9(size, factor, nturns, velfactor, nframes) % % size - [rows cols] size of image to produce % factor - controls spectrum = 1/(f^factor) % nturns - No of 2pi cycles phase can change over the whole sequence % lowvel - phase velocity at 0 frequency % velfactor - phase velocity = freq^velfactor % nframes - no of frames in movie % % factor = 0 - raw Gaussian noise image % = 1 - gives the 1/f `standard' drop-off for `natural' images % = 1.5 - seems to give the most intersting `cloud patterns' % = 2 or greater - produces `blobby' images % % Favourite parameters: % m = cloud9([480 640], 1.5, 4, 1, .1, 100); % % Copyright (c) 2000 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % April 2000 function CloudMovie = cloud9(sze, factor, nturns, lowvel, velfactor, nframes) rows = sze(1); cols = sze(2); phase = i*random('Uniform',0,2*pi,rows,cols); % Random uniform distribution 0 - 2pi % Create two matrices, x and y. All elements of x have a value equal to its % x coordinate relative to the centre, elements of y have values equal to % their y coordinate relative to the centre. From these two matrices produce % a radius matrix that gives distances from the middle x = ones(rows,1) * (-cols/2 : (cols/2 - 1)); % x = x/(cols/2); y = (-rows/2 : (rows/2 - 1))' * ones(1,cols);% y = y/(rows/2); radius = sqrt(x.^2 + y.^2); % Matrix values contain radius from centre. radius(rows/2+1,cols/2+1) = 1; % .. avoid division by zero. amp = 1./(radius.^factor); % Construct the amplitude spectrum amp = fftshift(amp); phasemod = round(fftshift(radius.^velfactor + lowvel)); phasechange = 2*pi*((random('unid',nturns+1,rows,cols) -1 - nturns/2) .* phasemod ); maxturns = max(max(phasechange/(2*pi))) maxturns = min(min(phasechange/(2*pi))) minturns = min(min(abs(phasechange)/(2*pi))) dphase = i*phasechange/(nframes-1); % premultiply by i to save time in th eloop % Construct fft of noise image with the specified amplitude spectrum fig = figure(1), warning off, imagesc(zeros(rows,cols)), axis('off'), truesize(1) set(fig,'DoubleBuffer','on'); %set(gca,'xlim',[-80 80],'ylim',[-80 80],... % 'NextPlot','replace','Visible','off') mov = avifile('cloud') a = 0.7; % Set up colormap map = a*bone + (1-a)*gray; for n = 1:nframes fprintf('frame %d/%d \r',n, nframes); phase = phase + dphase; newfft = amp .* exp(phase); im = real(ifft2(newfft)); % Invert to obtain final noise image imagesc(im), colormap(bone),axis('equal'), axis('off'), truesize(1) %if n==1 % CloudMovie = moviein(nframes); % initialise movie storage %end F = getframe(gca); mov = addframe(mov,F); %CloudMovie(:,n) = getframe; end fprintf('\n'); warning on mov = close(mov); %movie(CloudMovie,5,30); %save('CloudMovie','CloudMovie');
github
jacksky64/imageProcessing-master
circle.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/circle.m
1,226
utf_8
3ce939f9b481cd974576f40a598a69b6
% CIRCLE - Draws a circle. % % Usage: circle(c, r, n, col) % % Arguments: c - A 2-vector [x y] specifying the centre. % r - The radius. % n - Optional number of sides in the polygonal approximation. % (defualt is 16 sides) % col - optional colour, defaults to blue. % Copyright (c) 1996-2005 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. function h = circle(c, r, nsides, col) if nargin == 2 nsides = 16; end if nargin < 4 col = [0 0 1]; end nsides = max(round(nsides),3); % Make sure it is an integer >= 3 a = [0:2*pi/nsides:2*pi]; h = line(r*cos(a)+c(1), r*sin(a)+c(2), 'color', col);
github
jacksky64/imageProcessing-master
showdivim.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/showdivim.m
2,519
utf_8
9205933da4b7d7051f7944c5724dc03b
% SHOWDIVIM - Displays image with diverging colour map % % For data to be displayed correctly with a diverging colour map it is % important that the data values are respected so that the reference value in % the data is correctly associated with the centre entry of a diverging % colour map. % % In contrast, default display methods typically do not respect data values % directly and can perform inappropriate offsetting and normalisation of the % angular data before display and rendering with a colour map. % % Usage: rgbim = showdivim(im, map, refval, fig) % % Arguments: % im - Image to be displayed. % map - Colour map to render the data with. % refval - Reference value to be associated with centre point of % diverging colour map. Defaults to 0. % fig - Optional figure number to use. If not specified a new % figure is created. If set to 0 the function runs % 'silently' returning rgbim without displaying the image. % Returns: % rgbim - The rendered image. % % For a list of all diverging colour maps that can be generated by LABMAPLIB % use: >> labmaplib('div') % % See also: SHOW, SHOWANGULARIM, APPLYCOLOURMAP % Copyright (c) 2014 Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % PK October 2014 function rgbim = showdivim(im, map, refval, fig) if ~exist('refval', 'var'), refval = 0; end if ~exist('fig', 'var'), fig = figure; end minv = min(im(:)); maxv = max(im(:)); if refval < minv || refval > maxv fprintf('Warning: reference value is outside the range of image values\n'); end dr = max([maxv - refval, refval - minv]); range = [-dr dr] + refval; rgbim = applycolourmap(im, map, range); if fig show(rgbim,fig) end % If function was not called with any output arguments clear rgbim so that % it is not printed on the screen. if ~nargout clear('rgbim') end
github
jacksky64/imageProcessing-master
applycolourmap.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/applycolourmap.m
2,248
utf_8
cdab830abbc0e87f8934481ecf26f5c4
% APPLYCOLOURMAP Applies colourmap to a single channel image to obtain an RGB result % % Usage: rgbim = applycolourmap(im, map, range) % % Arguments: im - Single channel image to apply colourmap to. % map - RGB colourmap of size ncolours x 3. RGB values are % floating point values in the range 0-1. % range - Optional 2-vector specifying the min and max values in % the image to be mapped across the colour map. Values % outside this range are mapped to the end points of the % colour map. If range is omitted, or empty, the full range % of image values are used. % % Returns: rgbim - RGB image of floating point values in the range 0-1. % NaN values in the input image are rendered as black. % % This function is used by RELIEF as a base image upon which to apply relief % shading. Is is also used by SHOWANGULARIM. % % See also: IRELIEF, RELIEF, SHOWANGULARIM % Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % November 2013 % September 2014 - Optional range specification added and speeded up by removing loops! function rgbim = applycolourmap(im, map, range) [ncolours,chan] = size(map); assert(chan == 3, 'Colourmap must have 3 columns'); assert(ndims(im) == 2, 'Image must be single channel'); if ~isa(im,'double'), im = double(im); end if ~exist('range', 'var') || isempty(range) range = [min(im(:)) max(im(:))]; end assert(range(1) < range(2), 'range(1) must be less than range(2)'); [rows,cols] = size(im); % Convert image values to integers that can be used to index into colourmap im = round( (im-range(1))/(range(2)-range(1)) * (ncolours-1) ) + 1; mask = isnan(im); im(mask) = 1; % Set any Nan entries to 1 and im(im < 1) = 1; % clamp out of range entries. im(im > ncolours) = ncolours; rgbim = zeros(rows,cols,3); rgbim(:,:,1) = ~mask.*reshape(map(im,1), rows, cols); rgbim(:,:,2) = ~mask.*reshape(map(im,2), rows, cols); rgbim(:,:,3) = ~mask.*reshape(map(im,3), rows, cols);
github
jacksky64/imageProcessing-master
derespolar.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/derespolar.m
2,543
utf_8
16675236c863fa3ce1c748e6f5264835
% DERESPOLAR - Desresolves image in polar coordinates. % % Performs a deresolution operation on an image using Polar Coordinates % % Usage: deres = derespolar(im, nr, na, xc, yc) % where: nr = resolution in the radial direction % na = resolution in the angular direction % xc = column of polar origin (optional) % yc = row of polar origin (optional) % % If xc and yc are omitted the polar origin defaults to the centre of the image % Copyright (c) 1999 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % May 1999 % This code is horribly inefficient and needs a rewrite... function deres = derespolar(im,nr,na,xc,yc) [rows,cols] = size(im); if nargin == 3 xc = round(cols/2); yc = round(rows/2); end if ndims(im) == 3 % Assume colour image deres = uint8(zeros(size(im))); deres(:,:,1) = iderespolar(im(:,:,1),nr,na,xc,yc); deres(:,:,2) = iderespolar(im(:,:,2),nr,na,xc,yc); deres(:,:,3) = iderespolar(im(:,:,3),nr,na,xc,yc); else deres = iderespolar(im,nr,na,xc,yc); end % Internal function that does the work function deres = iderespolar(im,nr,na,xc,yc) [rows,cols] = size(im); %x = ones(rows,1) * (-cols/2 : (cols/2 - 1)); %y = (-rows/2 : (rows/2 - 1))' * ones(1,cols); [x,y] = meshgrid(-xc:cols-xc-1, -yc:rows-yc-1); radius = sqrt(x.^2 + y.^2); % Matrix values contain radius from centre. theta = atan2(y,x); % Matrix values contain polar angle. dr = max(max(radius))/nr; da = max(max(theta+pi))/na; rp = round(radius/dr)*dr; ra = round(theta/da)*da; rowp = yc + rp.*sin(ra); colp = xc + rp.*cos(ra); rowp = round(rowp); colp = round(colp); rowp = max(rowp,1); rowp = min(rowp,rows); colp = max(colp,1); colp = min(colp,cols); for row = 1:rows for col = 1:cols deres(row,col) = im(rowp(row,col), colp(row,col)); end end
github
jacksky64/imageProcessing-master
map2geosofttbl.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/map2geosofttbl.m
1,642
utf_8
8886e0a749224765428fd3f92e8ac2c4
% MAP2GEOSOFTTBL Converts MATLAB colourmap to Geosoft .tbl file % % Usage: map2geosofttbl(map, filename, cmyk) % % Arguments: map - N x 3 rgb colourmap % filename - Output filename % cmyk - Optional flag 0/1 indicating whether CMYK values should % be written. Defaults to 0 whereby RGB values are % written % % This function writes a RGB colourmap out to a .tbl file that can be loaded % into Geosoft Oasis Montaj or QGIS % % See also: RGB2CMYK % Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % PK October 2012 % June 2014 - RGB or CMYK option function map2geosofttbl(map, filename, cmyk) if ~exist('cmyk', 'var'), cmyk = 0; end [N, cols] = size(map); if cols ~= 3 error('Colourmap must be N x 3 in size') end % Ensure filename ends with .tbl if ~strendswith(filename, '.tbl') filename = [filename '.tbl']; end fid = fopen(filename, 'wt'); if cmyk % Convert RGB values in map to CMYK and scale 0 - 255 cmyk = round(rgb2cmyk(map)*255); kcmy = circshift(cmyk, [0 1]); % Shift K to 1st column fprintf(fid, '{ blk cyn mag yel }\n'); for n = 1:N fprintf(fid, ' %03d %03d %03d %03d \n', kcmy(n,:)); end else % Write RGB values map = round(map*255); fprintf(fid, '{ red grn blu }\n'); for n = 1:N fprintf(fid, ' %3d %3d %3d\n', map(n,:)); end end fclose(fid);
github
jacksky64/imageProcessing-master
digipts.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/digipts.m
876
utf_8
95a93e018771e295649e1cc41496df4e
% DIGIPTS - digitise points in an image % % Function to digitise points in an image. Points are digitised by clicking % with the left mouse button. Clicking any other button terminates the % function. Each location digitised is marked with a red '+'. % % Usage: [u,v] = digipts % % where u and v are nx1 arrays of x and y coordinate values digitised in % the image. % % This function uses the cross-hair cursor provided by GINPUT. This is % much more useable than IMPIXEL % Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk @ csse uwa edu au % http://www.csse.uwa.edu.au/~pk % % May 2002 function [u,v] = digipts hold on u = []; v = []; but = 1; while but == 1 [x y but] = ginput(1); if but == 1 u = [u;x]; v = [v;y]; plot(u,v,'r+'); end end hold off
github
jacksky64/imageProcessing-master
polyval2d.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/polyval2d.m
1,403
utf_8
699c1158bb9d569730ba4b087241556c
% POLYVAL2D Evaluates 2D polynomial surface generated by POLYFIT2D % % Usage: z = polyval2d(x, y, c) % % Arguments: x, y - Locations where polynomial is to be evaluated % c - Coefficients of polynomial as generated by polyfit2d % % Returns z - The surface values evalated at x, y % % For a degree 3 surface the coefficients are expected to progress in the % form % 00 01 02 03 10 11 12 20 21 30 % where the first digit is the y exponent and the 2nd the x exponent % % 0 0 0 1 0 2 0 3 1 0 1 1 1 2 % c1 x y + c2 x y + c3 x y + c4 x y + c5 x y + c6 x y + c7 x y + ... % % See also: POLYFIT2D % Peter Kovesi 2014 % Centre for Exploration Targeting % The University of Western Australia % peter.kovesi at uwa edu au % PK July 2014 function z = polyval2d(x, y, c) % Solve quadratic to determin degree of polynomial % ncoeff = (degree+1)*(degree+2)/2 ncoeff = length(c); degree = -1.5 + sqrt(2.25 - 2*(1-ncoeff)); if round(degree) ~= degree error('Cannot determine polynomial degree from number of coefficients'); end % p1 is the x exponent and p2 is the y exponent z = zeros(size(x)); ind = 1; for p2 = 0:degree for p1 = 0:(degree-p2) z = z + c(ind) * x.^p1 .* y.^p2; ind = ind+1; end end
github
jacksky64/imageProcessing-master
implace.m
.m
imageProcessing-master/Matlab Code for Computer Vision/Misc/implace.m
3,014
utf_8
e28ca1e9784b3b7297c12b70c7278015
% IMPLACE - place image at specified location within larger image % % Usage: newim = implace(im1, im2, roff, coff) % % Arguments: % % im1 - Image that im2 is to be placed in. % im2 - Image to be placed. % roff - Row and column offset of placement of im2 relative % coff to im1, (0,0) aligns top left corners. % % Warning: The class of final image matches the class of im1. If im1 is of % type double and im2 is a uint8 colour image you will obtain a double image % having 3 colour channels with values ranging between 0-255. This will % need to be cast to uint8, or divided by 255, for display via imshow or % show. % Copyright (c) 2004-2008 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % September 2004 Original version % July 2008 Bug fixes for colour images function newim = implace(im1, im2, roff, coff) [rows1, cols1, d] = size(im1); [rows2, cols2, d] = size(im2); % Find min row and column of im2 that will appear in im1 rmin2 = max(1,1-roff); cmin2 = max(1,1-coff); % Find min row and column within im1 that im2 covers rmin1 = max(1,1+roff); cmin1 = max(1,1+coff); % Find max row and column of im2 that will appear in im1 rmax2 = min(rows1-roff, rows2); cmax2 = min(cols1-coff, cols2); % Find max row and column within im1 that im2 covers rmax1 = min(rows2+roff, rows1); cmax1 = min(cols2+coff, cols1); % Check for the case where there is no overlap of the images if rmax1 < 1 | cmax1 < 1 | rmax2 < 1 | cmax2 < 1 | ... rmin1 > rows1 | cmin1 > cols1 | rmin2 > rows2 | cmin2 > cols2 newim = im1; % Simply copy im1 to newim else % Place im2 into im1 % Check if either image is colour and if one needs promoting to colour ndim1 = ndims(im1); ndim2 = ndims(im2); if ndim1 == 2 & ndim2 == 3 fprintf('promoting im1 \n'); im1 = uint8(repmat(im1,[1,1,3])); % 'Promote' im1 to 3 channels ndim1 = 3; elseif ndim2 == 2 & ndim1 == 3 fprintf('promoting im2 \n'); im2 = uint8(repmat(im2,[1,1,3])); % 'Promote' im2 to 3 channels ndim2 = 3; end newim = im1; if ndim1 ==2 % Greyscale newim(rmin1:rmax1, cmin1:cmax1) = ... im2(rmin2:rmax2, cmin2:cmax2); else % Assume colour newim(rmin1:rmax1, cmin1:cmax1,:) = ... im2(rmin2:rmax2, cmin2:cmax2,:); end end