function F = floodfill(I, node, targ, repl) % FLOODFILL - fills a region in I continuous with node (from targ to repl) % % Uses 4-connectivity % % returns only the part that was filled if I(node(1), node(2)) ~= targ F = []; warning('chosen node did not have target colour'); else F = zeros(size(I)); % the new image, after floodfill is applied Q = node; % The queue of nodes to be checked; new nodes added at end P = zeros(size(I)); % Keeps track of nodes that have been processed while ~isempty(Q) % while there are members of the queue n = Q(1:2); % the node to be checked % cut the first two elements off the node if length(Q) > 2 Q = Q(3:length(Q)); else Q = []; end if I(n(1), n(2)) == targ % if node is of the target colour F(n(1), n(2)) = repl; % colour node with replacement colour P(n(1), n(2)) = 1; % record that we've processed node % if north node exists, and it has not been processed, add it to end of Q if (n(1) ~= 1) && (P(n(1) - 1, n(2)) == 0) Q = [Q, n(1) - 1, n(2)]; %#ok<*AGROW> P(n(1) - 1, n(2)) = 1; end % if west node exists, and it has not been processed, add it to end of Q if (n(2) ~= 1) && (P(n(1), n(2) - 1) == 0) Q = [Q, n(1), n(2) - 1]; %#ok<*AGROW> P(n(1), n(2) - 1) = 1; end % if east node exists, and it has not been processed, add it to end of Q if (n(2) ~= size(I, 2)) && (P(n(1), n(2) + 1) == 0) Q = [Q, n(1), n(2) + 1]; %#ok<*AGROW> P(n(1), n(2) + 1) = 1; end % if south node exists, and it has not been processed, add it to end of Q if (n(1) ~= size(I, 1)) && (P(n(1) + 1, n(2)) == 0) Q = [Q, n(1) + 1, n(2)]; %#ok<*AGROW> P(n(1) + 1, n(2)) = 1; end end end end