Professional Documents
Culture Documents
clear all
clc
% Step 1 -- read in image and display
I=imread('rice.png');
imshow(I);
% Step 2 -- estimate background using morphological opening operation
% Morphological opening is an erosion followed by a dilation,
% using the same structuring element for both operations.
% The opening operation has the effect of removing objects
% that cannot completely contain the structuring element.
% strel('disk',15): disk-shaped structuring element with radius 15
% structuring element must be bigger than a single grain of rice
background=imopen(I,strel('disk',15));
% Step 3 -- view background approximation as a surface; first convert background
to double and use surf command to display every 8th pixel in each direction
figure; surf(double(background(1:8:end,1:8:end)));
% limit range to that of uint8 data to match input image (for subtraction)
zlim([0 255]);
% reverse y-axis of display to provide better view of surface
set(gca,'ydir','reverse');
% [0 0] is origin of image; high part of curve indicates highest pixel values of
background; this occurs at middle rows of image
% Step 4 -- subtract background image from original image
I2=I - background;
figure; imshow(I2);
% Step 5 -- increase image contrast -- background is too dark, using imadjust
I2=rgb2gray(I2);
I3=imadjust(I2);
figure; imshow(I3);
% Step 6 -- threshold image to create binary version of image in order to count
the number of grains of rice
% graythresh automatically computes threshold for conversion from gray
% scale to binary image
level=graythresh(I3);
% im2bw converts grayscale image to binary image using thresholding
bw=im2bw(I3,level);
% bwareaopen removes background noise
bw=bwareaopen(bw,50);
figure; imshow(bw);
% Step 7 -- identify objects in image
% bwconncomp finds all connected components (objects) in binary image
cc=bwconncomp(bw,4);
disp(['Jumlah beras ' num2str(cc.NumObjects)]);
% Step 8 -- examine a single detected object; each distinct object is labeled show
50th connected component
grain=false(size(bw));
grain(cc.PixelIdxList{50})=true;
figure; imshow(grain);
% Step 9 -- view all objects
% create a label matrix and display it as a pseudo-color indexed image