source: trunk/src/geometry_calib.m @ 693

Last change on this file since 693 was 693, checked in by sommeria, 11 years ago

bug repaired geometry_calib/Detect grid, + corrections in get_field

File size: 54.5 KB
RevLine 
[168]1%'geometry_calib': associated to the GUI geometry_calib to perform geometric calibration from a set of reference points
2%------------------------------------------------------------------------
3% function hgeometry_calib = geometry_calib(inputfile,pos)
[2]4%
[168]5%OUTPUT:
6% hgeometry_calib=current handles of the GUI geometry_calib.fig
[2]7%
[168]8%INPUT:
9% inputfile: (optional) name of an xml file containing coordinates of reference points
10% pos: (optional) 4 element vector setting the 'Position' of the GUI
11%
[109]12%A%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
[2]13%  Copyright Joel Sommeria, 2008, LEGI / CNRS-UJF-INPG, sommeria@coriolis-legi.org.
14%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
15%     This file is part of the toolbox UVMAT.
16%
17%     UVMAT is free software; you can redistribute it and/or modify
18%     it under the terms of the GNU General Public License as published by
19%     the Free Software Foundation; either version 2 of the License, or
20%     (at your option) any later version.
21%
22%     UVMAT is distributed in the hope that it will be useful,
23%     but WITHOUT ANY WARRANTY; without even the implied warranty of
24%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25%     GNU General Public License (file UVMAT/COPYING.txt) for more details.
26%AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
27
28function varargout = geometry_calib(varargin)
29% GEOMETRY_CALIB M-file for geometry_calib.fig
30%      GEOMETRY_CALIB, by itself, creates a MenuCoord GEOMETRY_CALIB or raises the existing
31%      singleton*.
32%
33%      H = GEOMETRY_CALIB returns the handle to a MenuCoord GEOMETRY_CALIB or the handle to
34%      the existing singleton*.
35%
36%      GEOMETRY_CALIB('CALLBACK',hObject,eventData,handles,...) calls the local
37%      function named CALLBACK in GEOMETRY_CALIB.M with the given input arguments.
38%
39%      GEOMETRY_CALIB('Property','Value',...) creates a MenuCoord GEOMETRY_CALIB or raises the
40%      existing singleton*.  Starting from the left, property value pairs are
41%      applied to the GUI before geometry_calib_OpeningFunction gets called.  An
42%      unrecognized property name or invalid value makes property application
43%      stop.  All inputs are passed to geometry_calib_OpeningFcn via varargin.
44%
45%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
46%      instance to run (singleton)".
47%
48% See also: GUIDE, GUIDATA, GUIHANDLES
49
50% Edit the above text to modify the response to help geometry_calib
51
[693]52% Last Modified by GUIDE v2.5 29-Oct-2013 06:46:10
[2]53
54% Begin initialization code - DO NOT edit
55gui_Singleton = 1;
56gui_State = struct('gui_Name',       mfilename, ...
57                   'gui_Singleton',  gui_Singleton, ...
58                   'gui_OpeningFcn', @geometry_calib_OpeningFcn, ...
59                   'gui_OutputFcn',  @geometry_calib_OutputFcn, ...
60                   'gui_LayoutFcn',  [] , ...
61                   'gui_Callback',   []);
[672]62if nargin
63   [pp,ff]=fileparts(which(varargin{1})); % name of the input file
64   if strcmp(ff,mfilename)% if we are activating a sub-function of geometry_calib
65   % ~isempty(regexp(varargin{1},'_Callback','once'))
[2]66    gui_State.gui_Callback = str2func(varargin{1});
[672]67   end
[2]68end
69
70if nargout
71    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
72else
73    gui_mainfcn(gui_State, varargin{:});
74end
75% End initialization code - DO NOT edit
76
77
78% --- Executes just before geometry_calib is made visible.
79%INPUT:
80%handles: handles of the geometry_calib interface elements
81% PlotHandles: set of handles of the elements contolling the plotting
82% parameters on the uvmat interface (obtained by 'get_plot_handle.m')
[60]83%------------------------------------------------------------------------
[657]84function geometry_calib_OpeningFcn(hObject, eventdata, handles,inputfile)
[60]85%------------------------------------------------------------------------
[2]86% Choose default command line output for geometry_calib
[156]87
[2]88handles.output = hObject;
89
90% Update handles structure
91guidata(hObject, handles);
[71]92set(hObject,'DeleteFcn',{@closefcn})%
[657]93%set(hObject,'WindowButtonDownFcn',{'mouse_alt_gui',handles}) % allows mouse action with right button (zoom for uicontrol display)
[71]94
[613]95%% position
[657]96set(0,'Unit','pixels')
[613]97ScreenSize=get(0,'ScreenSize');% get the size of the screen, to put the fig on the upper right
[672]98Left=ScreenSize(3)- 460; %right edge close to the right, with margin=40 (GUI width=420 px)
[674]99if ScreenSize(4)>920
[672]100    Height=840;%default height of the GUI
101    Bottom=ScreenSize(4)-Height-40; %put fig at top right
102else
[674]103    Height=ScreenSize(4)-80;
104    Bottom=40; % GUI lies o the screen bottom (with margin =40)
[672]105end
[674]106set(handles.calib_type,'Position',[1 Height-40 194 30])%  rank 1
107set(handles.APPLY,'Position',[197 Height-40 110 30])%  rank 1
108set(handles.REPLICATE,'Position',[309 Height-40 110 30])%  rank 1
109set(handles.Intrinsic,'Position',[1 Height-40-2-92 418 92])%  rank 2
110set(handles.Extrinsic,'Position',[1 Height-40-4-92-75 418 75])%  rank 3
111set(handles.PointLists,'Position',[1 Height-40-6-92-75-117 418 117]) %  rank 4
112set(handles.CheckEnableMouse,'Position',[3 Height-40-8-92-75-117-30 203 30])%  rank 5
113set(handles.PLOT,'Position',[3 Height-394 120 30])%  rank 6
114set(handles.Copy,'Position',[151 Height-394 120 30])%  rank 6
115set(handles.CLEAR_PTS,'Position',[297 Height-394 120 30])%  rank 6
[693]116set(handles.ClearLine,'Position',[297 Height-364 120 30])%  rank 6
[674]117set(handles.phys_title,'Position',[38 Height-426 125 20])%  rank 7
118set(handles.CoordUnit,'Position',[151 Height-426 120 30])%  rank 7
119set(handles.px_title,'Position',[272 Height-426 125 20])%  rank 7
120set(handles.ListCoord,'Position',[1 20 418 Height-446])% rank 8
[672]121set(handles.geometry_calib,'Position',[Left Bottom 420 Height])
[657]122
[109]123%set menu of calibration options
[121]124set(handles.calib_type,'String',{'rescale';'linear';'3D_linear';'3D_quadr';'3D_extrinsic'})
[116]125if exist('inputfile','var')&& ~isempty(inputfile)
[114]126    struct.XmlInputFile=inputfile;
[494]127    [RootPath,SubDir,RootFile,tild,tild,tild,tild,FileExt]=fileparts_uvmat(inputfile);
[341]128    if ~strcmp(FileExt,'.xml')
[494]129        inputfile=fullfile(RootPath,[SubDir '.xml']);%xml file corresponding to the input file
130        if ~exist(inputfile,'file')% case of civ files , removes the extension for subdir
131            inputfile=fullfile(RootPath,[regexprep(SubDir,'\..+$','') '.xml']);
132            if ~exist(inputfile,'file')
133                inputfile=[fullfile(RootPath,SubDir,RootFile) '.xml'];%old convention
134                if ~exist(inputfile,'file')
135                    inputfile='';
136                end
137            end
138        end
[116]139    end
[657]140    set(handles.ListCoord,'Data',[])
[156]141    if exist(inputfile,'file')
[498]142        Heading=loadfile(handles,inputfile);% load data from the xml file
[156]143        if isfield(Heading,'Campaign')&& ischar(Heading.Campaign)
144            struct.Campaign=Heading.Campaign;
145        end
146    end   
147    set(hObject,'UserData',struct)
[2]148end
[156]149
[17]150%------------------------------------------------------------------------
[2]151% --- Outputs from this function are returned to the command line.
[657]152function varargout = geometry_calib_OutputFcn(~, eventdata, handles)
[17]153%------------------------------------------------------------------------
[2]154% Get default command line output from handles structure
155varargout{1} = handles.output;
156varargout{2}=handles;
[67]157%
[60]158%------------------------------------------------------------------------
[2]159% executed when closing: set the parent interface button to value 0
[67]160function closefcn(gcbo,eventdata)
[60]161%------------------------------------------------------------------------
[2]162huvmat=findobj(allchild(0),'Name','uvmat');
[67]163if ~isempty(huvmat)
164    handles=guidata(huvmat);
[672]165    set(handles.MenuCalib,'Checked','off')
[541]166    hobject=findobj(handles.PlotAxes,'tag','calib_points');
[67]167    if ~isempty(hobject)
168        delete(hobject)
169    end
[541]170    hobject=findobj(handles.PlotAxes,'tag','calib_marker');
[67]171    if ~isempty(hobject)
172        delete(hobject)
173    end   
[2]174end
175
[60]176%------------------------------------------------------------------------
[569]177% --- Executes on button press APPLY (used to launch the calibration).
[2]178function APPLY_Callback(hObject, eventdata, handles)
[60]179%------------------------------------------------------------------------
[379]180%% look for the GUI uvmat and check for an image as input
[682]181set(handles.APPLY,'BackgroundColor',[1 1 0])
[379]182huvmat=findobj(allchild(0),'Name','uvmat');
183hhuvmat=guidata(huvmat);%handles of elements in the GUI uvmat
184
[569]185RootPath='';
186if ~isempty(hhuvmat.RootPath)&& ~isempty(hhuvmat.RootFile)
187    RootPath=get(hhuvmat.RootPath,'String');
188    SubDirBase=regexprep(get(hhuvmat.SubDir,'String'),'\..+$','');
189    outputfile=[fullfile(RootPath,SubDirBase) '.xml'];%xml file associated with the currently displayed image
190else
191    question={'save the calibration data and point coordinates in'};
192    def={fullfile(RootPath,'ObjectCalib.xml')};
193    options.Resize='on';
194    answer=inputdlg(question,'',1,def,options);
195    outputfile=answer{1};
196end
197[GeometryCalib,index]=calibrate(handles,hhuvmat);% apply calibration
198
[682]199if isempty(GeometryCalib) % if calibration cancelled
200    set(handles.APPLY,'BackgroundColor',[1 0 1])
201else   % if calibration confirmed
202   
203    %% copy the xml file from the old location if appropriate, then update with the calibration parameters
204    if ~exist(outputfile,'file') && ~isempty(SubDirBase)
205        oldxml=[fullfile(RootPath,SubDirBase,get(hhuvmat.RootFile,'String')) '.xml'];
206        if exist(oldxml,'file')
207            [success,message]=copyfile(oldxml,outputfile);%copy the old xml file to a new one with the new convention
208        end
[569]209    end
[682]210    errormsg=update_imadoc(GeometryCalib,outputfile,'GeometryCalib');% introduce the calibration data in the xml file
211    if ~strcmp(errormsg,'')
212        msgbox_uvmat('ERROR',errormsg);
213    end
214   
215    %% display image with new calibration in the currently opened uvmat interface
216    hhh=findobj(hhuvmat.PlotAxes,'Tag','calib_marker');% delete calib points and markers
217    if ~isempty(hhh)
218        delete(hhh);
219    end
220    hhh=findobj(hhuvmat.PlotAxes,'Tag','calib_points');
221    if ~isempty(hhh)
222        delete(hhh);
223    end
224    set(hhuvmat.CheckFixLimits,'Value',0)% put FixedLimits option to 'off'
225    set(hhuvmat.CheckFixLimits,'BackgroundColor',[0.7 0.7 0.7])
226    UserData=get(handles.geometry_calib,'UserData');
227    UserData.XmlInputFile=outputfile;%save the current xml file name
228    set(handles.geometry_calib,'UserData',UserData)
229    uvmat('RootPath_Callback',hObject,eventdata,hhuvmat); %file input with xml reading  in uvmat, show the image in phys coordinates
230    PLOT_Callback(hObject, eventdata, handles)
231    Data=get(handles.ListCoord,'Data');
232    Data(:,6)=zeros(size(Data,1),1);
[693]233    Data(index,6)=-1;% indicate in the list the point with max deviation (possible mistake)
[682]234    set(handles.ListCoord,'Data',Data)% indicate in the list the point with max deviation (possible mistake)
235    figure(handles.geometry_calib)
236    set(handles.APPLY,'BackgroundColor',[1 0 0])
[569]237end
238
239%------------------------------------------------------------------------
240% --- Executes on button press in REPLICATE
241function REPLICATE_Callback(hObject, eventdata, handles)
242%------------------------------------------------------------------------
243
244%% look for the GUI uvmat and check for an image as input
245huvmat=findobj(allchild(0),'Name','uvmat');
246hhuvmat=guidata(huvmat);%handles of elements in the GUI uvmat
247GeometryCalib=calibrate(handles,hhuvmat);% apply calibration
248
249%% open the GUI browse_data
250CalibData=get(handles.geometry_calib,'UserData');%read the calibration image source on the interface userdata
251if isfield(CalibData,'XmlInputFile')
252    InputDir=fileparts(fileparts(CalibData.XmlInputFile));
253end
254answer=msgbox_uvmat('INPUT_TXT','Campaign to calibrate?',InputDir);
255if strcmp(answer,'Cancel')
256    return
257end
258OutPut=browse_data(answer);
259nbcalib=0;
260for ilist=1:numel(OutPut.Experiment)
261    SubDirBase=regexprep(OutPut.Device{1},'\..+$','');
262    XmlName=fullfile(OutPut.Campaign,OutPut.Experiment{ilist},[SubDirBase '.xml']);
263    % copy the xml file from the old location if appropriate, then update with the calibration parameters
264    if ~exist(XmlName,'file') && ~isempty(SubDirBase)
265        oldxml=fullfile(OutPut.Campaign,OutPut.Experiment{ilist},SubDirBase,[get(hhuvmat.RootFile,'String') '.xml']);
266        if exist(oldxml,'file')
267            [success,message]=copyfile(oldxml,XmlName);%copy the old xml file to a new one with the new convention
268        end
269    end
[630]270    errormsg=update_imadoc(GeometryCalib,XmlName,'GeometryCalib');% introduce the calibration data in the xml file
[569]271    if ~strcmp(errormsg,'')
272        msgbox_uvmat('ERROR',errormsg);
273    else
274        display([XmlName ' updated with calibration parameters'])
275        nbcalib=nbcalib+1;
276    end
277end
278msgbox_uvmat('CONFIMATION',[SubDirBase ' calibrated for ' num2str(nbcalib) ' experiments']);
279
280%------------------------------------------------------------------------
281% --- activate calibration and store parameters in ouputfile .
282function [GeometryCalib,index]=calibrate(handles,hhuvmat)
283%------------------------------------------------------------------------
[379]284%% read the current calibration points
[657]285Coord=get(handles.ListCoord,'Data');
286Coord(:,6)=[];
[109]287% apply the calibration, whose type is selected in  handles.calib_type
288if ~isempty(Coord)
289    calib_cell=get(handles.calib_type,'String');
290    val=get(handles.calib_type,'Value');
291    GeometryCalib=feval(['calib_' calib_cell{val}],Coord,handles);
292else
293    msgbox_uvmat('ERROR','No calibration points, abort')
294    return
295end
[114]296Z_plane=[];
[109]297if ~isempty(Coord)
[114]298    %check error
[109]299    X=Coord(:,1);
300    Y=Coord(:,2);
301    Z=Coord(:,3);
302    x_ima=Coord(:,4);
303    y_ima=Coord(:,5);
[114]304    [Xpoints,Ypoints]=px_XYZ(GeometryCalib,X,Y,Z);
[109]305    GeometryCalib.ErrorRms(1)=sqrt(mean((Xpoints-x_ima).*(Xpoints-x_ima)));
306    [GeometryCalib.ErrorMax(1),index(1)]=max(abs(Xpoints-x_ima));
307    GeometryCalib.ErrorRms(2)=sqrt(mean((Ypoints-y_ima).*(Ypoints-y_ima)));
308    [GeometryCalib.ErrorMax(2),index(2)]=max(abs(Ypoints-y_ima));
[494]309    [tild,ind_dim]=max(GeometryCalib.ErrorMax);
[109]310    index=index(ind_dim);
[114]311    %set the Z position of the reference plane used for calibration
[109]312    if isequal(max(Z),min(Z))%Z constant
[114]313        Z_plane=Z(1);
[109]314        GeometryCalib.NbSlice=1;
[114]315        GeometryCalib.SliceCoord=[0 0 Z_plane];
[109]316    end
317end
[114]318%set the coordinate unit
[2]319unitlist=get(handles.CoordUnit,'String');
320unit=unitlist{get(handles.CoordUnit,'value')};
321GeometryCalib.CoordUnit=unit;
[114]322%record the points
[109]323GeometryCalib.SourceCalib.PointCoord=Coord;
[114]324display_intrinsic(GeometryCalib,handles)%display calibration intrinsic parameters
[109]325
[114]326% Display extrinsinc parameters (rotation and translation of camera with  respect to the phys coordiantes)
[109]327set(handles.Tx,'String',num2str(GeometryCalib.Tx_Ty_Tz(1),4))
328set(handles.Ty,'String',num2str(GeometryCalib.Tx_Ty_Tz(2),4))
329set(handles.Tz,'String',num2str(GeometryCalib.Tx_Ty_Tz(3),4))
[114]330set(handles.Phi,'String',num2str(GeometryCalib.omc(1),4))
331set(handles.Theta,'String',num2str(GeometryCalib.omc(2),4))
332set(handles.Psi,'String',num2str(GeometryCalib.omc(3),4))
[109]333
[379]334%% store the calibration data, by default in the xml file of the currently displayed image
[569]335UvData=get(hhuvmat.uvmat,'UserData');
[191]336NbSlice_j=1;%default
337ZStart=Z_plane;
338ZEnd=Z_plane;
[196]339volume_scan='n';
[191]340if isfield(UvData,'XmlData')
341    if isfield(UvData.XmlData,'TranslationMotor')
342        NbSlice_j=UvData.XmlData.TranslationMotor.Nbslice;
[196]343        ZStart=UvData.XmlData.TranslationMotor.ZStart/10;
344        ZEnd=UvData.XmlData.TranslationMotor.ZEnd/10;
345        volume_scan='y';
[191]346    end
347end
[569]348
349answer=msgbox_uvmat('INPUT_Y-N',{'store calibration data';...
[2]350    ['Error rms (along x,y)=' num2str(GeometryCalib.ErrorRms) ' pixels'];...
[84]351    ['Error max (along x,y)=' num2str(GeometryCalib.ErrorMax) ' pixels']});
[128]352
[569]353%% get plane position(s)
354if ~strcmp(answer,'Yes')
[682]355    GeometryCalib=[];
356    index=1;
[569]357    return
[2]358end
[569]359if strcmp(calib_cell{val}(1:2),'3D')%set the plane position for 3D (projection) calibration
360    input_key={'Z (first position)','Z (last position)','Z (water surface)', 'refractive index','NbSlice','volume scan (y/n)','tilt angle y axis','tilt angle x axis'};
361    input_val=[{num2str(ZEnd)} {num2str(ZStart)} {num2str(ZStart)} {'1.333'} num2str(NbSlice_j) {volume_scan} {'0'} {'0'}];
362    answer=inputdlg(input_key,'slice position(s)',ones(1,8), input_val,'on');
363    GeometryCalib.NbSlice=str2double(answer{5});
364    GeometryCalib.VolumeScan=answer{6};
365    if isempty(answer)
366        Z_plane=0; %default
367    else
368        Z_plane=linspace(str2double(answer{1}),str2double(answer{2}),GeometryCalib.NbSlice);
[114]369    end
[569]370    GeometryCalib.SliceCoord=Z_plane'*[0 0 1];
371    GeometryCalib.SliceAngle(:,3)=0;
372    GeometryCalib.SliceAngle(:,2)=str2double(answer{7})*ones(GeometryCalib.NbSlice,1);%rotation around y axis (to generalise)
373    GeometryCalib.SliceAngle(:,1)=str2double(answer{8})*ones(GeometryCalib.NbSlice,1);%rotation around x axis (to generalise)
374    GeometryCalib.InterfaceCoord=[0 0 str2double(answer{3})];
375    GeometryCalib.RefractionIndex=str2double(answer{4});
[114]376end
[128]377
[114]378
379
[60]380%------------------------------------------------------------------------
[2]381% determine the parameters for a calibration by an affine function (rescaling and offset, no rotation)
[109]382function GeometryCalib=calib_rescale(Coord,handles)
[60]383%------------------------------------------------------------------------
[2]384X=Coord(:,1);
[109]385Y=Coord(:,2);% Z not used
[2]386x_ima=Coord(:,4);
387y_ima=Coord(:,5);
[341]388[px]=polyfit(X,x_ima,1);
389[py]=polyfit(Y,y_ima,1);
390% T_x=px(2);
391% T_y=py(2);
[2]392GeometryCalib.CalibrationType='rescale';
[121]393GeometryCalib.fx_fy=[px(1) py(1)];%.fx_fy corresponds to pxcm along x and y
[2]394GeometryCalib.CoordUnit=[];% default value, to be updated by the calling function
[114]395GeometryCalib.Tx_Ty_Tz=[px(2)/px(1) py(2)/py(1) 1];
396GeometryCalib.omc=[0 0 0];
[2]397
[60]398%------------------------------------------------------------------------
[2]399% determine the parameters for a calibration by a linear transform matrix (rescale and rotation)
[242]400
401
[227]402function GeometryCalib=calib_linear(Coord,handles)
[60]403%------------------------------------------------------------------------
[2]404X=Coord(:,1);
[109]405Y=Coord(:,2);% Z not used
[2]406x_ima=Coord(:,4);
407y_ima=Coord(:,5);
408XY_mat=[ones(size(X)) X Y];
409a_X1=XY_mat\x_ima; %transformation matrix for X
410a_Y1=XY_mat\y_ima;%transformation matrix for X
[121]411R=[a_X1(2),a_X1(3);a_Y1(2),a_Y1(3)];
[242]412epsilon=sign(det(R));
[116]413norm=abs(det(R));
[2]414GeometryCalib.CalibrationType='linear';
[238]415if (a_X1(2)/a_Y1(3))>0
[242]416    GeometryCalib.fx_fy(1)=sqrt((a_X1(2)/a_Y1(3))*norm);
[238]417else
[242]418    GeometryCalib.fx_fy(1)=-sqrt(-(a_X1(2)/a_Y1(3))*norm);
[238]419end
[121]420GeometryCalib.fx_fy(2)=(a_Y1(3)/a_X1(2))*GeometryCalib.fx_fy(1);
[2]421GeometryCalib.CoordUnit=[];% default value, to be updated by the calling function
[227]422GeometryCalib.Tx_Ty_Tz=[a_X1(1)/GeometryCalib.fx_fy(1) a_Y1(1)/GeometryCalib.fx_fy(2) 1];
[242]423R(1,:)=R(1,:)/GeometryCalib.fx_fy(1);
[121]424R(2,:)=R(2,:)/GeometryCalib.fx_fy(2);
425R=[R;[0 0]];
[242]426GeometryCalib.R=[R [0;0;-epsilon]];
427GeometryCalib.omc=(180/pi)*[acos(GeometryCalib.R(1,1)) 0 0];
[569]428
[109]429%------------------------------------------------------------------------
430% determine the tsai parameters for a view normal to the grid plane
[114]431% NOT USED
[109]432function GeometryCalib=calib_normal(Coord,handles)
433%------------------------------------------------------------------------
434Calib.f1=str2num(get(handles.fx,'String'));
435Calib.f2=str2num(get(handles.fy,'String'));
[114]436Calib.k=str2num(get(handles.kc,'String'));
[109]437Calib.Cx=str2num(get(handles.Cx,'String'));
438Calib.Cy=str2num(get(handles.Cy,'String'));
439%default
440if isempty(Calib.f1)
441    Calib.f1=25/0.012;
442end
443if isempty(Calib.f2)
444    Calib.f2=25/0.012;
445end
446if isempty(Calib.k)
447    Calib.k=0;
448end
449if isempty(Calib.Cx)||isempty(Calib.Cy)
450    huvmat=findobj(allchild(0),'Tag','uvmat');
451    hhuvmat=guidata(huvmat);
[332]452    Calib.Cx=str2num(get(hhuvmat.num_Npx,'String'))/2;
453    Calib.Cx=str2num(get(hhuvmat.num_Npy,'String'))/2;
[109]454end   
455%tsai parameters
456Calib.dpx=0.012;%arbitrary
457Calib.dpy=0.012;
458Calib.sx=Calib.f1*Calib.dpx/(Calib.f2*Calib.dpy);
459Calib.f=Calib.f2*Calib.dpy;
460Calib.kappa1=Calib.k/(Calib.f*Calib.f);
[2]461
[109]462%initial guess
463X=Coord(:,1);
464Y=Coord(:,2);
465Zmean=mean(Coord(:,3));
466x_ima=Coord(:,4)-Calib.Cx;
467y_ima=Coord(:,5)-Calib.Cy;
468XY_mat=[ones(size(X)) X Y];
469a_X1=XY_mat\x_ima; %transformation matrix for X
470a_Y1=XY_mat\y_ima;%transformation matrix for Y
471R=[a_X1(2),a_X1(3),0;a_Y1(2),a_Y1(3),0;0,0,-1];% rotation+ z axis reversal (upward)
472norm=sqrt(det(-R));
473calib_param(1)=0;% quadratic distortion
474calib_param(2)=a_X1(1);
475calib_param(3)=a_Y1(1);
476calib_param(4)=Calib.f/(norm*Calib.dpx)-R(3,3)*Zmean;
[121]477calib_param(5)=angle(a_X1(2)+1i*a_X1(3));
[109]478display(['initial guess=' num2str(calib_param)])
479
480%optimise the parameters: minimisation of error
[121]481calib_param = fminsearch(@(calib_param) error_calib(calib_param,Calib,Coord),calib_param);
[109]482
483GeometryCalib.CalibrationType='tsai_normal';
484GeometryCalib.focal=Calib.f;
485GeometryCalib.dpx_dpy=[Calib.dpx Calib.dpy];
486GeometryCalib.Cx_Cy=[Calib.Cx Calib.Cy];
487GeometryCalib.sx=Calib.sx;
488GeometryCalib.kappa1=calib_param(1);
489GeometryCalib.CoordUnit=[];% default value, to be updated by the calling function
490GeometryCalib.Tx_Ty_Tz=[calib_param(2) calib_param(3) calib_param(4)];
491alpha=calib_param(5);
492GeometryCalib.R=[cos(alpha) sin(alpha) 0;-sin(alpha) cos(alpha) 0;0 0 -1];
493
[60]494%------------------------------------------------------------------------
[109]495function GeometryCalib=calib_3D_linear(Coord,handles)
[69]496%------------------------------------------------------------------
497path_uvmat=which('uvmat');% check the path detected for source file uvmat
498path_UVMAT=fileparts(path_uvmat); %path to UVMAT
[78]499huvmat=findobj(allchild(0),'Tag','uvmat');
500hhuvmat=guidata(huvmat);
[660]501coord_files=get(handles.ListCoordFiles,'String');
[121]502if ischar(coord_files)
503    coord_files={coord_files};
504end
505if isempty(coord_files{1}) || isequal(coord_files,{''})
506    coord_files={};
507end
[660]508%retrieve the calibration points stored in the files listed in the popup list ListCoordFiles
[121]509x_1=Coord(:,4:5)';%px coordinates of the ref points
[332]510nx=str2num(get(hhuvmat.num_Npx,'String'));
511ny=str2num(get(hhuvmat.num_Npy,'String'));
[121]512x_1(2,:)=ny-x_1(2,:);%reverse the y image coordinates
513X_1=Coord(:,1:3)';%phys coordinates of the ref points
514n_ima=numel(coord_files)+1;
515if ~isempty(coord_files)
516    msgbox_uvmat('CONFIRMATION',['The xy coordinates of the calibration points in ' num2str(n_ima) ' planes will be used'])
517    for ifile=1:numel(coord_files)
518    t=xmltree(coord_files{ifile});
519    s=convert(t);%convert to matlab structure
520        if isfield(s,'GeometryCalib')
521            if isfield(s.GeometryCalib,'SourceCalib')
522                if isfield(s.GeometryCalib.SourceCalib,'PointCoord')
523                PointCoord=s.GeometryCalib.SourceCalib.PointCoord;
524                Coord_file=zeros(length(PointCoord),5);%default
525                for i=1:length(PointCoord)
526                    line=str2num(PointCoord{i});
527                    Coord_file(i,4:5)=line(4:5);%px x
528                    Coord_file(i,1:3)=line(1:3);%phys x
529                end
530                eval(['x_' num2str(ifile+1) '=Coord_file(:,4:5)'';']);
531                eval(['x_' num2str(ifile+1) '(2,:)=ny-x_' num2str(ifile+1) '(2,:);' ]);
532                eval(['X_' num2str(ifile+1) '=Coord_file(:,1:3)'';']);
533                end
534            end
535        end
536    end
537end
538n_ima=numel(coord_files)+1;
[109]539est_dist=[0;0;0;0;0];
540est_aspect_ratio=0;
541est_fc=[1;1];
542%fc=[25;25]/0.012;
543center_optim=0;
544run(fullfile(path_UVMAT,'toolbox_calib','go_calib_optim'));
545GeometryCalib.CalibrationType='3D_linear';
[121]546GeometryCalib.fx_fy=fc';
547%GeometryCalib.focal=fc(2);
548%GeometryCalib.dpx_dpy=[1 1];
[109]549GeometryCalib.Cx_Cy=cc';
[121]550%GeometryCalib.sx=fc(1)/fc(2);
551GeometryCalib.kc=kc(1);
552%GeometryCalib.kappa1=-kc(1)/fc(2)^2;
[109]553GeometryCalib.CoordUnit=[];% default value, to be updated by the calling function
554GeometryCalib.Tx_Ty_Tz=Tc_1';
555GeometryCalib.R=Rc_1;
[121]556GeometryCalib.R(2,1:3)=-GeometryCalib.R(2,1:3);%inversion of the y image coordinate
557GeometryCalib.Tx_Ty_Tz(2)=-GeometryCalib.Tx_Ty_Tz(2);%inversion of the y image coordinate
558GeometryCalib.Cx_Cy(2)=ny-GeometryCalib.Cx_Cy(2);%inversion of the y image coordinate
559GeometryCalib.omc=(180/pi)*omc_1;%angles in degrees
560GeometryCalib.ErrorRMS=[];
561GeometryCalib.ErrorMax=[];
[109]562
563%------------------------------------------------------------------------
564function GeometryCalib=calib_3D_quadr(Coord,handles)
565%------------------------------------------------------------------
566
567path_uvmat=which('uvmat');% check the path detected for source file uvmat
568path_UVMAT=fileparts(path_uvmat); %path to UVMAT
569huvmat=findobj(allchild(0),'Tag','uvmat');
570hhuvmat=guidata(huvmat);
571% check_cond=0;
[660]572coord_files=get(handles.ListCoordFiles,'String');
[109]573if ischar(coord_files)
574    coord_files={coord_files};
575end
576if isempty(coord_files{1}) || isequal(coord_files,{''})
577    coord_files={};
578end
579
[660]580%retrieve the calibration points stored in the files listed in the popup list ListCoordFiles
[114]581x_1=Coord(:,4:5)';%px coordinates of the ref points
[332]582nx=str2num(get(hhuvmat.num_Npx,'String'));
583ny=str2num(get(hhuvmat.num_Npy,'String'));
[114]584x_1(2,:)=ny-x_1(2,:);%reverse the y image coordinates
585X_1=Coord(:,1:3)';%phys coordinates of the ref points
[109]586n_ima=numel(coord_files)+1;
587if ~isempty(coord_files)
588    msgbox_uvmat('CONFIRMATION',['The xy coordinates of the calibration points in ' num2str(n_ima) ' planes will be used'])
589    for ifile=1:numel(coord_files)
590    t=xmltree(coord_files{ifile});
591    s=convert(t);%convert to matlab structure
592        if isfield(s,'GeometryCalib')
593            if isfield(s.GeometryCalib,'SourceCalib')
594                if isfield(s.GeometryCalib.SourceCalib,'PointCoord')
595                PointCoord=s.GeometryCalib.SourceCalib.PointCoord;
[121]596                Coord_file=zeros(length(PointCoord),5);%default
[109]597                for i=1:length(PointCoord)
598                    line=str2num(PointCoord{i});
599                    Coord_file(i,4:5)=line(4:5);%px x
600                    Coord_file(i,1:3)=line(1:3);%phys x
601                end
602                eval(['x_' num2str(ifile+1) '=Coord_file(:,4:5)'';']);
[114]603                eval(['x_' num2str(ifile+1) '(2,:)=ny-x_' num2str(ifile+1) '(2,:);' ]);
[109]604                eval(['X_' num2str(ifile+1) '=Coord_file(:,1:3)'';']);
605                end
606            end
607        end
608    end
609end
610n_ima=numel(coord_files)+1;
[108]611est_dist=[1;0;0;0;0];
[109]612est_aspect_ratio=1;
613%est_fc=[0;0];
614%fc=[25;25]/0.012;
615center_optim=0;
[83]616run(fullfile(path_UVMAT,'toolbox_calib','go_calib_optim'));
[69]617
[109]618GeometryCalib.CalibrationType='3D_quadr';
[114]619GeometryCalib.fx_fy=fc';
620%GeometryCalib.focal=fc(2);
621%GeometryCalib.dpx_dpy=[1 1];
[69]622GeometryCalib.Cx_Cy=cc';
[114]623%GeometryCalib.sx=fc(1)/fc(2);
624GeometryCalib.kc=kc(1);
625%GeometryCalib.kappa1=-kc(1)/fc(2)^2;
[69]626GeometryCalib.CoordUnit=[];% default value, to be updated by the calling function
627GeometryCalib.Tx_Ty_Tz=Tc_1';
628GeometryCalib.R=Rc_1;
[114]629GeometryCalib.R(2,1:3)=-GeometryCalib.R(2,1:3);%inversion of the y image coordinate
630GeometryCalib.Tx_Ty_Tz(2)=-GeometryCalib.Tx_Ty_Tz(2);%inversion of the y image coordinate
631GeometryCalib.Cx_Cy(2)=ny-GeometryCalib.Cx_Cy(2);%inversion of the y image coordinate
632GeometryCalib.omc=(180/pi)*omc_1;%angles in degrees
[109]633GeometryCalib.ErrorRMS=[];
634GeometryCalib.ErrorMax=[];
[69]635
[109]636
[60]637%------------------------------------------------------------------------
[109]638function GeometryCalib=calib_3D_extrinsic(Coord,handles)
639%------------------------------------------------------------------
640path_uvmat=which('geometry_calib');% check the path detected for source file uvmat
641path_UVMAT=fileparts(path_uvmat); %path to UVMAT
[116]642x_1=double(Coord(:,4:5)');%image coordiantes
643X_1=double(Coord(:,1:3)');% phys coordinates
[114]644huvmat=findobj(allchild(0),'Tag','uvmat');
645hhuvmat=guidata(huvmat);
[332]646ny=str2double(get(hhuvmat.num_Npy,'String'));
[114]647x_1(2,:)=ny-x_1(2,:);%reverse the y image coordinates
[109]648n_ima=1;
[114]649GeometryCalib.CalibrationType='3D_extrinsic';
650GeometryCalib.fx_fy(1)=str2num(get(handles.fx,'String'));
651GeometryCalib.fx_fy(2)=str2num(get(handles.fy,'String'));
652GeometryCalib.Cx_Cy(1)=str2num(get(handles.Cx,'String'));
653GeometryCalib.Cx_Cy(2)=str2num(get(handles.Cy,'String'));
654GeometryCalib.kc=str2num(get(handles.kc,'String'));
[109]655fct_path=fullfile(path_UVMAT,'toolbox_calib');
656addpath(fct_path)
[116]657GeometryCalib.Cx_Cy(2)=ny-GeometryCalib.Cx_Cy(2);%reverse Cx_Cy(2) for calibration (inversion of px ordinate)
[109]658% [omc1,Tc1,Rc1,H,x,ex,JJ] = compute_extrinsic(x_1,X_1,...
659%     [Calib.f Calib.f*Calib.sx]',...
660%     [Calib.Cx Calib.Cy]',...
661%     [-Calib.kappa1*Calib.f^2 0 0 0 0]);
[114]662[omc,Tc1,Rc1,H,x,ex,JJ] = compute_extrinsic(x_1,X_1,...
[116]663    (GeometryCalib.fx_fy)',GeometryCalib.Cx_Cy',[GeometryCalib.kc 0 0 0 0]);
[109]664rmpath(fct_path);
665GeometryCalib.CoordUnit=[];% default value, to be updated by the calling function
666GeometryCalib.Tx_Ty_Tz=Tc1';
667%inversion of z axis
668GeometryCalib.R=Rc1;
[114]669GeometryCalib.R(2,1:3)=-GeometryCalib.R(2,1:3);%inversion of the y image coordinate
670GeometryCalib.Tx_Ty_Tz(2)=-GeometryCalib.Tx_Ty_Tz(2);%inversion of the y image coordinate
[116]671GeometryCalib.Cx_Cy(2)=ny-GeometryCalib.Cx_Cy(2);%inversion of the y image coordinate
[114]672GeometryCalib.omc=(180/pi)*omc';
[109]673%GeometryCalib.R(3,1:3)=-GeometryCalib.R(3,1:3);%inversion for z upward
674
675
[116]676
[109]677%------------------------------------------------------------------------
678%function GeometryCalib=calib_tsai_heikkila(Coord)
679% TEST: NOT IMPLEMENTED
680%------------------------------------------------------------------
681% path_uvmat=which('uvmat');% check the path detected for source file uvmat
682% path_UVMAT=fileparts(path_uvmat); %path to UVMAT
683% path_calib=fullfile(path_UVMAT,'toolbox_calib_heikkila');
684% addpath(path_calib)
685% npoints=size(Coord,1);
686% Coord(:,1:3)=10*Coord(:,1:3);
687% Coord=[Coord zeros(npoints,2) -ones(npoints,1)];
688% [par,pos,iter,res,er,C]=cacal('dalsa',Coord);
689% GeometryCalib.CalibrationType='tsai';
690% GeometryCalib.focal=par(2);
691
692
693%------------------------------------------------------------------------
694% --- determine the rms of calibration error
695function ErrorRms=error_calib(calib_param,Calib,Coord)
696%calib_param: vector of free calibration parameters (to optimise)
697%Calib: structure of the given calibration parameters
698%Coord: list of phys coordinates (columns 1-3, and pixel coordinates (columns 4-5)
699Calib.f=25;
700Calib.dpx=0.012;
701Calib.dpy=0.012;
702Calib.sx=1;
703Calib.Cx=512;
704Calib.Cy=512;
705Calib.kappa1=calib_param(1);
706Calib.Tx=calib_param(2);
707Calib.Ty=calib_param(3);
708Calib.Tz=calib_param(4);
709alpha=calib_param(5);
710Calib.R=[cos(alpha) sin(alpha) 0;-sin(alpha) cos(alpha) 0;0 0 -1];
[2]711
[109]712X=Coord(:,1);
713Y=Coord(:,2);
714Z=Coord(:,3);
715x_ima=Coord(:,4);
716y_ima=Coord(:,5);
717[Xpoints,Ypoints]=px_XYZ(Calib,X,Y,Z);
718ErrorRms(1)=sqrt(mean((Xpoints-x_ima).*(Xpoints-x_ima)));
719ErrorRms(2)=sqrt(mean((Ypoints-y_ima).*(Ypoints-y_ima)));
720ErrorRms=mean(ErrorRms);
721
[671]722% %------------------------------------------------------------------------
723% function XImage_Callback(hObject, eventdata, handles)
724% %------------------------------------------------------------------------
725% update_list(hObject, eventdata,handles)
726%
727% %------------------------------------------------------------------------
728% function YImage_Callback(hObject, eventdata, handles)
729% %------------------------------------------------------------------------
730% update_list(hObject, eventdata,handles)
[2]731
[60]732%------------------------------------------------------------------------
[109]733% --- Executes on button press in STORE.
734function STORE_Callback(hObject, eventdata, handles)
[657]735Coord=get(handles.ListCoord,'Data');
736%Object=read_geometry_calib(Coord_cell);
[109]737unitlist=get(handles.CoordUnit,'String');
738unit=unitlist{get(handles.CoordUnit,'value')};
739GeometryCalib.CoordUnit=unit;
[657]740GeometryCalib.SourceCalib.PointCoord=Coord(:,1:5);
[109]741huvmat=findobj(allchild(0),'Name','uvmat');
742hhuvmat=guidata(huvmat);%handles of elements in the GUI uvmat
[128]743% RootPath='';
744% RootFile='';
[121]745if ~isempty(hhuvmat.RootPath)&& ~isempty(hhuvmat.RootFile)
[341]746%     testhandle=1;
[109]747    RootPath=get(hhuvmat.RootPath,'String');
748    RootFile=get(hhuvmat.RootFile,'String');
749    filebase=fullfile(RootPath,RootFile);
750    while exist([filebase '.xml'],'file')
751        filebase=[filebase '~'];
752    end
753    outputfile=[filebase '.xml'];
[630]754    errormsg=update_imadoc(GeometryCalib,outputfile,'GeometryCalib');
[114]755    if ~strcmp(errormsg,'')
756        msgbox_uvmat('ERROR',errormsg);
757    end
[660]758    listfile=get(handles.ListCoordFiles,'string');
[109]759    if isequal(listfile,{''})
760        listfile={outputfile};
761    else
[128]762        listfile=[listfile;{outputfile}];%update the list of coord files
[109]763    end
[660]764    set(handles.ListCoordFiles,'string',listfile);
[109]765end
[657]766set(handles.ListCoord,'Data',[])
[109]767
[114]768% --------------------------------------------------------------------
769% --- Executes on button press in CLEAR_PTS: clear the list of calibration points
770function CLEAR_PTS_Callback(hObject, eventdata, handles)
771% --------------------------------------------------------------------
[657]772set(handles.ListCoord,'Data',[])
[654]773PLOT_Callback(hObject, eventdata, handles)
[114]774
[109]775%------------------------------------------------------------------------
776% --- Executes on button press in CLEAR.
777function CLEAR_Callback(hObject, eventdata, handles)
778%------------------------------------------------------------------------
[660]779set(handles.ListCoordFiles,'Value',1)
780set(handles.ListCoordFiles,'String',{''})
[109]781
782%------------------------------------------------------------------------
[660]783% --- Executes on selection change in CheckEnableMouse.
784function CheckEnableMouse_Callback(hObject, eventdata, handles)
[60]785%------------------------------------------------------------------------
[660]786choice=get(handles.CheckEnableMouse,'Value');
[78]787if choice
[660]788    set(handles.CheckEnableMouse,'BackgroundColor',[1 1 0])
[177]789    huvmat=findobj(allchild(0),'tag','uvmat');
790    if ishandle(huvmat)
791        hhuvmat=guidata(huvmat);
[657]792        if get(hhuvmat.CheckEditObject,'Value')
793        set(hhuvmat.CheckEditObject,'Value',0)
794        uvmat('CheckEditObject_Callback',hhuvmat.CheckEditObject,[],hhuvmat)
795        end
[177]796    end
[78]797else
[660]798    set(handles.CheckEnableMouse,'BackgroundColor',[0.7 0.7 0.7])
[2]799end
800
[541]801
[2]802% --------------------------------------------------------------------
803function MenuHelp_Callback(hObject, eventdata, handles)
[116]804path_to_uvmat=which('uvmat');% check the path of uvmat
[2]805pathelp=fileparts(path_to_uvmat);
[116]806helpfile=fullfile(pathelp,'uvmat_doc','uvmat_doc.html');
[36]807if isempty(dir(helpfile)), msgbox_uvmat('ERROR','Please put the help file uvmat_doc.html in the sub-directory /uvmat_doc of the UVMAT package')
[2]808else
[36]809   addpath (fullfile(pathelp,'uvmat_doc'))
[2]810   web([helpfile '#geometry_calib'])
811end
812
[654]813% --------------------------------------------------------------------
814function MenuSetScale_Callback(hObject, eventdata, handles)
[682]815
816 answer=msgbox_uvmat('INPUT_TXT','scale pixel/cm?','');
[654]817 %create test points
818 huvmat=findobj(allchild(0),'Name','uvmat');%find the current uvmat interface handle
819UvData=get(huvmat,'UserData');%Data associated to the current uvmat interface
[655]820npy=size(UvData.Field.A,1);
821npx=size(UvData.Field.A,2);
822Xima=[0.25*npx 0.75*npx 0.75*npx 0.25*npx]';
823Yima=[0.25*npy 0.25*npy 0.75*npy 0.75*npy]';
[654]824x=Xima/str2num(answer);
825y=Yima/str2num(answer);
[657]826Coord=[x y zeros(4,1) Xima Yima zeros(4,1)];
827set(handles.ListCoord,'Data',Coord)
[682]828set(handles.APPLY,'BackgroundColor',[1 0 1])
[654]829
[17]830%------------------------------------------------------------------------
[2]831function MenuCreateGrid_Callback(hObject, eventdata, handles)
[17]832%------------------------------------------------------------------------
[61]833CalibData=get(handles.geometry_calib,'UserData');
[12]834Tinput=[];%default
835if isfield(CalibData,'grid')
836    Tinput=CalibData.grid;
837end
[71]838[T,CalibData.grid]=create_grid(Tinput);%display the GUI create_grid
[61]839set(handles.geometry_calib,'UserData',CalibData)
[2]840
[12]841%grid in phys space
[660]842Coord=get(handles.ListCoord,'Data');
843Coord(1:size(T,1),1:3)=T;%update the existing list of phys coordinates from the GUI create_grid
844set(handles.ListCoord,'Data',Coord)
[682]845set(handles.APPLY,'BackgroundColor',[1 0 1])
[17]846
[71]847% -----------------------------------------------------------------------
848% --- automatic grid dectection from local maxima of the images
[60]849function MenuDetectGrid_Callback(hObject, eventdata, handles)
[71]850%------------------------------------------------------------------------
[159]851%% read the four last point coordinates in pixels
[660]852Coord=get(handles.ListCoord,'Data');%read list of coordinates on geometry_calib
853nbpoints=size(Coord,1); %nbre of calibration points
[62]854if nbpoints~=4
[227]855    msgbox_uvmat('ERROR','four points must have be selected by the mouse to delimitate the phys grid area; the Ox axis will be defined by the two first points')
[71]856    return
[60]857end
[660]858corners_X=(Coord(end:-1:end-3,4)); %pixel absissa of the four corners
859corners_Y=(Coord(end:-1:end-3,5));
[60]860
[71]861%reorder the last two points (the two first in the list) if needed
[121]862angles=angle((corners_X-corners_X(1))+1i*(corners_Y-corners_Y(1)));
[62]863if abs(angles(4)-angles(2))>abs(angles(3)-angles(2))
864      X_end=corners_X(4);
865      Y_end=corners_Y(4);
866      corners_X(4)=corners_X(3);
867      corners_Y(4)=corners_Y(3);
868      corners_X(3)=X_end;
869      corners_Y(3)=Y_end;
870end
871
[227]872%% initiate the grid
873CalibData=get(handles.geometry_calib,'UserData');%get information stored on the GUI geometry_calib
874grid_input=[];%default
875if isfield(CalibData,'grid')
876    grid_input=CalibData.grid;%retrieve the previously used grid
877end
878[T,CalibData.grid,white_test]=create_grid(grid_input,'detect_grid');%display the GUI create_grid, read the set of phys coordinates T
879set(handles.geometry_calib,'UserData',CalibData)%store the phys grid parameters for later use
880
[159]881%% read the current image, displayed in the GUI uvmat
[60]882huvmat=findobj(allchild(0),'Name','uvmat');
883UvData=get(huvmat,'UserData');
[693]884A=UvData.Field.A;%currently displayed image
[60]885npxy=size(A);
[159]886X=[CalibData.grid.x_0 CalibData.grid.x_1 CalibData.grid.x_0 CalibData.grid.x_1]';%corner absissa in the phys coordinates (cm)
887Y=[CalibData.grid.y_0 CalibData.grid.y_0 CalibData.grid.y_1 CalibData.grid.y_1]';%corner ordinates in the phys coordinates (cm)
[109]888
[693]889%calculate transform matrices for plane projection: rectangle assumed to be viewed in perspective
[108]890% reference: http://alumni.media.mit.edu/~cwren/interpolator/ by Christopher R. Wren
891B = [ X Y ones(size(X)) zeros(4,3)        -X.*corners_X -Y.*corners_X ...
892      zeros(4,3)        X Y ones(size(X)) -X.*corners_Y -Y.*corners_Y ];
893B = reshape (B', 8 , 8 )';
894D = [ corners_X , corners_Y ];
895D = reshape (D', 8 , 1 );
[121]896l = (B' * B)\B' * D;
[108]897Amat = reshape([l(1:6)' 0 0 1 ],3,3)';
898C = [l(7:8)' 1];
899
[159]900% transform grid image into 'phys' coordinates
[693]901GeometryCalib.CalibrationType='3D_linear';
[114]902GeometryCalib.fx_fy=[1 1];
903GeometryCalib.Tx_Ty_Tz=[Amat(1,3) Amat(2,3) 1];
[108]904GeometryCalib.R=[Amat(1,1),Amat(1,2),0;Amat(2,1),Amat(2,2),0;C(1),C(2),0];
[159]905GeometryCalib.CoordUnit='cm';
[114]906path_uvmat=which('uvmat');% check the path detected for source file uvmat
907path_UVMAT=fileparts(path_uvmat); %path to UVMAT
908addpath(fullfile(path_UVMAT,'transform_field'))
909Data.ListVarName={'AY','AX','A'};
910Data.VarDimName={'AY','AX',{'AY','AX'}};
911if ndims(A)==3
912    A=mean(A,3);
913end
914Data.A=A-min(min(A));
915Data.AY=[npxy(1)-0.5 0.5];
916Data.AX=[0.5 npxy(2)];
[158]917Data.CoordUnit='pixel';
[114]918Calib.GeometryCalib=GeometryCalib;
[121]919DataOut=phys(Data,Calib);
[114]920rmpath(fullfile(path_UVMAT,'transform_field'))
[693]921Amod=DataOut.A;% current imgage expressed in 'phys' coord
[114]922Rangx=DataOut.AX;
923Rangy=DataOut.AY;
[156]924if white_test
[159]925    Amod=double(Amod);%case of white grid markers: will look for image maxima
[156]926else
[159]927    Amod=-double(Amod);%case of black grid markers: will look for image minima
[156]928end
[114]929% figure(12) %display corrected image
[109]930% Amax=max(max(Amod));
931% image(Rangx,Rangy,uint8(255*Amod/Amax))
[114]932
[159]933%% detection of local image extrema in each direction
[88]934Dx=(Rangx(2)-Rangx(1))/(npxy(2)-1); %x mesh in real space
935Dy=(Rangy(2)-Rangy(1))/(npxy(1)-1); %y mesh in real space
[121]936ind_range_x=ceil(abs(GeometryCalib.R(1,1)*CalibData.grid.Dx/3));% range of search of image ma around each point obtained by linear interpolation from the marked points
937ind_range_y=ceil(abs(GeometryCalib.R(2,2)*CalibData.grid.Dy/3));% range of search of image ma around each point obtained by linear interpolation from the marked points
[60]938nbpoints=size(T,1);
[693]939%lokk for image maxima around each expected pgrid point
[60]940for ipoint=1:nbpoints
941    i0=1+round((T(ipoint,1)-Rangx(1))/Dx);%round(Xpx(ipoint));
942    j0=1+round((T(ipoint,2)-Rangy(1))/Dy);%round(Xpx(ipoint));
[109]943    j0min=max(j0-ind_range_y,1);
944    j0max=min(j0+ind_range_y,size(Amod,1));
945    i0min=max(i0-ind_range_x,1);
946    i0max=min(i0+ind_range_x,size(Amod,2));
947    Asub=Amod(j0min:j0max,i0min:i0max);
[60]948    x_profile=sum(Asub,1);
949    y_profile=sum(Asub,2);
950    [Amax,ind_x_max]=max(x_profile);
951    [Amax,ind_y_max]=max(y_profile);
[61]952    %sub-pixel improvement using moments
953    x_shift=0;
954    y_shift=0;
[109]955    if ind_x_max+2<=numel(x_profile) && ind_x_max-2>=1
[61]956        Atop=x_profile(ind_x_max-2:ind_x_max+2);
957        x_shift=sum(Atop.*[-2 -1 0 1 2])/sum(Atop);
958    end
[114]959    if ind_y_max+2<=numel(y_profile) && ind_y_max-2>=1
[61]960        Atop=y_profile(ind_y_max-2:ind_y_max+2);
961        y_shift=sum(Atop.*[-2 -1 0 1 2]')/sum(Atop);
962    end
[109]963    Delta(ipoint,1)=(x_shift+ind_x_max+i0min-i0-1)*Dx;%shift from the initial guess
964    Delta(ipoint,2)=(y_shift+ind_y_max+j0min-j0-1)*Dy;
[60]965end
[693]966Tmod=T(:,(1:2))+Delta;% 'phys' coordinates of the detected points
967Tmod(:,2)=flipdim(Tmod(:,2),1);% inverse the order of y coordinates
968[Xpx,Ypx]=px_XYZ(GeometryCalib,Tmod(:,1),Tmod(:,2));% image coordinates of the detected points
[660]969Coord=[T Xpx Ypx zeros(size(T,1),1)];
970set(handles.ListCoord,'Data',Coord)
[654]971PLOT_Callback(hObject, eventdata, handles)
[682]972set(handles.APPLY,'BackgroundColor',[1 0 1])
[60]973
[71]974%-----------------------------------------------------------------------
975function MenuTranslatePoints_Callback(hObject, eventdata, handles)
976%-----------------------------------------------------------------------
977%hcalib=get(handles.calib_type,'parent');%handles of the GUI geometry_calib
978CalibData=get(handles.geometry_calib,'UserData');
979Tinput=[];%default
980if isfield(CalibData,'translate')
981    Tinput=CalibData.translate;
982end
983T=translate_points(Tinput);%display translate_points GUI and get shift parameters
984CalibData.translate=T;
985set(handles.geometry_calib,'UserData',CalibData)
986%translation
[671]987Coord=get(handles.ListCoord,'Data');
988Coord(:,1)=T(1)+Coord(:,1);
989Coord(:,2)=T(2)+Coord(:,2);
990Coord(:,3)=T(3)+Coord(:,3);
991set(handles.ListCoord,'Data',Coord);
[682]992set(handles.APPLY,'BackgroundColor',[1 0 1])
[71]993
994% --------------------------------------------------------------------
995function MenuRotatePoints_Callback(hObject, eventdata, handles)
996%hcalib=get(handles.calib_type,'parent');%handles of the GUI geometry_calib
997CalibData=get(handles.geometry_calib,'UserData');
998Tinput=[];%default
999if isfield(CalibData,'rotate')
1000    Tinput=CalibData.rotate;
1001end
[356]1002T=rotate_points(Tinput);%display rotate_points GUI to introduce rotation parameters
[71]1003CalibData.rotate=T;
1004set(handles.geometry_calib,'UserData',CalibData)
1005%-----------------------------------------------------
1006%rotation
1007Phi=T(1);
1008O_x=0;%default
1009O_y=0;%default
1010if numel(T)>=2
1011    O_x=T(2);%default
1012end
1013if numel(T)>=3
1014    O_y=T(3);%default
1015end
[671]1016Coord=get(handles.ListCoord,'Data');
[71]1017r1=cos(pi*Phi/180);
1018r2=-sin(pi*Phi/180);
1019r3=sin(pi*Phi/180);
1020r4=cos(pi*Phi/180);
[671]1021x=Coord(:,1)-O_x;
1022y=Coord(:,2)-O_y;
1023Coord(:,1)=r1*x+r2*y;
1024Coord(:,2)=r3*x+r4*y;
1025set(handles.ListCoord,'Data',Coord)
[682]1026set(handles.APPLY,'BackgroundColor',[1 0 1])
[71]1027
[109]1028% --------------------------------------------------------------------
1029function MenuImportPoints_Callback(hObject, eventdata, handles)
[121]1030fileinput=browse_xml(hObject, eventdata, handles);
[109]1031if isempty(fileinput)
1032    return
1033end
1034[s,errormsg]=imadoc2struct(fileinput,'GeometryCalib');
1035GeometryCalib=s.GeometryCalib;
[657]1036Coord=GeometryCalib.SourceCalib.PointCoord;
[671]1037Coord=[Coord zeros(size(Coord,1),1)];
[657]1038set(handles.ListCoord,'Data',Coord)
[654]1039PLOT_Callback(handles.geometry_calib, [], handles)
[682]1040set(handles.APPLY,'BackgroundColor',[1 0 1])
[109]1041
1042% -----------------------------------------------------------------------
1043function MenuImportIntrinsic_Callback(hObject, eventdata, handles)
1044%------------------------------------------------------------------------
1045fileinput=browse_xml(hObject, eventdata, handles);
1046if isempty(fileinput)
1047    return
1048end
1049[s,errormsg]=imadoc2struct(fileinput,'GeometryCalib');
1050GeometryCalib=s.GeometryCalib;
[114]1051display_intrinsic(GeometryCalib,handles)
[109]1052
1053% -----------------------------------------------------------------------
1054function MenuImportAll_Callback(hObject, eventdata, handles)
1055%------------------------------------------------------------------------
[121]1056fileinput=browse_xml(hObject, eventdata, handles);
[109]1057if ~isempty(fileinput)
1058    loadfile(handles,fileinput)
1059end
1060
1061% -----------------------------------------------------------------------
1062% --- Executes on menubar option Import/Grid file: introduce previous grid files
1063function MenuGridFile_Callback(hObject, eventdata, handles)
1064% -----------------------------------------------------------------------
[121]1065inputfile=browse_xml(hObject, eventdata, handles);
[671]1066listfile=get(handles.ListCoordFiles,'String');
[109]1067if isequal(listfile,{''})
1068    listfile={inputfile};
1069else
[121]1070    listfile=[listfile;{inputfile}];%update the list of coord files
[109]1071end
[660]1072set(handles.ListCoordFiles,'string',listfile);
[109]1073
[114]1074
1075%------------------------------------------------------------------------
[109]1076function fileinput=browse_xml(hObject, eventdata, handles)
1077%------------------------------------------------------------------------
1078fileinput=[];%default
1079oldfile=''; %default
[116]1080UserData=get(handles.geometry_calib,'UserData');
[114]1081if isfield(UserData,'XmlInputFile')
1082    oldfile=UserData.XmlInputFile;
[109]1083end
1084[FileName, PathName, filterindex] = uigetfile( ...
1085       {'*.xml;*.mat', ' (*.xml,*.mat)';
1086       '*.xml',  '.xml files '; ...
1087        '*.mat',  '.mat matlab files '}, ...
1088        'Pick a file',oldfile);
1089fileinput=[PathName FileName];%complete file name
1090testblank=findstr(fileinput,' ');%look for blanks
1091if ~isempty(testblank)
1092    msgbox_uvmat('ERROR','forbidden input file name or path: no blank character allowed')
1093    return
1094end
1095sizf=size(fileinput);
1096if (~ischar(fileinput)||~isequal(sizf(1),1)),return;end
[114]1097UserData.XmlInputFile=fileinput;
[109]1098set(handles.geometry_calib,'UserData',UserData)%record current file foer further use of browser
1099
1100% -----------------------------------------------------------------------
[128]1101function Heading=loadfile(handles,fileinput)
[109]1102%------------------------------------------------------------------------
[128]1103Heading=[];%default
[565]1104[s,errormsg]=imadoc2struct(fileinput,'Heading','GeometryCalib');
[128]1105if ~isempty(errormsg)
[502]1106    msgbox_uvmat('ERROR',errormsg)
[128]1107    return
1108end
1109if ~isempty(s.Heading)
1110    Heading=s.Heading;
1111end
[682]1112
[116]1113GeometryCalib=s.GeometryCalib;
[114]1114fx=1;fy=1;Cx=0;Cy=0;kc=0; %default
1115CoordCell={};
1116Tabchar={};%default
1117val_cal=1;%default
1118if ~isempty(GeometryCalib)
1119    % choose the calibration option
1120    if isfield(GeometryCalib,'CalibrationType')
[682]1121        calib_list=get(handles.calib_type,'String');
1122        for ilist=1:numel(calib_list)
1123            if strcmp(calib_list{ilist},GeometryCalib.CalibrationType)
1124                val_cal=ilist;
1125                break
1126            end
1127        end
[114]1128    end
1129    display_intrinsic(GeometryCalib,handles)%intrinsic param
1130    %extrinsic param
1131    if isfield(GeometryCalib,'Tx_Ty_Tz')
1132        Tx_Ty_Tz=GeometryCalib.Tx_Ty_Tz;
1133        set(handles.Tx,'String',num2str(GeometryCalib.Tx_Ty_Tz(1),4))
1134        set(handles.Ty,'String',num2str(GeometryCalib.Tx_Ty_Tz(2),4))
1135        set(handles.Tz,'String',num2str(GeometryCalib.Tx_Ty_Tz(3),4))
1136    end
1137    if isfield(GeometryCalib,'omc')
1138        set(handles.Phi,'String',num2str(GeometryCalib.omc(1),4))
1139        set(handles.Theta,'String',num2str(GeometryCalib.omc(2),4))
1140        set(handles.Psi,'String',num2str(GeometryCalib.omc(3),4))
1141    end
[674]1142    if isfield(GeometryCalib,'SourceCalib')
[682]1143        calib=GeometryCalib.SourceCalib.PointCoord;
1144        Coord=[calib zeros(size(calib,1),1)];
1145        set(handles.ListCoord,'Data',Coord)
[674]1146    end
[654]1147    PLOT_Callback(handles.geometry_calib, [], handles)
[682]1148    set(handles.APPLY,'BackgroundColor',[1 0 1])
[109]1149end
[114]1150set(handles.calib_type,'Value',val_cal)
1151
[109]1152if isempty(CoordCell)% allow mouse action by default in the absence of input points
[660]1153    set(handles.CheckEnableMouse,'Value',1)
1154    set(handles.CheckEnableMouse,'BackgroundColor',[1 1 0])
[109]1155else % does not allow mouse action by default in the presence of input points
[660]1156    set(handles.CheckEnableMouse,'Value',0)
1157    set(handles.CheckEnableMouse,'BackgroundColor',[0.7 0.7 0.7])
[109]1158end
1159
[114]1160%------------------------------------------------------------------------
1161%---display calibration intrinsic parameters
1162function display_intrinsic(GeometryCalib,handles)
1163%------------------------------------------------------------------------
1164fx=[];
1165fy=[];
1166if isfield(GeometryCalib,'fx_fy')
1167    fx=GeometryCalib.fx_fy(1);
1168    fy=GeometryCalib.fx_fy(2);
1169end
1170Cx_Cy=[0 0];%default
1171if isfield(GeometryCalib,'Cx_Cy')
1172    Cx_Cy=GeometryCalib.Cx_Cy;
1173end
1174kc=0;
1175if isfield(GeometryCalib,'kc')
[121]1176    kc=GeometryCalib.kc; %* GeometryCalib.focal*GeometryCalib.focal;
[114]1177end
1178set(handles.fx,'String',num2str(fx,5))
1179set(handles.fy,'String',num2str(fy,5))
1180set(handles.Cx,'String',num2str(Cx_Cy(1),'%1.1f'))
1181set(handles.Cy,'String',num2str(Cx_Cy(2),'%1.1f'))
1182set(handles.kc,'String',num2str(kc,'%1.4f'))
[109]1183
1184
[507]1185% --- Executes when user attempts to close geometry_calib.
1186function geometry_calib_CloseRequestFcn(hObject, eventdata, handles)
1187
[674]1188delete(hObject); % closes the figure
[654]1189
1190%------------------------------------------------------------------------
1191% --- Executes on button press in PLOT.
1192%------------------------------------------------------------------------
1193function PLOT_Callback(hObject, eventdata, handles)
1194huvmat=findobj(allchild(0),'Name','uvmat');%find the current uvmat interface handle
1195hhuvmat=guidata(huvmat); %handles of GUI elements in uvmat
1196h_menu_coord=findobj(huvmat,'Tag','TransformName');
1197menu=get(h_menu_coord,'String');
1198choice=get(h_menu_coord,'Value');
1199if iscell(menu)
1200    option=menu{choice};
1201else
1202    option='px'; %default
1203end
[657]1204Coord=get(handles.ListCoord,'Data');
1205if ~isempty(Coord)
[654]1206    if isequal(option,'phys')
[657]1207        Coord_plot=Coord(:,1:3);
[654]1208    elseif isequal(option,'px')||isequal(option,'')
[657]1209        Coord_plot=Coord(:,4:5);
[654]1210    else
[657]1211        msgbox_uvmat('ERROR','the choice in menu_coord of uvmat must be blank, px or phys ')
[654]1212    end
1213end
1214
1215set(0,'CurrentFigure',huvmat)
1216set(huvmat,'CurrentAxes',hhuvmat.PlotAxes)
1217hh=findobj('Tag','calib_points');
[657]1218if  ~isempty(Coord) && isempty(hh)
1219    hh=line(Coord_plot(:,1),Coord_plot(:,2),'Color','m','Tag','calib_points','LineStyle','.','Marker','+');
1220elseif isempty(Coord)%empty list of points, suppress the plot
[654]1221    delete(hh)
1222else
[657]1223    set(hh,'XData',Coord_plot(:,1))
1224    set(hh,'YData',Coord_plot(:,2))
[654]1225end
[663]1226pause(.1)
1227figure(handles.geometry_calib)
[657]1228
[663]1229%------------------------------------------------------------------------
[674]1230% --- Executes on button press in Copy: display Coord on the Matlab work space
[663]1231%------------------------------------------------------------------------
1232function Copy_Callback(hObject, eventdata, handles)
[671]1233global Coord
[657]1234evalin('base','global Coord')%make CurData global in the workspace
[671]1235Coord=get(handles.ListCoord,'Data');
[657]1236display('coordinates of calibration points (phys,px,marker) :')
1237evalin('base','Coord') %display CurData in the workspace
1238commandwindow; %brings the Matlab command window to the front
[654]1239
[674]1240%------------------------------------------------------------------------
[657]1241% --- Executes when selected cell(s) is changed in ListCoord.
[674]1242%------------------------------------------------------------------------
[657]1243function ListCoord_CellSelectionCallback(hObject, eventdata, handles)
1244if ~isempty(eventdata.Indices)
[674]1245    iline=eventdata.Indices(1);% selected line number
1246    Data=get(handles.ListCoord,'Data');
1247    Data(:,6)=zeros(size(Data,1),1);
[693]1248    Data(iline,6)=-1;% mark the selected line
[674]1249    set(handles.ListCoord,'Data',Data)
1250    update_calib_marker(Data(iline,:))
1251end
[657]1252
[674]1253%------------------------------------------------------------------------
[657]1254% --- Executes when entered data in editable cell(s) in ListCoord.
[674]1255%------------------------------------------------------------------------
[657]1256function ListCoord_CellEditCallback(hObject, eventdata, handles)
1257
1258Input=str2num(eventdata.EditData);%pasted input
1259Coord=get(handles.ListCoord,'Data');
1260iline=eventdata.Indices(1);% selected line number
1261if size(Coord,1)<iline+numel(Input)
1262    Coord=[Coord ; zeros(iline+numel(Input)-size(Coord,1),6)];% append zeros to fit the new column
1263end
1264Coord(iline:iline+numel(Input)-1,eventdata.Indices(2))=Input';
1265set(handles.ListCoord,'Data',Coord)
1266PLOT_Callback(hObject, eventdata, handles)
1267
[674]1268%------------------------------------------------------------------------
1269% --- 'key_press_fcn:' function activated when a key is pressed on the keyboard
1270%------------------------------------------------------------------------
[682]1271function ListCoord_KeyPressFcn(hObject, eventdata, handles)
[680]1272xx=double(get(handles.geometry_calib,'CurrentCharacter'));%get the keyboard character
1273if ismember(xx,[30 31 127])% arrow upward, downward, or delete
[674]1274    Coord=get(handles.ListCoord,'Data');
[680]1275    ind=find(Coord(:,6));%find the marker '+' for line selection
[674]1276    Coord(:,6)=zeros(size(Coord,1),1);% desactivate the current line mark
1277    switch xx
1278        case 30 % arrow upward
1279            Coord(ind-1,6)=1;
1280        case 31% arrow downward
1281            Coord(ind+1,6)=1;
[680]1282        case 127% remove line
[674]1283            Coord(ind,:)=[];
[680]1284            PLOT_Callback(hObject,eventdata,handles)
[682]1285            set(handles.APPLY,'BackgroundColor',[1 0 1])
1286        otherwise
[674]1287    end
1288    set(handles.ListCoord,'Data',Coord);
[682]1289else
1290    set(handles.APPLY,'BackgroundColor',[1 0 1])
[674]1291end
1292
1293
1294%------------------------------------------------------------------------
1295% --- update the plot of calibration points
1296%------------------------------------------------------------------------
[657]1297function update_calib_marker(Coord)
1298%% update the plot on uvmat
1299huvmat=findobj(allchild(0),'Name','uvmat');%find the current uvmat interface handle
1300hplot=findobj(huvmat,'Tag','PlotAxes');%main plotting axis of uvmat
1301hhh=findobj(hplot,'Tag','calib_marker');
1302
1303h_menu_coord=findobj(huvmat,'Tag','TransformName');
1304menu=get(h_menu_coord,'String');
1305choice=get(h_menu_coord,'Value');
1306if iscell(menu)
1307    option=menu{choice};
1308else
1309    option='px'; %default
1310end
1311if isequal(option,'phys')
1312    XCoord=Coord(1);
1313    YCoord=Coord(2);
1314elseif isequal(option,'px')|| isequal(option,'')
1315    XCoord=Coord(4);
1316    YCoord=Coord(5);
1317else
1318    msgbox_uvmat('ERROR','the choice in menu_coord of uvmat must be blank, px or phys ')
1319end
1320if isempty(XCoord)||isempty(YCoord)
1321     if ~isempty(hhh)
1322        delete(hhh)%delete the circle marker
1323    end
1324    return
1325end
1326xlim=get(hplot,'XLim');
1327ylim=get(hplot,'YLim');
1328ind_range=max(abs(xlim(2)-xlim(1)),abs(ylim(end)-ylim(1)))/20;%defines the size of the circle marker
1329if isempty(hhh)
1330    set(0,'CurrentFig',huvmat)
1331    set(huvmat,'CurrentAxes',hplot)
1332    rectangle('Curvature',[1 1],...
1333              'Position',[XCoord-ind_range/2 YCoord-ind_range/2 ind_range ind_range],'EdgeColor','m',...
1334              'LineStyle','-','Tag','calib_marker');
1335else
1336    set(hhh,'Position',[XCoord-ind_range/2 YCoord-ind_range/2 ind_range ind_range])
1337end
[693]1338
1339%------------------------------------------------------------------------
1340% --- Executes on button press in ClearLine: remove the selected line in the table Coord
1341%------------------------------------------------------------------------
1342function ClearLine_Callback(hObject, eventdata, handles)
1343
1344Coord=get(handles.ListCoord,'Data');
1345ind=find(Coord(:,6));%find the marker '-' for line selection
1346if isempty(ind)
1347    msgbox_uvmat('WARNING','no line suppressed, select a line in the table')
1348else
1349    answer=msgbox_uvmat('INPUT_Y-N',['suppress line ' num2str(ind) '?']);
1350    if isequal(answer,'Yes')
1351Coord(:,6)=zeros(size(Coord,1),1);% desactivate the current line mark
1352Coord(ind,:)=[];
1353PLOT_Callback(hObject,eventdata,handles)
1354set(handles.APPLY,'BackgroundColor',[1 0 1])
1355set(handles.ListCoord,'Data',Coord);
1356    end
1357end
Note: See TracBrowser for help on using the repository browser.