matlab实验 识别木桩图中每个木桩的大小 腐蚀 连通域

上视觉物联网课程的一个小实验,记录一下心得。

效果应如下图所示,至少需要掌握的知识有:二值化,中值滤波,腐蚀,连通域的标记和操作。核心操作是利用bwlabel函数标记每个连通域(即每个木桩),regionprops函数计算连通域面积。

 

1. 图像前置处理

主要思路是将原始图像先二值化,利用中值滤波过滤噪点,再利用腐蚀(我这里设的是3次)去除每个木桩有连结的部分。参数都可以自行调整,要确保腐蚀过后有些小的木桩不会消失。

% 读取图像并转化为二值图像
I = imread('Fig0941.tif');
% 设置阈值
threshold = graythresh(I);
% 转化为二值图像
bw = imbinarize(I,threshold);
% 中值滤波
bw = medfilt2(bw, [3 3]);
% 腐蚀
for k = 1:3
    se = strel('disk',3);
    bw = imerode(bw, se);
end

 

 2. 连通域的标记和操作

bwlabel会返回两个参数,第一个参数l是矩阵,会将同一个连通域下的点设为同一个值;第二个参数num是连通域个数。

regionprops会返回很多信息,可以在传入参数的时候选择是‘Area’还是‘Centroid’,Area是返回一个48x1的面积矩阵,Centroid返回的是中心坐标。

% 连通域标记
[l, num] = bwlabel(bw, 8)
% 获取面积,坐标
area = regionprops(l,'Area');
centroid = regionprops(l,'Centroid');
figure(1)
imshow(bw);
figure(2)
imshow(I);

3. 给原图添加文字

要注意是area(i).Area(1)。

阈值设为1000,大于它的就标记为big,小于它的标记为small。

big_num = 0;
small_num = 0;
% 添加文字
for i=1:num
    if(area(i).Area(1)>1000)
        text(centroid(i,1).Centroid(1,1),centroid(i,1).Centroid(1,2), 'big','Color', 'b', 'Fontsize', 8) 
        big_num = big_num+1;
    else
        text(centroid(i,1).Centroid(1,1),centroid(i,1).Centroid(1,2), 'small','Color', 'r', 'Fontsize', 8) 
        small_num = small_num+1;
    end
end 
text(500, 440,['total: ', num2str(num)],'Color', 'r', 'Fontsize', 14) 
text(500, 470,['big: ', num2str(big_num)],'Color', 'r', 'Fontsize', 14) 
text(500, 500,['small: ', num2str(small_num)],'Color', 'r', 'Fontsize', 14) 

4. 完整代码

% 读取图像并转化为二值图像
I = imread('Fig0941.tif');
% 设置阈值
threshold = graythresh(I);
% 转化为二值图像
bw = imbinarize(I,threshold);
% 中值滤波
bw = medfilt2(bw, [3 3]);
% 腐蚀
for k = 1:3
    se = strel('disk',3);
    bw = imerode(bw, se);
end

% 连通域标记
[l, num] = bwlabel(bw, 8)
% 获取面积,坐标
area = regionprops(l,'Area');
centroid = regionprops(l,'Centroid');
figure(1)
imshow(bw);
figure(2)
imshow(I);

big_num = 0;
small_num = 0;
% 添加文字
for i=1:num
    if(area(i).Area(1)>1000)
        text(centroid(i,1).Centroid(1,1),centroid(i,1).Centroid(1,2), 'big','Color', 'b', 'Fontsize', 8) 
        big_num = big_num+1;
    else
        text(centroid(i,1).Centroid(1,1),centroid(i,1).Centroid(1,2), 'small','Color', 'r', 'Fontsize', 8) 
        small_num = small_num+1;
    end
end 
text(500, 440,['total: ', num2str(num)],'Color', 'r', 'Fontsize', 14) 
text(500, 470,['big: ', num2str(big_num)],'Color', 'r', 'Fontsize', 14) 
text(500, 500,['small: ', num2str(small_num)],'Color', 'r', 'Fontsize', 14) 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值