matlab 求图像的连通区域的圆度并可视化

代码

%% 圆度的计算
% 圆形需要是白色的,背景是黑色的,可以根据需要确定是否对图像进行反向
clc
clear;close all;  
%
%读取源图像  
I = imread('1.bmp');  
% figure;imshow(I);  
%  
%灰度化、取反 
h = I;
if ndims(h) == 3
    h = rgb2gray(I);  
end
% figure;imshow(h);%灰度图像  
% h = imcomplement(h);%取反  
% figure;imshow(h);  
%  
%中值滤波、二值化  
h = medfilt2(h,[4,4]);  
bw = im2bw(h,graythresh(h));  
%  
%消除噪点  
se = strel('disk',2);  
bw = imclose(bw,se);  
% figure;imshow(bw);  
%  
%填补闭合图形,填充色为白色  
bw  = imfill(bw,'holes');  
%  
%边界寻找  
[B,L] = bwboundaries(bw,'noholes');  
% 为每个闭合图形设置颜色显示  
figure;
imshow(label2rgb(L, @jet, [1 1 1]))  
hold on  
for k = 1:length(B)  
  boundary = B{k};  
  plot(boundary(:,2), boundary(:,1), 'b', 'LineWidth', 2)  
end  
%  
%计算面积  
roundness = zeros(size(B,1), 3); %圆度的统计值,将图形中每个分离的连通区域的周长、面积和圆度值记录下来
stats = regionprops(L,'Area','Centroid');
threshold = 0.94;% 循环处理每个边界,length(B)是闭合图形的个数,即检测到的陶粒对象个数  
for k = 1:length(B)  % 获取边界坐标'  
    boundary = B{k};  % 计算周长  
    delta_sq = diff(boundary).^2;  
    perimeter = sum(sqrt(sum(delta_sq,2)));  % 对标记为K的对象获取面积  
    area = stats(k).Area;  % 圆度计算公式4*PI*A/P^2  
    metric = 4*pi*area/perimeter^2;  % 结果显示  
    roundness(k,:) = [perimeter, area, metric ];
    metric_string = sprintf('%2.2f',metric);  % 用一个黑色小圆圈标记圆度大于threshold = 0.94 的对象
    if metric > threshold  
        centroid = stats(k).Centroid;  
%         plot(640-centroid(2), 640-centroid(1),'wo');  
        plot(centroid(1), centroid(2),'ko');  
        text(centroid(1), centroid(2),metric_string,'Color','r',...  
                            'FontSize',14,'FontWeight','bold');
    end  
end
title('圆度识别结果,越圆越接近1,');
%% 以下两种方法均可以提取出连通区域的面积
% method 1
a = struct2cell( stats );
b = a(1,:);
c = cell2mat( b );
figure,plot(c)
% method 2
% d = struct2array( stats );
% e = d(1:3:end);
% figure,plot(e)

图片

原图

原图

处理后的图片

处理后的图片

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

littletomatodonkey

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值