线结构光的条纹形状随着物体表面的变化而不同,在比较小的范围内,可 以认为线结构光条纹只有四种模式,水平,垂直,左倾45°,右倾45°。为了能够准确地描述线结构光条纹的形状,在模块选取时一般根据光带的粗细程度进行选取,因为太大不能准确的反映出条纹的细节,太小又不能反映出光带的走向,因此选取了一个9x9的模块来与之相匹配对应这四种模式。设计了四种方
向的模板,将模板记为T,模板内的元素为0和l,建立的四个模扳为
这四个模板沿着细化后的图像中的细线移动, 依次以每个点为中心与图像做相关运算
c(u,v)为图像中细化曲线上的点,对每一个点可以求得四个不同的相关值, 这个值反映了这个点处的图像与模板的相关程度。其值越大,相关程度越高,
所以当H的相关度最高时,可以认为该点附近的图像的斜率最接近于第k个模板 的方向,因此就可以近似地求出该点的法线。求出了法线以后,沿着法线方向,
以这个点为中心,两边各取6个点,然后利用灰度重心法求出该处的线结构光 ’
图像的中心。
clear;
clc
I = imread('IMG1_1.bmp');
if ndims(I) == 3
I = rgb2gray(I);
end
thresh =20;
[r,c] = size(I);
for i = 1:r
for j = 1:c
if I(i,j) < thresh
I(i,j) = 0;
end
end
end
%创建预定义滤波算子
gaussFilter = fspecial('gaussian',[7 7],5);
%对图像进行滤波,‘replicate’表示图像大小通过复制外边界的值来扩展
I = imfilter(I,gaussFilter,'replicate');
%灰度拉伸,增强图像对比
I = im2uint8( mat2gray( log(1 + double(I)) ) );
imshow(I);
I = double(I)/255;
%二值化图像
thresh = graythresh(I);
I1=im2bw(I,thresh);
imshow(I1);
%膨胀处理
I1=bwmorph(I1,'dilate',10);
imshow(I1);
%腐蚀
se = strel('disk',6);
I1=imclose(I1,se);
I1 = bwmorph(I1,'thin',Inf);
% bwl=bwmorph(I,'skel',Inf);
% figure;
imshow(I1);
% [r,c]=size(I1);
% T1=[0 0 0 0 1 0 0 0 0;
% 0 0 0 0 1 0 0 0 0;
% 0 0 0 0 1 0 0 0 0;
% 0 0 0 0 1 0 0 0 0;
% 0 0 0 0 1 0 0 0 0;
% 0 0 0 0 1 0 0 0 0;
%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;
1 0 0 0 0 0 0 0 0 0 0 0 0
];
% [H,W] = size(I);
% I = [zeros(7,W);I;zeros(7,W)];
% I = [zeros(H+14,7),I,zeros(H+14,7)];
% [H,W] = size(I1);
% I1 = [zeros(7,W);I1;zeros(7,W)];
% I1 = [zeros(H+14,7),I1,zeros(H+14,7)];
[r,c] = size(I1);
H1=zeros(r,c);
H2=zeros(r,c);
H3=zeros(r,c);
H4=zeros(r,c);
num1=zeros(11,1);
num2=zeros(11,1);
centerU = [];
centerV = [];
center = [];
ccc=0;
%模板匹配,遍历模板中的点与骨架上的每一个点,如果匹配度最高,必定乘积最大
for u=7:r-7
for v=7:c-7
if I1(u,v)
for i=1:13
for j=1:13
H1(u,v)=I1(u-7+i,v-7+j).*T1(i,j)+H1(u,v);
H2(u,v)=I1(u-7+i,v-7+j).*T2(i,j)+H2(u,v);
H3(u,v)=I1(u-7+i,v-7+j).*T3(i,j)+H3(u,v);
H4(u,v)=I1(u-7+i,v-7+j).*T4(i,j)+H4(u,v);
end
end
data=[H1(u,v),H2(u,v),H3(u,v),H4(u,v)];
h=find(data==max( data));
cc=length(h);
if cc>1
h=h(2);
end
if h==1
for k = 1:9
num1(k) = I(u-5+k,v)*(u-5+k);
num2(k) = I(u-5+k,v);
end
centerU = sum(num1)/sum(num2);
centerV = v;
center = [center;[centerV,centerU]];
end
if h==2
for k = 1:9
num1(k) = I(u,v-5+k)*(v-5+k);
num2(k) = I(u,v-5+k);
end
centerU = sum(num1)/sum(num2);
centerV = u;
center = [center;[centerU,centerV]];
end
if h==3
for k = 1:9
num1(k) = I(u+5-k,v-5+k)*(v-5+k);
num2(k) = I(u+5-k,v-5+k);
end
centerU = sum(num1)/sum(num2);
for k = 1:9
num1(k) = I(u+5-k,v-5+k)*(u+5-k);
num2(k) = I(u+5-k,v-5+k);
end
centerV = sum(num1)/sum(num2);
center = [center;[centerU,centerV]];
end
if h==4
for k = 1:9
num1(k) = I(u-5+k,v-5+k)*(v-5+k);
num2(k) = I(u-5+k,v-5+k);
end
centerU = sum(num1)/sum(num2);
for k = 1:9
num1(k) = I(u-5+k,v-5+k)*(u-5+k);
num2(k) = I(u-5+k,v-5+k);
end
centerV = sum(num1)/sum(num2);
center = [center;[centerU,centerV]];
end
end
end
end
% center=sortrows(center,1);
figure;
imshow(I)
hold on
plot(center(:,1),center(:,2),'r.')
% hold on
% plot(b,a,'b.')