matlab 图像工具箱 Identifying Round Objects

来源:互联网 发布:淘宝怎么进入对方社区 编辑:程序博客网 时间:2024/05/22 17:33

http://www.mathworks.cn/cn/help/images/examples/identifying-round-objects.html

Identifying Round Objects

第一步:读入图像

RGB = imread('pillsetc.png');

imshow(RGB);


第二步:图像阈值求解

I = rgb2gray(RGB);       % 图像转为黑白图像

threshold = graythresh(I); % 求解图像的阈值

bw = im2bw(I,threshold);  % 转为2值图像

imshow(bw);

第三步:去噪声

bw = bwareaopen(bw,30); % 去掉少于30像素的对象

se = strel(‘disk’,2);

bw = imclose(bw,se);    % 用se填补对象中的gap

bw = imfill(bw,’holes’);  % 填满对象中的空洞

imshow(bw);


第四步:查找边界

[B,L] = bwboundaries(bw,'noholes');    %找到所有的边界

% 显示label结果 并且画出边界

imshow(label2rgb(L, @jet, [.5 .5 .5]))

hold on

for k = 1:length(B)

  boundary = B{k};

  plot(boundary(:,2), boundary(:,1), 'w', 'LineWidth', 2)

end


第五步:监测对象是否为圆形

估计每个对象的面积和周长,对象为圆形的概率为:    metric = 4*pi*area/perimeter^2,这里取0.94为区分圆形的阈值。

stats = regionprops(L,'Area','Centroid');

threshold = 0.94;

% 对每个周长操作

for k = 1:length(B)

  boundary = B{k};

    delta_sq = diff(boundary).^2;   % 简单计算对象周长

  perimeter = sum(sqrt(sum(delta_sq,2)));

  area = stats(k).Area;                % 求解面积

  metric = 4*pi*area/perimeter^2;  % 计算为圆形的概率

  metric_string = sprintf('%2.2f',metric);   % 显示结果

  % 将大于阈值的对象标记上黑色的圆圈

  if metric > threshold

    centroid = stats(k).Centroid;

    plot(centroid(1),centroid(2),'ko');

  end

  text(boundary(1,2)-35,boundary(1,1)+13,metric_string,'Color','y','FontSize',14,'FontWeight','bold');

end

title(['Metrics closer to 1 indicate that ','the object is approximately round']);

 

 

原创粉丝点击