MATLAB中的连通分量分析

时间:2015-11-04 08:31:45

标签: matlab connected-components

我想在灰度图像上应用连通分量分析,同时考虑灰度级大于阈值的像素。那么,我想删除那些长度小于阈值的连通组件。请帮我?我在MATLAB中编写了以下代码,它有效吗? 提前谢谢你。

%im = input image;
% alpha1 = 0.0001;
% alpha2 = 0.0001;
% [row col] = size(im);
% 
% 
% thr1 = mean(mean(im))-alpha1*std(std(im));
% BW = zeros(size(im));
% 
% for rr = 1:row
%     for cc = 1:col
%         if im(rr,cc)>thr2
%             BW(rr,cc) = 1;
%         else
%             BW(rr,cc) = 0;
%         end
%     end
% end
% 
% CC = bwconncomp(BW);
% area_in_pixels = cellfun(@length,CC.PixelIdxList);
% thr2 = mean(area_in_pixels)-alpha2*std(area_in_pixels);
% idx = find(area_in_pixels <= thr3);
% for  kk = 1:length(idx)
% aaa = idx(kk);
% BW(CC.PixelIdxList{aaa})=0;
% end

1 个答案:

答案 0 :(得分:0)

您可以尝试使用regionprops来提取图像中的所有对象。使用下面的代码,您可以获得小于阈值的所有对象的位置,您可以操作或执行之后需要执行的操作... 相比之下,您可以浏览不同的对象并提取灰度级,如果低于阈值则操纵它们。

    % Threshold for the size in pixels that you want
    threshold = 100; 

    % read your image    
    rawimage = imread('yourimage.jpg');

    % create a 2D field by summing 
    im = sum(rawimage,3);

    % label all objects that have 8 neighbours    
    IMAGE_labeled = bwlabel(im,8); 

    % get the properties of all elements
    shapedata=regionprops (IMAGE_labeled,'all'); 

    % get those elements that are smaller in size (area) than the threshold
    index = find(cell2mat({shapedata(:).Area})<=threshold); 

    % make a contourplot of im
    figure
    contourf(im)
    hold on

    % creation of colormap with the size of all identified objects below the thres
    mycolormap = jet(size(index,2));

    % loop over all small objects, extraction of their position in the original file, plotting circles with different colors at the position of each small object

   imap = 1;
   mean_of_red = zeros(length(index),1);
   for i = index
      plot (shapedata(i).PixelList(:,1),shapedata(i).PixelList(:,2),'o','MarkerFaceColor',mycolormap(imap,:))
      mean_of_red(i) = mean(mean(im(shapedata(i).PixelList(:,1),shapedata(i).PixelList(:,1),1)));
      imap=imap+1; 
   end