to segment the coins from the background in the image and find the centroid of each distinct segmented coin

% Define the filter size we will use in step 2:
filtsize = 85;
% Creating test image 'im' by splicing together two built in images.
% Also zero-padding (adding zeros around the border) with half the
% filter size (filtsize) we will use so that the filter could be
% centered on any actual image pixel, including those near the border.
% 'coins.png' contains bright nickels and dimes on a dark background
% 'eight.tif' contains dark quarters on a bright background, so we invert it
% to match 'coins.png'
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;
% Initializing assessed/displayed variables as empty so that code is executable
msk=[]; msk_dil=[]; msk_dil_erd=[]; centroid=[]; component_size=[];
%%%%% 1. Localize the centroid of each coin
% Otsu threshold
figure; imagesc(msk); colormap(gray); title('Otsu'); axis equal;
% Dilate
figure; imagesc(msk_dil); colormap(gray); title('Dilated'); axis equal;
% Erode
figure; imagesc(msk_dil_erd); colormap(gray); title('Eroded'); axis equal;
% Connected components to get centroids of coins:
centroid
centroid = []
component_size
component_size = []
%%%%%%%%%%%%%%%%%%%% Helper Functions %%%%%%%%%%%%%%%%%%%%%

Answers (2)

You need to use regionprops
It does exactly what you want. It's a generic, general purpose demo of how to threshold an image to find blobs (using the coins image), and then measure things about the blobs, and extract certain blobs based on their areas or diameters.
It looks like a homework question that gave you some starter code and you're supposed to fill in the commands after the comments, like for example
% Otsu threshold
h = histogram(im)
thr = otsuthresh(h.Values) % Won't work unless you crop off the black surround.
msk = imbinarize(im, thr);
See if you can get the other things it wants you to do.

Asked:

on 1 Mar 2026

Answered:

on 3 Mar 2026

Community Treasure Hunt

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

Start Hunting!