前一段时间,有同学给我传了张图像,说能不能定位一下图中的特定区域。
识别特定区域:
一般会用到边缘检测、二值化、形态学操作、区域分析等方法。
clear;
close all;
src=imread('C:\Users\samsung\Desktop\1.jpg') ;%读入的是三通道的灰度图像
src=src(:,:,1);%取1通道
img=src;
bw=img<20;%二值化
bw=~bw;%图像取反
figure,imshow(bw)
se1=ones(5,5);
bw=imerode(bw,se1);%腐蚀
bw=bwareaopen(bw,2000);%去掉小的干扰区域
se2=strel('disk',9);
bw=imopen(bw,se2);%开运算
figure,imshow(bw);
ss=regionprops(bw,'BoundingBox');
box=ss.BoundingBox;
x=box(1);y=box(2);
width=box(3);height=box(4);
hold on;
plot(x:x+width,y,'r');
plot(x:x+width,y+height,'r');
plot(x,y:y+height,'r');
plot(x+width,y:y+height,'r');
src1=src(round(y):round(y)+height,round(x):round(x)+width );%截取图像
figure,imshow(255-src1);
src2=255-src1;
src3=imdilate(src2,strel('square',9) );
figure,imshow(src3);
srcbw=im2bw(src3,graythresh(src3));
srcbw=imclearborder(srcbw);
se3=strel('disk',7);
srcbw=imopen(srcbw,se3);
figure,imshow(srcbw);
ss1=regionprops(srcbw,'Area','BoundingBox');
figure,imshow(srcbw);hold on;
for jj=1:length(ss1)
boxtem=ss1(jj).BoundingBox;
xt=boxtem(1);yt=boxtem(2);
widtht=boxtem(3);heightt=boxtem(4);
plot(xt:xt+widtht,yt,'g');
plot(xt:xt+widtht,yt+heightt,'g');
plot(xt,yt:yt+heightt,'g');
plot(xt+widtht,yt:yt+heightt,'g');
end
area=[ss1.Area];
boundingbox=[ss1.BoundingBox];
boundingbox=reshape(boundingbox,4,[]);
boundingbox=boundingbox.';
[~,maxind]=max(area);
box1=boundingbox(maxind,:);%选择最大的矩形框
box1=round(box1);
box1(1)=box1(1)+round(x)-1;
box1(2)=box1(2)+round(y)-1;
figure,imshow(src);
hold on;
x1=box1(1);y1=box1(2);
width1=box1(3);height1=box1(4);
plot(x1:x1+width1,y1,'r');%标注
plot(x1:x1+width1,y1+height1,'r');
plot(x1,y1:y1+height1,'r');
plot(x1+width1,y1:y1+height1,'r');
result=cat(3,src,src,src);
result(y1,x1:x1+width1,1)=255;%标注矩形框
result(y1,x1:x1+width1,2)=255;
result(y1,x1:x1+width1,3)=0;
result(y1+height1,x1:x1+width1,1)=255;
result(y1+height1,x1:x1+width1,2)=255;
result(y1+height1,x1:x1+width1,3)=0;
result(y1:y1+height1,x1,1)=255;
result(y1:y1+height1,x1,2)=255;
result(y1:y1+height1,x1,3)=0;
result(y1:y1+height1,x1+width1,1)=255;
result(y1:y1+height1,x1+width1,2)=255;
result(y1:y1+height1,x1+width1,3)=0;
imwrite(result,'C:\Users\samsung\Desktop\result.png');