Counting coins - bwconncomp returns only one object
Show older comments
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?
Accepted Answer
More Answers (1)
Image Analyst
on 24 Dec 2020
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 Comments
KALYAN ACHARJYA
on 24 Dec 2020
Sir, I executed the code, it runs without any error. (Considering the same image name)
Image Analyst
on 24 Dec 2020
Yes, but if they're different sized images like he used, then it throws an error.
Categories
Find more on Region and Image Properties in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!