How to apply recursion?
Afficher commentaires plus anciens
I am trying to use recursion to apply region growing but I have got an error: Out of memory. The likely cause is an infinite recursion within the program.
I am posting the code snippet here,Can somebody point out the error and make suggestions.Thank you.
Here,Ig is the grayscale image with intensities to check
i is column vector containing x-coordinates of seed pixels
j is column vector containing y-coordinates of seed pixels
threshold is column vector containing threshold values for seed pixels
reg_output is the final logical array output after region growing ,
visited is a matrix used to prevent redundant computations using recursion,
%REGION GROWING FROM ALL LOW INTENSITY PIXELS
global reg_output;
reg_output = zeros(size(Ig));
global visited;
visited = zeros(size(Ig));
global row;
global col;
row = [-1;-1;-1;0;0;1;1;1];
col = [-1;0;1;-1;1;-1;0;1];
global si;
global sj;
[si,sj] = size(Ig);
for ll = 1:length(i)
region_grow(i(ll),j(ll),threshold(ll));
end
figure,imshow(reg_output)
function region_grow(m,n,t)
global reg_output;
global visited;
global Ig;
global row;
global col;
global si;
global sj;
reg_output(m,n) = 1;
visited(m,n) = 1;
for kc = 1:length(row)
i = m+row(kc);
j = n+col(kc);
if i>=1 && i<=si && j>=1 && j<=sj
if visited(i,j)==0 && Ig(i,j)>= t
region_grow(i,j,t);
end
end
end
end
4 commentaires
Stephen23
le 9 Jan 2020
Ugh, no, no, no, no... Do NOT write such basic code with global variables, they will make your code buggy and difficult to debug.
You should parameterize your function properly, just like the documentation explains:
Guillaume
le 9 Jan 2020
Yes, sorry don't use globals. They may or may not be the cause of your problem in this case, but globals always result in problems. It's better if you learn to program without them.
What exactly is code doing? Couldn't it be implemented with a convolution?
Adam Danz
le 9 Jan 2020
All of those global variables reminds me of a mirror "fun house" where you have no idea where objects are coming from or where they are heading.

A better solution is to pass in a structure or cell array variable containing all of the globally accessed variables.
Which line is throwing the error?
Guillaume
le 9 Jan 2020
it looks like the global are probably local to the functions, so possibly could be replaced by persistent variables.
However, even that I'm not convinced that it's needed, particularly if the recursion is removed. Recursion is rarely a good idea.
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Whos dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!