source: trunk/src/geometry_calib.m @ 724

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