demo4

Contents

clear
g = rgb2gray(imread('cropped_target.jpg'));
imshow(g);

histogram

imhist(g);

graythresh and im2bw

level = graythresh(I) computes a global threshold (level) that can be used to convert an intensity image to a binary image with im2bw. level is a normalized intensity value that lies in the range [0, 1].

%The graythresh function uses Otsu's method, which chooses the threshold
% to minimize the intraclass variance of the black and white pixels.

level = graythresh(g);
fprintf('threshold %g\n',level);
threshold 0.521569

convert to bw image

BW = im2bw(g,level);
imshow(BW);

bwconncomp

CC = bwconncomp(BW) returns the connected components CC found in BW. The binary image BW can have any dimension. CC is a structure with four fields.

CC = bwconncomp(~BW);
disp(CC)
    Connectivity: 8
       ImageSize: [474 717]
      NumObjects: 21
    PixelIdxList: {1x21 cell}

stats = regionprops(CC)


area = [stats.Area]
stats = 

21x1 struct array with fields:

    Area
    Centroid
    BoundingBox


area =

  Columns 1 through 6

        6499        1666         429         112        1769        3199

  Columns 7 through 12

        3157         592          71          84       67247        1379

  Columns 13 through 18

        1399        1412        1401        1398        1400        1404

  Columns 19 through 21

        1422        1393        1374

labelmatrix

L = labelmatrix(CC) creates a label matrix from the connected components structure CC returned by bwconncomp. The size of L is CC.ImageSize. The elements of L are integer values greater than or equal to 0.

L = labelmatrix(CC);

label2rgb

RGB = label2rgb(L) converts a label matrix into an RGB color image for the purpose of visualizing the labeled regions.

RGB = label2rgb(L);
imshow(RGB);