我有一张包含闭合曲线的图像。
我想以逆时针方式跟踪任何闭合曲线。我发现我可以使用bwtraceboundary
功能,但我不知道如何正确使用它。
目前我的代码是:
function [] = project()
close all;
origImg = imread('closed.png');
BW = im2bw(imcomplement(rgb2gray(origImg)));
imshow(BW,[]);
s = size(BW);
for row = 2:15:s(1)
for col = 1:s(2)
if BW(row,col)
break;
end
end
contour = bwtraceboundary(BW,[row col],'W',8,1000,'counterclockwise');
if(~isempty(contour))
hold on;
plot(contour(:,2),contour(:,1),'g','LineWidth',2);
hold on;
plot(col,row,'gx','LineWidth',2);
else
hold on;
plot(col,row,'rx','LineWidth',2);
end
端
目前我的代码没有跟踪"已关闭"区域!
知道怎么继续吗?
答案 0 :(得分:0)
我带了你的代码并对其进行了评论,所以你知道什么是最重要的。
你从matlab的例子中得到了那些代码,但它没有按照你的想法去做。您不需要所有迭代,您可能希望修改代码以获得跟踪轮廓的更多点。由于我不想为你编写代码,所以我觉得解释你在做什么是一个好主意,所以现在就是这样。你可以复制粘贴它并且应该可以工作,你应该会看到某种动画。
代码:
% READ IMAGE
origImg = imread('so.png');
% Create a binary image of the original image being white the contours and
% black the rest
BW = im2bw(imcomplement(rgb2gray(origImg)));
% show it
imshow(BW,[]);
% wait 2 seconds so you can see it
pause(2)
s = size(BW);
% Go iterating thougth rows and cols until you find something white
% (contour)
for row = 2:15:s(1)
for col = 1:s(2)
if BW(row,col)
break; %something white found!
end
end
% Trace that boundary! Starting in the white point (row,col)
contour = bwtraceboundary(BW,[row col],'W',8,200,'counterclockwise');
% Did we actually found a contour or its just empty (e.g. it was
% point)
if(~isempty(contour))
% There is a contour! lets plot it (we will only get a piece of it,
% because we specified that only 200 points of it will be used!
hold on;
% plot the contour in green
plot(contour(:,2),contour(:,1),'g','LineWidth',2);
hold on;
% plot the initial point of the conotur in blue
plot(col,row,'bx','LineWidth',2);
pause(1)
else
% If there was not a contour just put a red X on it
hold on;
plot(col,row,'rx','LineWidth',2);
end
end