function out = OpenBoundaryTrack(bw)
% 单个边缘跟踪,pstart为联通区右下方的像素点 当边缘位于边界处,无法跟踪,需将
% 图像人为扩大2*2像素并置0,并将最后结果做边界处理

bw1=zeros(size(bw)+2);
bw1(2:end-1,2:end-1)=bw;
ba=BoundaryTrack(bw1);
[row,col]=size(bw);
ba=ba-1;
ba(find(ba(:,1)==1 | ba(:,1) == col | ba(:,2)== 1 | ba(:,2)== row),:)=[];
% 寻找最大距离为开始点
[~,dex]=max(sum((ba(1:end-1,:)-ba(2:end,:)).^2,2));
out=[ba(dex+1:end,:);ba(1:dex,:)];


function pt =BoundaryTrack(bw,pstart,pend)
% 单个边缘跟踪,pstart为联通区右下方的像素点 当边缘位于边界处,无法跟踪,需将
% 图像人为扩大2*2像素并置0,并将最后结果做边界处理
[row, col]= size(bw);
if ~exist('pstart','var')
    for i=1:row
        for j=1:col
            if bw(i,j)~=0
                pstart.y = i;
                pstart.x = j;
            end
        end
    end
end
if ~exist('pend','var')
    pend=pstart;
end

%%
k=0;
flag = 1;
ptcurrent = pstart;
off=[1 0; 1 1; 0 1; -1 1; -1 0; -1 -1; 0 -1; 1 -1];

pt=[pstart.x pstart.y];
while flag
flag = 0;   
for i =1:8
    k=bitand(k,7);
    x = ptcurrent.x + off(k+1,1);
    y = ptcurrent.y + off(k+1,2);

    if x>=1 && x <=col && y>=1 && y <=row
        if bw(y,x)
            for j = 1:2:8
                ptemp.x = x + off(j,1);
                ptemp.y = y + off(j,2);
                if ptemp.x >=1 && ptemp.x <=col && ptemp.y >=1 && ptemp.y <=row
                    if bw(ptemp.y, ptemp.x) == 0
                        flag = 1;
                        ptcurrent.x = x;
                        ptcurrent.y = y;
                        pt=[pt;x y];
                        break;
                    end
                end
            end
        end
    end
    if flag
        if pend.x == ptcurrent.x && pend.y == ptcurrent.y 
            flag = 0;
        end
        break;
    end
    k = k +1;
end
k = k + 6;
end