% 确定目标(篮球)的横纵坐标,以及球的半径
function [cc,cr,radius,flag]=extractball(Imwork,Imback,fig1,fig2,fig3,fig5,index)
cc = 0;
cr = 0;
radius=0;
flag=0;
[MR,MC,Dim] = size(Imback);
% 与背景相减得到相素不同的点
fore = zeros(MR,MC);
fore = (abs(Imwork(:,:,1)-Imback(:,:,1)) > 10) ...
| (abs(Imwork(:,:,2) - Imback(:,:,2)) > 10) ...
| (abs(Imwork(:,:,3) - Imback(:,:,3)) > 10);
if fig5 > 0
figure(fig5)
clf
imshow(fore)
end
% 腐蚀除去噪声
foremm = bwmorph(fore,'erode',2);
if fig2 > 0
figure(fig2)
clf
imshow(foremm)
end
% 确定目标外框,得到面积
labeled = bwlabel(foremm,4);
stats = regionprops(labeled,['basic']);
[N,W] = size(stats);
if N < 1
return
end
% 用冒泡法(从大到小)排序
id = zeros(N);
for i = 1 : N
id(i) = i;
end
for i = 1 : N-1
for j = i+1 : N
if stats(i).Area < stats(j).Area
tmp = stats(i);
stats(i) = stats(j);
stats(j) = tmp;
tmp = id(i);
id(i) = id(j);
id(j) = tmp;
end
end
end
% 确定一个最大区域,即面积
if stats(1).Area < 100
return
end
selected = (labeled==id(1));
if fig3 > 0
figure(fig3)
clf
imshow(selected)
end
% 确定目标的质心和半径
centroid = stats(1).Centroid;
radius = sqrt(stats(1).Area/pi);
cc = centroid(1);
cr = centroid(2);
flag = 1;
return