MATLAB: Counting coins on a greyscale image – using morphological and/or f transforms

morphological

I am trying to convert the image into a binary image, using the function form: function C = coins2bw(A) where A is a 2D grayscale image variable and C is a 2D binary image variable. The output image C should show the coins as filled in round disks with no other arifacts or stray foreground pixels(background in black while the coins are white). Using only morphological or fourier transforms.

Best Answer

I = imread('image.png');
I = imadjust(I);
[centers,radii] = imfindcircles(I,[15 75],'ObjectPolarity','dark','Sensitivity',0.85);
BW = false(size(I,1),size(I,2));
[Xgrid,Ygrid] = meshgrid(1:size(BW,2),1:size(BW,1));
for n = 1:size(centers,1)
BW = BW | (hypot(Xgrid-centers(n,1),Ygrid-centers(n,2)) <= radii(n));
end
maskedImage = I;
maskedImage(~BW) = 0;
imshow(BW)
fprintf('Numbers of coins: %d\n',size(centers,1))