% 步骤1:读取图像并转换为灰度图像
im = imread(‘rice_image.jpg’);
grayIm = rgb2gray(im);
% 步骤2:进行边缘检测
edgeIm = edge(grayIm, ‘Canny’);
% 步骤3:进行锐化
sharpIm = imsharpen(grayIm);
% 步骤4:进行滤波
filteredIm = imgaussfilt(sharpIm, 2);
% 步骤5:进行二值化
threshold = graythresh(filteredIm);
binaryIm = imbinarize(filteredIm, threshold);
% 步骤6:填充小的空洞
filledIm = imfill(binaryIm, ‘holes’);
% 步骤7:进行连通区域分析
stats = regionprops(filledIm, ‘Area’, ‘Centroid’);
% 步骤8:筛选并计数大米粒
minArea = 100; % 设置最小大米粒面积
riceCount = 0;
for i = 1:numel(stats)
area = stats(i).Area;
if area > minArea
riceCount = riceCount + 1;
end
end
% 步骤9:可视化结果
imshow(im);
hold on;
for i = 1:numel(stats)
area = stats(i).Area;
centroid = stats(i).Centroid;
if area > minArea
plot(centroid(1), centroid(2), ‘r+’, ‘MarkerSize’, 10);
end
end
hold off;
% 显示结果
disp([‘大米粒数量:’, num2str(riceCount)]);