天天看点

matlab边缘拟合,图像边缘检测,轮廓拟合

%%图像边缘检测和拟合轮廓

clc

clear

close all

%% 读取图像

I = imread('coins.png');

I = im2bw(I);                                   %二值化

I = imfill(I,'holes');                          %填补孔洞

[M,N] = size(I);

figure(1),imshow(I);title('原图');hold on

%% 选取待拟合坐标

% conicP = ginput(15);

bw1 = edge(I,'sobel');                           %边缘检测

figure(2),imshow(bw1);title('边缘检测');

[L,num] = bwlabel(bw1);                           %标签

for i = 1:num

[row,col] = find(L == i);

conicP = zeros(length(row),2);

conicP(:,1) = col;

conicP(:,2) = row;

figure(1),plot(conicP(:,1)', conicP(:,2)', 'xr');     %drawing sample points

%% 自定义椭圆函数拟合

a0 = [1 1 1 1 1 1];

f = @(a,x)a(1)*x(:,1).^2+a(2)*x(:,2).^2+a(3)*x(:,1).*x(:,2)+a(4)*x(:,1)+a(5)*x(:,2)+a(6);%建立方程

p = nlinfit(conicP , zeros(size(conicP, 1), 1), f,[1 2 3 4 5 6]);

syms x y

conic = p(1)*x^2+p(2)*y^2+p(3)*x*y+p(4)*x+p(5)*y+p(6);

%% 在原图上显示拟合结果

c = ezplot(conic,[0,N],[0,M]);

figure(1),set(c, 'Color', 'Blue','LineWidth',2);

end

hold off