Connected-Component Images in Matlab

» rgb = imread('coins3.tif');
» gray = rgb2gray(rgb);
» imhist(gray);

Use the histogram to choose a threshold that isolates the objects of interest. The image bw is a binary image.

» bw = gray>40;
» imshow(bw);
» imwrite(bw,'bw.jpg');

Use the Matlab function bwlabel to label the objects in the binary image. Display the results as an indexed image (with a pseudo-color colormap).

» [L,num] = bwlabel(bw);
» num

num =  11

» M = im2uint8(L/num);
» imwrite(M,jet,'label.jpg');

There are 11 objects, some of which are just stray pixels. Find the area of each object using the Matlab function bwarea.

» for i=1:num
area(i) = bwarea(L==i);
end
» area

area =

  1.0e+003 *

  Columns 1 through 7 

    0.0020    4.3670    0.0010    0.0010    7.0810    7.0396    7.0464

  Columns 8 through 11 

    0.0010    0.0010    4.2916    0.0010

Find those elements whose area is large. These are the coins.

» x = find(area>5)

x =

     2     5     6     7    10

» area(x)'

ans =

  1.0e+003 *

    4.3670
    7.0810
    7.0396
    7.0464
    4.2916

Select those objects representing the smaller coins (pennies). Mask these objects in the original grayscale image and display the result.

» M = (L==2)|(L==10);
» imshow(M)
» penny = im2double(gray).*M;
» imshow(penny)
» imwrite(penny,'penny.jpg');


Maintained by John Loomis, last updated 8 Feb 2000