很多时候我们需要在图像中标定矩形框,比如视觉跟踪领域经常需要标定跟踪目标的groundtruth.我们为此在Matlab环境下编写了如下程序,很好地实现了这个功能。
clear
clc
title='xx';%待标定图像所在的文件夹名称
route='xxx\';%该文件夹的路径
imgfile=dir([route,title,'\*.jpg']);%假定图像为jpg格式,可进行相应的更改
Num=numel(imgfile);%图像帧数
gt=[];%存放标定结果
i=1;%开始序号
interval=1;%标定间隔,如果interval为4,则每5帧标定一次
while i<Num
img=imread([route,title,'\',imgfile(i).name]);
imshow(img);
text(5,18,num2str(i),'Color','y','FontWeight','bold','FontSize',18);
if i==1
h=imrect;%第一帧初始化环境
else
h=imrect(gca,gt(end,2:5));%显示上一次的标定结果
end
pause;
disp(round(getPosition(h)))%按空格键显示标定矩形框的参数[x,y,w,h]
gt=[gt;i,getPosition(h)];
i=i+interval;
end
img=imread([route,title,'\',imgfile(Num).name]);
imshow(img);
text(5,18,num2str(Num),'Color','y','FontWeight','bold','FontSize',18);
h=imrect(gca,gt(end,2:5));
pause;
disp(round(getPosition(h)))
gt=[gt;Num,getPosition(h)];
k=1;
tempAll = [];%存放插值之后的标定结果
while(gt(k,1)<max(gt(:,1)))
tempStart = gt(k,:);
tempEnd = gt(k+1,:);
%% 对tempStart和tempEnd的异常处理
total = tempEnd(1)-tempStart(1);
delta =(tempEnd-tempStart) / total;
for j=0:total-1
tempAll=[tempAll;tempStart + j*delta];
end
k = k + 1;
end
tempAll = [tempAll; tempEnd];
tempAll=round(tempAll);
%存储最后的标定结果,每一行的格式为[x,y,w,h]并用逗号隔开
dlmwrite([route,title,'\1.txt'],tempAll(:,2:5),'delimiter',',');