% Use the system's self-contained rice grain image rice.png. After preprocessing the image, calculate the area of each rice grain in the image and the number of all rice grains, clear all clcclose Alli = imread('rice.png '); EDI = edge (I, 'shecol'); FHI = imfill (EDI, 'holle'); Se = strel ('disk', 4); OPI = imopen (FHI, SE); % OPI = ones (100,100 ); % OPI = im2bw (OPI); figure, imshow (OPI); [row Col] = size (OPI); Count = 0; ricearr = zeros (row * Col, 1 ); visited = zeros (SIZE (OPI); % call the compute connection Domain Function to calculate the number of grains and the size of the grains for I = 1: Row for j = 1: col if OPI (I, j) & visited (I, j) = 0 count = count + 1; Pt = [I; j]; [C, domain] = finddomain (OPI, pt); ricearr (count) = C; for M = 1: C visited (domain (1, m), domain (2, m )) = 1; end endenddisp ('number of rice grains is '); disp (count); disp ('area of each rice grains is'); disp (ricearr (1: count ));
% Calculate the function [C, domain] = finddomain (input, pt) of the connected domain of a vertex. % input an image and a vertex in the image, the number of pixels in the connection domain and connection domain where the point is located in the image is obtained and output. % Enter a white point, enter the white points in the fields around the point into the queue, and continue searching for the points in the queue [row Col] = size (input ); iplus = [-1-1 0 1 1 1 0-1]; jplus = [0 1 1 1 0-1-1]; visited = zeros (SIZE (input); stack = zeros (2, row * col); domain = zeros (2, row * col); stack (:, 1) = pt; domain (:, 1) = pt; visited (Pt (1), Pt (2) = 1; Count = 1; EOS = 1; SOS = 1; while SOS ~ = EOS + 1 m = stack (1, SOS); n = stack (2, SOS); for I = 1: 8% look for white points in the neighborhood. If it is a white point in the queue, and indicate that you have accessed it. If M + iplus (I)> 0 & M + iplus (I) <= row & N + jplus (I)> 0 & N + jplus (I) <= Col if input (m + iplus (I), N + jplus (I) = 1 & visited (m + iplus (I ), N + jplus (I) = 0 EOS = EOS + 1; stack (:, Eos) = [M + iplus (I); N + jplus (I)]; visited (m + iplus (I), N + jplus (I) = 1; Count = count + 1; domain (:, count) = [M + iplus (I ); N + jplus (I)]; end SOS = SOS + 1; % when all vertices in the neighborhood are accessed, This vertex is in the queue and the corresponding pointer is incremented by 1. ENDC = count;