Dear All, I am really new to matlab and dont know how to run this code. can anybody guide me stepwise? code courtesy: http://www​.cs.sfu.ca​/~hamarneh​/software/​livewire/l​wcontour_s​ven.m

조회 수: 2 (최근 30일)
function IJpath_return_vector = lwcontour_sven(image2d, varargin)
IP = inputParser; IP.addParamValue('clims', [], @(x)isnumeric(x) && length(x)==2 && diff(x)>0); IP.addParamValue('fig_h', [], @ishandle); IP.addParamValue('seedIJ', [-1 -1], @(x)isnumeric(x) && length(x)==2); IP.addParamValue('xVec', [], @(x)isnumeric(x) && all(diff(x)>0)); IP.addParamValue('yVec', [], @(x)isnumeric(x) && all(diff(x)>0)); IP.parse(varargin{:});
if isempty(IP.Results.xVec) isempty(IP.Results.yVec) PxIJ_to_AxIJ = @(pxIJ)pxIJ; AxIJ_to_PxIJ = @(axIJ)axIJ; else PxIJ_to_AxIJ = @(pxIJ)[IP.Results.yVec(pxIJ(:,1))' IP.Results.xVec(pxIJ(:,2))']; AxIJ_to_PxIJ = @(axIJ)round([ interp1(IP.Results.yVec(:),1:length(IP.Results.yVec), axIJ(:,1)), ... interp1(IP.Results.xVec(:),1:length(IP.Results.xVec), axIJ(:,2))]); end
findNeighbour = @findNeighbour_LWCONTOUR;
p_inputImage = im2doubleWithBounds(image2d, IP.Results.clims); [imageCannyEdge, imageLoG, gradientx, gradienty, magnitude] = getImageEdgesAndGradients(p_inputImage); wghtCoA = 4; %Presence of canny edge weight wghtCoB = 1; %Gradient magnitude weight wghtCoC = 1; %Gradient direction weight wghtCoD = 4; %Presence of LoG edge weight imageSizeIJ = size(imageCannyEdge);
% Start with an empty contour contourIJset = {};
% Create a figure showing the image, or use the one provided if ishandle(IP.Results.fig_h) fig_h = IP.Results.fig_h; figure(fig_h) figureCreated = false; else fig_h = figure; imshow(p_inputImage); figureCreated = true; end hold on;
% Get a starting seed, and calculate the initial COST function image seedIJ = AxIJ_to_PxIJ(IP.Results.seedIJ); while ~isValidSeed(seedIJ, 1) inputSeed = ginput(1); seedIJ = AxIJ_to_PxIJ(inputSeed([2 1])); end COST = getCOST(seedIJ);
H_permLine = plot(seedIJ(2), seedIJ(1), 'Color','g', 'LineWidth',3,'Tag','lwpermline'); H_tempLine = plot(nan, nan, 'Color','m', 'LineWidth',3,'Tag','lwpermline');
% Apply mouse and button actions, storing the old ones for restoration oldFcnStruct = applyFigFcns();
% Wait for the user to draw their contours. Pressing a button will resume uiwait(fig_h);
% Build the final contour to be returned. if isempty(contourIJset) IJpath_return_vector = zeros(0,2); else IJpath_return_vector = PxIJ_to_AxIJ(cat(1, contourIJset{:})); end if ~ishandle(fig_h), return; end set(fig_h, oldFcnStruct) % Resotre the original figure functions in case they were overwritten if figureCreated close(fig_h); end
%% SUPPORTING SUB-FUNCTIONS function oldFcnStruct = applyFigFcns() % Set the livewire mouse and button actions, retaining the old functions for restoration fcnNames = {'WindowButtonDownFcn','WindowButtonMotionFcn','KeyPressFcn','KeyReleaseFcn'}; fcnVals = get(fig_h,fcnNames); fcnNameValPairs = cat(1, fcnNames, fcnVals); oldFcnStruct = struct(fcnNameValPairs{:}); set(fig_h,'WindowButtonDownFcn',@(src,evnt)onSeedClick); set(fig_h,'WindowButtonMotionFcn',@(src,evnt)onMouseMove); set(fig_h,'KeyPressFcn',@(src,evnt)onKeyPress(src,evnt)); set(fig_h,'KeyReleaseFcn',@(src,evnt)onKeyRelease(src,evnt)); end
function pxIJ = currentPointInPxIJ()
seed=get(gca,'CurrentPoint');
pxIJ = round(AxIJ_to_PxIJ(seed(1,[2 1])));
end
function onSeedClick()
if ~isValidSeed(clickedIJ, 1), return; end
[pathI, pathJ] = findNeighbour(clickedIJ(1), clickedIJ(2));
contourIJset{end+1} = [pathI' pathJ'];
updateFullPathDisplay()
COST = getCOST(clickedIJ);
end
function updateFullPathDisplay()
% Update the new permanent line, and reset the temporary line
fullPathIJ = cat(1, contourIJset{:});
if isempty(fullPathIJ), fullPathIJ = [nan nan]; end
drawPath = PxIJ_to_AxIJ(fullPathIJ);
set(H_permLine,'XData', drawPath(:,2), 'YData', drawPath(:,1))
set(H_tempLine,'XData', [], 'YData', [])
end
function TF = isValidSeed(inputSeedIJ, paddingIJ)
% Is this input a valid point inside the input image? Seeds may not lie on image boundaries
% or a .dll error occurs, so seed points should have paddingIJ = 1.
if nargin<2, paddingIJ=0; end
TF = all(inputSeedIJ>paddingIJ & inputSeedIJ<=(imageSizeIJ-paddingIJ));
end
function onMouseMove()
% As the mouse moves, get the hovered point, then get the best path from there to the source
% location of the COST image.
hoveredIJ = currentPointInPxIJ();
[pathI, pathJ] = findNeighbour(hoveredIJ(1), hoveredIJ(2));
% Update the temporary line to show this calculated path
if ~any(isnan([pathI,pathJ]))
drawPath = PxIJ_to_AxIJ([pathI(:), pathJ(:)]);
else
drawPath = [nan nan];
end
set(H_tempLine,'XData', drawPath(:,2), 'YData', drawPath(:,1))
end
function onKeyPress(src, evnt)
% Return upon any key press
switch lower(evnt.Key)
case 'u' % UNDO last clicked path segment!
fprintf('Undo last point.\n')
if isempty(contourIJset), return; end
% Grab the previous source point then remove that piece of the path
previousSourceIJ = contourIJset{end}(1,:);
contourIJset(end) = [];
% Update the display and reset the COST image based on this previous source pt
updateFullPathDisplay()
COST = getCOST(previousSourceIJ);
case 'control' % Clear out the key press function (onKeyRelease will reset it)
fprintf('Starting straight-line mode... ')
set(fig_h,'KeyPressFcn','');
findNeighbour = @findNeighbour_STRAIGHT;
otherwise % IN ALL OTHER CASES, END PROGRAM AND RESUME
delete([H_permLine H_tempLine])
uiresume(src);
end
end
function onKeyRelease(~, evnt)
% Resume the normal key press function when 'control' is released
if strcmpi('control', evnt.Key)
fprintf('straight-line mode ended.\n')
set(fig_h,'KeyPressFcn',@(src,evnt)onKeyPress(src,evnt));
findNeighbour = @findNeighbour_LWCONTOUR;
end
end
function COST = getCOST(seedSubs)
% Calculate the COST using simplelw, then ensure the borders are impossible to reach
seedSubs = seedSubs-1; % Negate one to conform with simplelw syntax.
output=simplelw(imageSizeIJ(1),imageSizeIJ(2),seedSubs(1),seedSubs(2),wghtCoA,wghtCoB,wghtCoC,wghtCoD,gradientx,gradienty,imageCannyEdge,imageLoG,magnitude);
output(output(:) == max(output(:))) = inf;
COST = output;
end
function [endx, endy] = findNeighbour_LWCONTOUR(endx, endy)
% Walk from the endx, endy points to the source location of the COST image
% NOTE: Within findNeighbour, "x" and "y" really mean the first and second dimensions of an
% image, not true X and Y directions
%Checks if coordinates are valid
if ~isValidSeed([endx, endy])
return;
end
findNeighbourX = [-1 -1 -1 0 0 1 1 1]';%vector for calculating neighbour pixels
findNeighbourY = [-1 0 1 -1 1 -1 0 1]';
% Start walking!
pathcost = COST(endx, endy);%flipped x|y
previouscost = pathcost+1;
while ((pathcost > 0) && (previouscost > pathcost))
neighbour = [findNeighbourX+endx(1) findNeighbourY+endy(1)];%fncFindNeighbour(endx, endy, 1, 1, imagesize(1), imagesize(2));
endx = [neighbour(1,1) endx]; %#ok, I guess
endy = [neighbour(1,2) endy]; %#ok, I guess
for ind = 1:size(neighbour,1)
if (COST(neighbour(ind,1), neighbour(ind,2)) < pathcost)
pathcost = COST(neighbour(ind,1), neighbour(ind,2));
endx(1) = neighbour(ind,1);
endy(1) = neighbour(ind,2);
end;%end of if (cost()<
end;%end of for loop
end;%while pathcost > 0
end
function [endx, endy] = findNeighbour_STRAIGHT(endx, endy)
%Checks if coordinates are valid
if ~isValidSeed([endx, endy]),
return;
end
% Walk STRAIGHT!
[~, minIdx] = min(COST(:));
[srcI, srcJ] = ind2sub(size(COST),minIdx);
srcXY = [srcI, srcJ]; tgtXY = [endx, endy];
srtToTgtDistance = ceil(sqrt(sum((tgtXY-srcXY).^2,2)));
pathXY = round(interp1([0;1],[srcXY;tgtXY],linspace(0,1,srtToTgtDistance)));
endx = pathXY(:,1)';
endy = pathXY(:,2)';
end
end
%% SUPPORTING FUNCTIONS function convertedIm = im2doubleWithBounds(I, clims) % Convert an image to double, bounded by limits [min max] if nargin<2 length(clims)~=2, clims = double([min(I(:)) max(I(:))]); end convertedIm = (double(I)-clims(1))/diff(clims); convertedIm = min(max(convertedIm,0), 1); end
function [imageCannyEdge, imageLoG, gradientx, gradienty, magnitude] = getImageEdgesAndGradients(p_inputImage)
% Handle edge changes that are identical regardless of input type, setting edge costs to 0 imageCannyEdge = edge(mean(p_inputImage,3), 'canny'); imageLoG = edge(mean(p_inputImage,3),'log'); imageCannyEdge = abs(imageCannyEdge -1); imageLoG = abs(imageLoG -1);
switch size(p_inputImage,3) case 1 % SIMPLE GRAYSCALE IMAGE % get the x and y gradient [gradientx, gradienty] = gradient(mean(p_inputImage,3)); %Calculate gradient magnitude magnitude = sqrt(gradientx.*gradientx + gradienty.*gradienty); maxMag = max(magnitude(:)); %invert the magnitude map so high magnitude has low cost. %normalized to within 0:1 range magnitude = abs(magnitude./maxMag - 1);
case 3 % RGB IMAGE
% Calculate color gradient magnitude and direction using all 3 colors
[du_dx,du_dy] = gradient(p_inputImage(:,:,1));
[dv_dx,dv_dy] = gradient(p_inputImage(:,:,2));
[dw_dx,dw_dy] = gradient(p_inputImage(:,:,3));
[gradientx, gradienty, magnitude] = deal(zeros(size(du_dx)));
for ind = 1:numel(du_dx)
D=[du_dx(ind),du_dy(ind); dv_dx(ind),dv_dy(ind); dw_dx(ind), dw_dy(ind);];
[eigen_vectors, eigen_values] = eig(D'*D);
magnitude(ind) = max(diag(eigen_values));
if eigen_values(1,1) == 0 && eigen_values(2,2) == 0
continue; % gradients already zero
elseif eigen_values(1,1) > eigen_values(2,2)
gradientx(ind) = eigen_vectors(2,1);
gradienty(ind) = eigen_vectors(1,1);
else
gradientx(ind)=eigen_vectors(1,2);
gradienty(ind)=eigen_vectors(2,2);
end;
end
magnitude = sqrt(magnitude); % Magnitudes were stored as max eigenvalue. True mag is sqrt of that.
%invert the magnitude map so high magnitude has low cost.
%normalized to within 0:1 range
magnitude = abs(magnitude./max(abs(magnitude(:))) - 1);
end
end
  댓글 수: 2
Sven
Sven 2014년 11월 23일
Dear "s d",
1. You didn't actually ask a question. A step-by-step guide to using some code you found without any context to what you've done or what you want to do is completely impossible. You might not have MATLAB installed, you might not have lwcontour in your path, you might not have your computer on. We don't know.
2. You chose to copy an entire file's code into your question and then asked how to use it. Did you even notice the help section at the top that tells you how to use the code? You literally copied every line of the file above and below this help but chose to ignore the help itself.
Please heed David's answer - start with "getting started".

댓글을 달려면 로그인하십시오.

답변 (1개)

David Young
David Young 2014년 11월 21일
Probably the best place to start is the getting started guide. You'll find the sections on functions and scripts particularly useful, but it would be wise to run through the whole thing.

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by