I am new in MATLAB, I am trying to implement flood filling using this algorithm in matlab, I dont know what I did wrong may be I didnt used recursive function right, but still I dont whats going wrong and this code make my matlab close I am using the following code I am trying to debug it since morning but failed to find the problem
function [ colored_Image ] = floodFill( image, target_Loc_x, target_Loc_y, targetColor, replacementColor )
colored_Image = image;
if (target_Loc_x >= 1) && (target_Loc_x <= size(image,1)) && (target_Loc_y >= 1) && (target_Loc_y <= size(image,2))
if image(target_Loc_x,target_Loc_y) == targetColor
colored_Image(target_Loc_x,target_Loc_y) = replacementColor;
colored_Image = floodFill(colored_Image,target_Loc_x ,target_Loc_y + 1, targetColor, replacementColor);
colored_Image = floodFill(colored_Image,target_Loc_x + 1,target_Loc_y, targetColor, replacementColor);
colored_Image = floodFill(colored_Image,target_Loc_x,target_Loc_y - 1, targetColor, replacementColor);
colored_Image = floodFill(colored_Image,target_Loc_x - 1,target_Loc_y, targetColor, replacementColor);
end
end
end
calling this function using
image = floodFill(im,1,1,0,127);
imshow(image);
im is my matrix image of 200 by 200 I want my black color(0) to grey color(127), any help will be thankful
You are probably hitting Matlab's recursion limit. My computer doesn't crash, but generates this error:
Maximum recursion limit of 500 reached. Use set(0,'RecursionLimit',N) to change the limit. Be aware that exceeding your available stack space can crash MATLAB and/or your computer.
The way around this is to rewrite floodFill so it does not use recursion. There are some alternative algorithms on Wikipedia.
Also: aardvarkk's answer makes an important point about Matlab's column-major indexing. You can fix your function by swapping all x and y variables.
I believe there are two things wrong with this:
a) You appear to be indexing the image
matrix in the order (x,y)
. MATLAB matrices are in column order, so you have to (unintuitively) index them in the order (y,x)
. So the line:
image(target_Loc_x,target_Loc_y)
should probably be:
image(target_Loc_y,target_Loc_x)
Same goes for when you set the value in the colored image. Note also that size(image,1)
will give the size in the y
direction, not x
!
b) You're using a recursive function to do a very simple operation. It very quickly hits MATLAB's recursion limit. In a 200x200 image, you'll have a stack of calls 40,000 deep, and MATLAB only allows a recursion limit of 500 by default. Why not try something like this instead:
colored_image = image;
colored_image(colored_image == targetColor) = replacementColor;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With