首页 > 代码库 > 分割RGB中物体并计算数目

分割RGB中物体并计算数目

I=imread(im_path);
         axes(handles.axes1);
         imshow(I),
%          title('原始图像');
         
         %计算每个像素点的真实长度
        [x,y]=ginput(2);
        length=str2double(get(handles.edit5,'string'));
        length_pp=length/(sqrt(((x(1)-x(2))^2+(y(1)-y(2))^2)));
        
        %图像变换
        [row,col]=size(I);
        I2=rgb2gray(I);
        clear I;
        %图像增强,提高图像对比度
        J=imadjust(I2);
        BW=im2bw(J,0.5);%0.20
        figure,imshow(I2),title('灰度图像');
        figure,imshow(BW),title('二值图像');
        figure,imshow(J),title('对比度增强');

        % 图像运算,消除二值图像的的噪声和中空的区域
        se = ones(2);
        bw_erode=imerode(BW,se);
        bw_delate=imdilate(bw_erode,se);

        %清除临时变量,减少内存使用
        clear BW;
        clear I2;
        clear bw_erode;
        L1=bwlabel(bw_delate,8);
        clear L1;
        %figure, imshow(bw_erode);
        % 
        % % %
        % %填充了已有的检测的连续形状边界L
        bw_fill = imfill(~bw_delate,'holes');
        clear bw_delate;
        %B = bwmorph(B,'remove');
        figure,imshow(bw_fill),title('填充后的图像');
        % % 
        %去除面积较小的的噪声区域
        cc = bwconncomp(bw_fill);
        stats = regionprops(cc, 'Area');
        clear bw_fill;
        %去掉标签范围<100*100 的区域
        idx = find([stats.Area] >20000);%
        bw_ismember = ismember(labelmatrix(cc), idx);
        clear idx;
        [L,num] = bwlabel(bw_ismember,8);
        figure, imshow(~bw_ismember),title('分割后的图像');
        %标记已经分割好的图像,
        cc1 = bwconncomp(bw_ismember);
        clear bw_ismember;
        clear L;

        %提取每个label 区域的最长轴,即为枣的长度
        stats1=regionprops(cc1,'MajorAxisLength');
        %定义枣长度矩阵,枣品相矩阵
        result_len=double(ones(1,num));
        result_quli=cell(1,num);

        %计算每个枣的长度并显示,通过枣的长度判断其的品相
       
        td=0;yd=0;ed=0;
        s='';
        for i=1:num
            %计算每个枣的长度并以cm表示
            result_len(i)=(stats1(i).MajorAxisLength)*length_pp;
            if(result_len(i)>tedeng)
                result_quli(i)={'特等'};
                td=td+1;
            elseif(result_len(i)>=erdeng&&result_len(i)<=tedeng)
                result_quli(i)={'一等'};
                yd=yd+1;
            elseif(result_len(i)<erdeng)
                result_quli(i)={'二等'};
                ed=ed+1;
            end
            fprintf('第%d个枣的长度:%fcm,等级:%s\n',i,result_len(i),result_quli{i});
            if i<10
                si=['第','0',num2str(i),'个枣长度:',num2str(result_len(i)),',等级:', result_quli{i},';     '];
            else
                si=['第',num2str(i),'个枣长度:',num2str(result_len(i)),',等级:', result_quli{i},';     '];
            end
            s=[s si];
        end
        
        s=[s '一共:',num2str(num),'个枣;  ','其中特等:',num2str(td),'个;  ','一等:',num2str(yd),'个;  ','二等:',num2str(ed),'个;  '];
        set(handles.text2,'string',s);