%%圖像邊緣檢測和拟合輪廓
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