Counting coins - bwconncomp returns only one object

I'm doing an exercise using the Image Processing Toolbox and the 'coins.png' image built-in in MATLAB.
In the last line of the code before the function, when I call the function bwconncomp, I returns only one object instead of 14.
filtsize = 85;
im1 = imread('coins.png');
[r,c] = size(im1);
im2 = imread('eight.tif');
[r2,c2] = size(im2);
filtsizeh = floor(filtsize/2);
im = zeros(r+r2+filtsize,c+filtsize);
im(filtsizeh+1:filtsizeh+r+r2,filtsizeh+1:filtsizeh+c) = [im1;255-im2(:,1:c)];
[r,c] = size(im);
imagesc(im);colormap(gray);title('test image');axis equal;
msk=[]; msk_dil=[]; msk_dil_erd=[]; centroid=[]; component_size=[];
[msk,thrsh] = OtsuThreshold(im);
figure; imagesc(msk); colormap(gray); title('Otsu'); axis equal;
msk_dil = im<=88;
figure; imagesc(msk_dil); colormap(gray); title('Dilated'); axis equal;
msk_dil_erd = imerode(msk_dil,ones(7,7));
figure; imagesc(msk_dil_erd); colormap(gray); title('Eroded'); axis equal;
comps = bwconncomp(msk_dil_erd);
%%
function [msk,thrsh] = OtsuThreshold(img)
histogram = imhist(img);
thrsh = otsuthresh(histogram);
thrsh = thrsh*255;
msk = img > thrsh;
end
Someone able to help?

 채택된 답변

KALYAN ACHARJYA
KALYAN ACHARJYA 2020년 12월 24일
편집: KALYAN ACHARJYA 2020년 12월 24일
Please note it consider white pixels as objects, hence it shows 1. Have you check the "msk_dil_erd" image. May be you complement the image, check it carefully-
figure; imagesc(~msk_dil_erd); colormap(gray); title('Eroded'); axis equal;
comps = bwconncomp(~msk_dil_erd)
More: This may show a different result, as some coins may still be interconnected., do the image erode with proper structuring element to get disconnected coins (also note on the outer space may consider the 1 object)

추가 답변 (1개)

Image Analyst
Image Analyst 2020년 12월 24일
So it doesn't work because of this line:
im(filtsizeh+1:filtsizeh+r+r2,filtsizeh+1:filtsizeh+c) = [im1;255-im2(:,1:c)];
c is the number of columns in im1, then you're trying to use it to index into im2, which does not have as many columns as im1, and it throws the error.
Index in position 2 exceeds array bounds (must not exceed 308).
Error in test5 (line 17)
im(filtsizeh+1:filtsizeh+r+r2,filtsizeh+1:filtsizeh+c) = [im1;255-im2(:,1:c)];
But I noticed you accepted the answer so I guess you got it figured out. Let us know if that's not the case and I need to fix anything.

댓글 수: 2

Sir, I executed the code, it runs without any error. (Considering the same image name)
Yes, but if they're different sized images like he used, then it throws an error.

댓글을 달려면 로그인하십시오.

질문:

2020년 12월 24일

댓글:

2020년 12월 24일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by