基于matlab的数米粒算法(注释多)[辅导]
基于matlab的数米粒算法(注释多)
clear;
close all;
I = imread('rice.png');
[width,height] = size(I);
J = edge(I,'canny');
%figure,imshow(J);
K = imfill(J,'holes');
%figure,imshow(K);
SE = strel('disk',3);%用于膨胀腐蚀及开闭运算等操作的结构元素对象
%对图像实现开运算,开运算一般能平滑图像的轮廓,消弱狭窄的部分,去掉细的突出。
L = imopen(K,SE);
figure,imshow(L);
L = uint8(L);%把L由logic类型转化为uint8类型
for i = 1:height
for j = 1:width
if L(i,j) == 1
L(i,j) = 255;%把白色像素点像素值赋值为255
end
end
end
MAXSIZE = 999999;
Q = zeros(MAXSIZE,2);%用数组模拟队列,存储像素点坐标
front = 1;%指明队头的位置
rear = 1;%指明队尾的下一个位置;front=rear表示队空
flag = 0;%米粒的标号
for i = 1:height
for j = 1:width
if L(i,j) == 255%白色像素点入队列
if front == rear%队列空,找到新米粒,米粒标
号加一
flag = flag+1;
end
L(i,j) = flag;%给白色像素赋值为米粒的标号
Q(rear,1) = i;
Q(rear,2) = j;
rear = rear+1;%队尾后移
while front ~= rear
%队头出队
temp_i = Q(front,1);
temp_j = Q(front,2);
front = front + 1;
%把队头位置像素点8连通邻域中未作标记的
白色像素点入队,并加上米粒标号
%左上角的像素点
if L(temp_i - 1,temp_j - 1) == 255
L(temp_i - 1,temp_j - 1) = flag;
Q(rear,1) = temp_i - 1;
Q(rear,2) = temp_j - 1;
rear = rear + 1;
end
%正上方的像素点
if L(temp_i - 1,temp_j) == 255
L(temp_i - 1,temp_j) = flag;
Q(rear,1) = temp_i - 1;
Q(rear,2) = temp_j;
rear = rear + 1;
end
%右上方的像素点
if L(temp_i - 1,temp_j + 1) == 255
L(temp_i - 1,temp_j + 1) = flag;
Q(rear,1) = temp_i - 1;
Q(rear,2) = temp_j + 1;
rear = rear + 1;
end
%正左方的像素点
if L(temp_i,temp_j - 1) == 255
L(temp_i,temp_j - 1) = flag;
Q(rear,1) = temp_i;
Q(rear,2) = temp_j - 1;
rear = rear + 1;
end
%正右方的像素点
if L(temp_i,temp_j + 1) == 255
L(temp_i,temp_j + 1) = flag;
Q(rear,1) = temp_i;
Q(rear,2) = temp_j + 1;
rear = rear + 1;
end
%左下方的像素点
if L(temp_i + 1,temp_j - 1) == 255
L(temp_i + 1,temp_j - 1) = flag;
Q(rear,1) = temp_i + 1;
Q(rear,2) = temp_j - 1;
rear = rear + 1;
end
%正下方的像素点
if L(temp_i + 1,temp_j) == 255
L(temp_i + 1,temp_j) = flag;
Q(rear,1) = temp_i + 1;
Q(rear,2) = temp_j;
rear = rear + 1;
end
%右下方的像素点
if L(temp_i + 1,temp_j + 1) == 255
L(temp_i + 1,temp_j + 1) = flag;
Q(rear,1) = temp_i + 1;
Q(rear,2) = temp_j + 1;
rear = rear + 1;
end
end
end
end
end
figure,imshow(L);
RiceNumber = flag;%记录米粒的总个数
disp('米粒的总个数:')
RiceNumber
RiceArea = zeros(1,RiceNumber);%记录各米粒的大小
for i = 1:height
for j = 1:width
if L(i,j) ~= 0
RiceArea(L(i,j)) = RiceArea(L(i,j)) + 1;
end
end
end
disp('各米粒的大小(按照从上往下,从左往右的顺序):')
RiceArea
本文档为【基于matlab的数米粒算法(注释多)[辅导]】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑,
图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
该文档来自用户分享,如有侵权行为请发邮件ishare@vip.sina.com联系网站客服,我们会及时删除。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。
本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。
网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。