問題描述:
有一張這樣的圖片,如何提取里面的紅色圈圈坐標,并且連接這些坐標形成兩個封閉的環路?
程序展示
影像匯入
oriPic=imread('test1.png');
subplot(2,2,1)
imshow(oriPic)
依據RGB值影像二值化
原理就是圖中顏色種類比較少,只有紅黑白,而紅色和白色都是R通道數值較大,因此我們可以利用這一點進行影像分割
% 洗掉紅色外的部分并構造二值圖
grayPic=rgb2gray(oriPic);
grayPic(oriPic(:,:,1)<250)=255;
grayPic(grayPic<250)=0;
%subplot(2,2,2)
figure
imshow(grayPic)

影像腐蝕
對于白色來說是腐蝕,對于黑色來說是膨脹,這一步是為了讓那些有缺口的小圓圈將缺口補起來
% 影像膨脹,使未連接邊緣連接
SE=[0 1 0;1 1 1;0 1 0];
bwPic=imerode(grayPic,SE);
figure
imshow(bwPic)

影像邊緣清理
就是把和邊緣連接的不被黑色包圍的區域變成黑色:
% 邊緣清理:保留圓圈聯通區域
bwPic=imclearborder(bwPic);
%subplot(2,2,3)
figure
imshow(bwPic)

聯通區域查找與坐標均值計算
現在每一個白點都是一個坐標區域,我們檢測所有聯通區域并計算各個區域的重心即可:
% 獲取每一個聯通區域
LPic=bwlabel(bwPic);
labelNum=max(max(LPic));
% 計算每一個聯通區域 坐標均值
pointSet=zeros(labelNum,2);
for i=1:labelNum
[X,Y]=find(LPic==i);
Xmean=mean(X);
Ymean=mean(Y);
pointSet(i,:)=[Xmean,Ymean];
end
% 畫個圖展示一下
%subplot(2,2,4)
figure
imshow(bwPic)
hold on
scatter(pointSet(:,2),pointSet(:,1),'r','LineWidth',1)
可以看出定位結果還是非常準確的:

圈查找
就以一個點開始不斷找最近的點唄,沒啥好說的:
n=1;
while ~isempty(pointSet)
circleSetInd=1;
for j=1:length(pointSet)
disSet=sqrt(sum((pointSet-pointSet(circleSetInd(end),:)).^2,2));
[~,ind]=sort(disSet);
ind=ind(1:5);
[~,~,t_ind]=intersect(circleSetInd,ind);
ind(t_ind)=[];
if ~isempty(ind)
circleSetInd=[circleSetInd;ind(1)];
else
circleSet{n}=pointSet(circleSetInd,:);
pointSet(circleSetInd,:)=[];
n=n+1;
break
end
end
end
figure
imshow(oriPic)
hold on
for i=1:n-1
plot(circleSet{i}(:,2),circleSet{i}(:,1),'LineWidth',2)
end
這效果就很美滋滋:

完整代碼
function redPnt
oriPic=imread('test1.png');
%subplot(2,2,1)
figure
imshow(oriPic)
% 洗掉紅色外的部分并構造二值圖
grayPic=rgb2gray(oriPic);
grayPic(oriPic(:,:,1)<250)=255;
grayPic(grayPic<250)=0;
%subplot(2,2,2)
figure
imshow(grayPic)
% 影像膨脹,使未連接邊緣連接
SE=[0 1 0;1 1 1;0 1 0];
bwPic=imerode(grayPic,SE);
figure
imshow(bwPic)
% 邊緣清理:保留圓圈聯通區域
bwPic=imclearborder(bwPic);
%subplot(2,2,3)
figure
imshow(bwPic)
% 獲取每一個聯通區域
LPic=bwlabel(bwPic);
labelNum=max(max(LPic));
% 計算每一個聯通區域 坐標均值
pointSet=zeros(labelNum,2);
for i=1:labelNum
[X,Y]=find(LPic==i);
Xmean=mean(X);
Ymean=mean(Y);
pointSet(i,:)=[Xmean,Ymean];
end
%subplot(2,2,4)
figure
imshow(bwPic)
hold on
scatter(pointSet(:,2),pointSet(:,1),'r','LineWidth',1)
n=1;
while ~isempty(pointSet)
circleSetInd=1;
for j=1:length(pointSet)
disSet=sqrt(sum((pointSet-pointSet(circleSetInd(end),:)).^2,2));
[~,ind]=sort(disSet);
ind=ind(1:5);
[~,~,t_ind]=intersect(circleSetInd,ind);
ind(t_ind)=[];
if ~isempty(ind)
circleSetInd=[circleSetInd;ind(1)];
else
circleSet{n}=pointSet(circleSetInd,:);
pointSet(circleSetInd,:)=[];
n=n+1;
break
end
end
end
figure
imshow(oriPic)
hold on
for i=1:n-1
plot(circleSet{i}(:,2),circleSet{i}(:,1),'LineWidth',2)
end
end
其它形狀空心散點檢測
來波正方形試試:






可以看出效果還是很棒的,當然大家可以根據實際情況自行更改影像腐蝕模板形狀,如果散點是其它顏色請自行更改第一步的影像分割條件,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/296686.html
標籤:其他

