形态学初步定位键盘按键(demo)

178 阅读1分钟

  接juejin.cn/editor/draf… 中项目的代码部分在这里单独介绍。

Step1: 显示选择的图像 (图1)

global RGB;
[filename, pathname] = uigetfile({'*.bmp';'*.jpg';'*.gif'},'choose image pathway');
str = [pathname filename];
if (filename~=0)                          
RGB=imread(str);          
axes(handles.axes1)
imshow(RGB)
else    %empty file
   clear;
end

Step2: 对选择图像二值化(图2)

global RGB;
global bw;
bw=imbinarize(RGB,'global'); %二值化
axes(handles.axes2)
imshow(bw)

Step3: 去除噪点并取反(图3)

global bw;
global bwf_open;
bw_open=bwareaopen(bw,70000);   %去掉连通像素小于90000的区域;去除噪点
bwf_open  = ~ bw_open ;% 图像取反
axes(handles.axes3)
imshow(bwf_open)

Step4: 膨胀运算 (图4)

global bwf_open;
se = strel('disk',11);        
img_src = imerode(bwf_open,se);
axes(handles.axes4)
imshow(img_src)

Step5: 计算边界定位(图5)

global img_src;
global RGB;
[B,L] = bwboundaries(img_src);
axes(handles.axes5)
imshow(RGB);
hold on;
for k = 1:length(B)
    boundary = B{k};
    x = boundary(:,2); % 黑色区域的x轴坐标
    y = boundary(:,1); % 黑色区域的y轴坐标
    if y < 450         % 防止把边框圈住了 
        plot(x,y,'g','LineWidth',2);
    end
end