Could you please advice how can I implement morphological closing by reconstruction in Matlab?
As i know imreconstruct command can be used to implement opening by reconstruction (below my code for Opening by reconstruction).
img = rgb2gray(imread("input.jpg"));
img = imcomplement(img);
se=strel("square", 40);
marker= imerode(img,se);
mask=img;
opn_recon=imreconstruct(marker,mask);
Below is the code I wrote for Closing Reconstruction:
%Closing by reconstruction
img = rgb2gray(imread("input.jpg"));
img = imcomplement(img);
se=strel("square", 40);
marker= imdilate(img,se);
tmp=0;
while 1
marker_loop = marker;
geodesic=max(marker_loop,img);
recon=imerode(geodesic,se);
if isequal(recon,tmp)==1
break
end
tmp = recon;
marker = imdilate(marker_loop,se);
end
But code does not work properly. Could you please advice whats my mistake, so i can fix it?
imreconstruct
applies an inf-reconstruction, which can be interpreted as the repeated dilation conditioned by a second image (mask
). Because it's a dilation, it can be applied after a structural erosion to form an opening (opening by reconstruction).
To form a closing by reconstruction, we need to apply a dilation followed by a sup-reconstruction. The sup-reconstruction is the dual of the inf-reconstruction, and can therefore be interpreted as the repeated erosion conditioned by a second image. Being the dual, we can implement the sup-reconstruction in terms of the ind-reconstruction by inverting the image, applying the operation, and then inverting the result:
out = imcomplement(imreconstruct(imcomplement(marker), imcomplement(mask)));
Thus, the closing by reconstruction is:
img = imread('cameraman.tif');
se = strel('square', 40);
marker = imdilate(img,se);
mask = img;
cls_recon = imcomplement(imreconstruct(imcomplement(marker), imcomplement(mask)));