clc;clear;
edgeIm = imread('04.png');
%figure, imshow(edgeIm);
%edgeIm中非零元素的坐标,即轮廓坐标
[i, j] = find(edgeIm);%i为对应的行,j为对应的列,要与坐标x,y 区别开来。一般x对应列j。y对应i行。
%轮廓点数
numPoints = size(i, 1);%当然size(j,1)。相同
curNum = 0;%目标点数累加初始化(用以叠加计数)
%初始搜索点坐标
currentR = i(1, 1);
currentC = j(1, 1);
%初始化轮廓点坐标
points = zeros(numPoints, 2);
%开始搜索
curNum = curNum + 1;
points(curNum,1:2) = [currentR, currentC];%currentR对应矩阵的行,%要保证下标对应的位数要匹配(可以是:或1:2,不能是省或是单个1或2)
edgeIm(currentR, currentC) = 0;%把对应轮廓图的哪一点变为0,即背景像素值
while curNum ~= numPoints;%当搜索的计数的轮廓点数不等于实际总数,则执行循环
if edgeIm(currentR, currentC-1) == 1;%如果该点轮廓坐标附近左边那一个点(currentR, currentC-1)是目标(像素为1)
curNum = curNum + 1;%则目标像素个数增加一个
currentC = currentC - 1;%获取该点实际坐标对应的的列值
points(curNum,:) = [currentR, currentC];%把这一点对应的像素坐标放到为目标轮廓开辟的空间的第二个(curNum = curNum + 1,初始curNum为0)(行)对应的位置。同理(curNum,:)可以是(curNum,1:2)
edgeIm(currentR, currentC) = 0;%放完之后把对应轮廓图的这一点变为0,即背景像素值
elseif edgeIm(currentR-1, currentC-1) == 1;%原始最初目标点的左上方,即8邻域,顺时针寻找目标轮廓
curNum = curNum + 1;%如果上一步条件成立,则这一步表示寻找的轮廓点增加一个
currentR = currentR - 1;%执行一次循环最初点,向上移动一个单位:
currentC = currentC - 1;%执行一次循环最初点,向左移动一个单位:
points(curNum,:) = [currentR, currentC];%把这一点对应的像素坐标放到为目标轮廓开辟的空间的curNum个(行)对应的位置
edgeIm(currentR, currentC) = 0;%放完之后把对应轮廓图的这一点变为0,即背景像素值
elseif edgeIm(currentR-1, currentC) == 1;%同理,判断是否成立,即最初目标点的正上方,即8邻域,故进一步可知是顺时针寻找目标轮廓,若想改为逆时针,则只需改变此处if句的判断顺序即可
curNum = curNum + 1;
currentR = currentR - 1;
points(curNum,:) = [currentR, currentC];%得到的顺时针寻找目标轮廓对应的像素点的坐标
edgeIm(currentR, currentC) = 0;%把对应轮廓图的这一点变为0,即背景像素值
elseif edgeIm(currentR-1, currentC+1) == 1;%最初目标点的右上方
curNum = curNum + 1;
currentR = currentR - 1;
currentC = currentC + 1;
points(curNum,:) = [currentR, currentC];
edgeIm(currentR, currentC) = 0;
elseif edgeIm(currentR, currentC+1) == 1;%最初目标点的右边
curNum = curNum + 1;
currentC = currentC + 1;
points(curNum,:) = [currentR, currentC];
edgeIm(currentR, currentC) = 0;
elseif edgeIm(currentR+1, currentC+1) == 1;%最初目标点的右下边
curNum = curNum + 1;
currentR = currentR + 1;
currentC = currentC + 1;
points(curNum,:) = [currentR, currentC];
edgeIm(currentR, currentC) = 0;
elseif edgeIm(currentR+1, currentC) == 1;%最初目标点的正下边
curNum = curNum + 1;
currentR = currentR + 1;
points(curNum,:) = [currentR, currentC];
edgeIm(currentR, currentC) = 0;
elseif edgeIm(currentR+1, currentC-1) ==1;%最初目标点的左下边
curNum = curNum + 1;
currentR = currentR + 1;
points(curNum,:) = [currentR, currentC];
edgeIm(currentR, currentC) = 0;
end
end