source: trunk/src/geometry_calib.m @ 238

Last change on this file since 238 was 238, checked in by sommeria, 10 years ago

various bug corrections

File size: 64.0 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 05-Oct-2010 13:47:00
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 && ischar(varargin{1}) && ~isempty(regexp(varargin{1},'_Callback','once'))
63    gui_State.gui_Callback = str2func(varargin{1});
64end
65
66if nargout
67    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
68else
69    gui_mainfcn(gui_State, varargin{:});
70end
71% End initialization code - DO NOT edit
72
73
74% --- Executes just before geometry_calib is made visible.
75%INPUT:
76%handles: handles of the geometry_calib interface elements
77% PlotHandles: set of handles of the elements contolling the plotting
78% parameters on the uvmat interface (obtained by 'get_plot_handle.m')
79%------------------------------------------------------------------------
80function geometry_calib_OpeningFcn(hObject, eventdata, handles,inputfile,pos)
81%------------------------------------------------------------------------
82% Choose default command line output for geometry_calib
83
84handles.output = hObject;
85
86% Update handles structure
87guidata(hObject, handles);
88set(hObject,'DeleteFcn',{@closefcn})%
89
90%set the position of the interface
91if exist('pos','var')&& length(pos)>=4
92%     %pos_gui=get(hObject,'Position');
93%     pos_gui(1)=pos(1);
94%     pos_gui(2)=pos(2);
95    set(hObject,'Position',pos);
96end
97
98%set menu of calibration options
99set(handles.calib_type,'String',{'rescale';'linear';'3D_linear';'3D_quadr';'3D_extrinsic'})
100inputxml='';
101if exist('inputfile','var')&& ~isempty(inputfile)
102    struct.XmlInputFile=inputfile;
103    [Pathsub,RootFile,field_count,str2,str_a,str_b,ext]=name2display(inputfile);
104    if ~strcmp(ext,'.xml')
105        inputfile=[fullfile(Pathsub,RootFile) '.xml'];%xml file corresponding to the input file
106    end
107    set(handles.ListCoord,'String',{'......'})
108    if exist(inputfile,'file')
109        Heading=loadfile(handles,inputfile);% load the point coordiantes existing in the xml file
110        if isfield(Heading,'Campaign')&& ischar(Heading.Campaign)
111            struct.Campaign=Heading.Campaign;
112        end
113    end   
114    set(hObject,'UserData',struct)
115end
116
117set(handles.ListCoord,'KeyPressFcn',{@key_press_fcn,handles})%set keyboard action function
118
119
120%------------------------------------------------------------------------
121% --- Outputs from this function are returned to the command line.
122function varargout = geometry_calib_OutputFcn(hObject, eventdata, handles)
123%------------------------------------------------------------------------
124% Get default command line output from handles structure
125varargout{1} = handles.output;
126varargout{2}=handles;
127%
128%------------------------------------------------------------------------
129% executed when closing: set the parent interface button to value 0
130function closefcn(gcbo,eventdata)
131%------------------------------------------------------------------------
132huvmat=findobj(allchild(0),'Name','uvmat');
133if ~isempty(huvmat)
134    handles=guidata(huvmat);
135%     set(handles.MenuMask,'enable','on')
136%     set(handles.MenuGrid,'enable','on')
137%     set(handles.MenuObject,'enable','on')
138%     set(handles.MenuEdit,'enable','on')
139%     set(handles.edit,'enable','on')
140    hobject=findobj(handles.axes3,'tag','calib_points');
141    if ~isempty(hobject)
142        delete(hobject)
143    end
144    hobject=findobj(handles.axes3,'tag','calib_marker');
145    if ~isempty(hobject)
146        delete(hobject)
147    end   
148end
149
150%------------------------------------------------------------------------
151% --- Executes on button press in calibrate_lin.
152function APPLY_Callback(hObject, eventdata, handles)
153%------------------------------------------------------------------------
154%read the current calibration points
155Coord_cell=get(handles.ListCoord,'String');
156Object=read_geometry_calib(Coord_cell);
157Coord=Object.Coord;
158% apply the calibration, whose type is selected in  handles.calib_type
159if ~isempty(Coord)
160    calib_cell=get(handles.calib_type,'String');
161    val=get(handles.calib_type,'Value');
162    GeometryCalib=feval(['calib_' calib_cell{val}],Coord,handles);
163else
164    msgbox_uvmat('ERROR','No calibration points, abort')
165    return
166end
167Z_plane=[];
168if ~isempty(Coord)
169    %check error
170    X=Coord(:,1);
171    Y=Coord(:,2);
172    Z=Coord(:,3);
173    x_ima=Coord(:,4);
174    y_ima=Coord(:,5);
175    [Xpoints,Ypoints]=px_XYZ(GeometryCalib,X,Y,Z);
176    GeometryCalib.ErrorRms(1)=sqrt(mean((Xpoints-x_ima).*(Xpoints-x_ima)));
177    [GeometryCalib.ErrorMax(1),index(1)]=max(abs(Xpoints-x_ima));
178    GeometryCalib.ErrorRms(2)=sqrt(mean((Ypoints-y_ima).*(Ypoints-y_ima)));
179    [GeometryCalib.ErrorMax(2),index(2)]=max(abs(Ypoints-y_ima));
180    [EM,ind_dim]=max(GeometryCalib.ErrorMax);
181    index=index(ind_dim);
182    %set the Z position of the reference plane used for calibration
183    if isequal(max(Z),min(Z))%Z constant
184        Z_plane=Z(1);
185        GeometryCalib.NbSlice=1;
186        GeometryCalib.SliceCoord=[0 0 Z_plane];
187    end
188end
189%set the coordinate unit
190unitlist=get(handles.CoordUnit,'String');
191unit=unitlist{get(handles.CoordUnit,'value')};
192GeometryCalib.CoordUnit=unit;
193%record the points
194GeometryCalib.SourceCalib.PointCoord=Coord;
195display_intrinsic(GeometryCalib,handles)%display calibration intrinsic parameters
196
197% Display extrinsinc parameters (rotation and translation of camera with  respect to the phys coordiantes)
198set(handles.Tx,'String',num2str(GeometryCalib.Tx_Ty_Tz(1),4))
199set(handles.Ty,'String',num2str(GeometryCalib.Tx_Ty_Tz(2),4))
200set(handles.Tz,'String',num2str(GeometryCalib.Tx_Ty_Tz(3),4))
201set(handles.Phi,'String',num2str(GeometryCalib.omc(1),4))
202set(handles.Theta,'String',num2str(GeometryCalib.omc(2),4))
203set(handles.Psi,'String',num2str(GeometryCalib.omc(3),4))
204
205% store the calibration data, by default in the xml file of the currently displayed image
206huvmat=findobj(allchild(0),'Name','uvmat');
207UvData=get(huvmat,'UserData');
208NbSlice_j=1;%default
209ZStart=Z_plane;
210ZEnd=Z_plane;
211volume_scan='n';
212if isfield(UvData,'XmlData')
213    UvData.XmlData
214    if isfield(UvData.XmlData,'TranslationMotor')
215        NbSlice_j=UvData.XmlData.TranslationMotor.Nbslice;
216        ZStart=UvData.XmlData.TranslationMotor.ZStart/10;
217        ZEnd=UvData.XmlData.TranslationMotor.ZEnd/10;
218        volume_scan='y';
219    end
220end
221hhuvmat=guidata(huvmat);%handles of elements in the GUI uvmat
222RootPath='';
223RootFile='';
224if ~isempty(hhuvmat.RootPath)&& ~isempty(hhuvmat.RootFile)
225    testhandle=1;
226    RootPath=get(hhuvmat.RootPath,'String');
227    RootFile=get(hhuvmat.RootFile,'String');
228    filebase=fullfile(RootPath,RootFile);
229    outputfile=[filebase '.xml'];%xml file associated with the currently displayed image
230else
231    question={'save the calibration data and point coordinates in'};
232    def={fullfile(RootPath,'ObjectCalib.xml')};
233    options.Resize='on';
234    answer=inputdlg(question,'save average in a new file',1,def,options);
235    outputfile=answer{1};
236end
237answer=msgbox_uvmat('INPUT_Y-N',{[outputfile ' updated with calibration data'];...
238    ['Error rms (along x,y)=' num2str(GeometryCalib.ErrorRms) ' pixels'];...
239    ['Error max (along x,y)=' num2str(GeometryCalib.ErrorMax) ' pixels']});
240
241%% record the calibration parameters and display the current image of uvmat in the new phys coordinates
242if strcmp(answer,'Yes')
243    if strcmp(calib_cell{val}(1:2),'3D')%set the plane position for 3D (projection) calibration
244       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'};
245       input_val=[{num2str(ZEnd)} {num2str(ZStart)} {num2str(ZStart)} {'1.333'} num2str(NbSlice_j) {volume_scan} {'0'} {'0'}];
246        answer=inputdlg(input_key,'slice position(s)',ones(1,8), input_val,'on');
247        %answer_1=msgbox_uvmat('INPUT_TXT',' Z= ',num2str(Z_plane));
248        GeometryCalib.NbSlice=str2double(answer{5});
249        GeometryCalib.VolumeScan=answer{6};
250        if isempty(answer)
251            Z_plane=0; %default
252        else
253            Z_plane=linspace(str2double(answer{1}),str2double(answer{2}),GeometryCalib.NbSlice);
254        end     
255        GeometryCalib.SliceCoord=Z_plane'*[0 0 1];
256        GeometryCalib.SliceAngle(:,3)=0;
257        GeometryCalib.SliceAngle(:,2)=str2double(answer{7})*ones(GeometryCalib.NbSlice,1);%rotation around y axis (to generalise)
258        GeometryCalib.SliceAngle(:,1)=str2double(answer{8})*ones(GeometryCalib.NbSlice,1);%rotation around x axis (to generalise)
259        GeometryCalib.InterfaceCoord=[0 0 str2double(answer{3})];
260        GeometryCalib.RefractionIndex=str2double(answer{4});     
261    end
262    errormsg=update_imadoc(GeometryCalib,outputfile);% introduce the calibration data in the xml file
263    if ~strcmp(errormsg,'')
264        msgbox_uvmat('ERROR',errormsg);
265    end
266   
267    %display image with new calibration in the currently opened uvmat interface
268    hhh=findobj(hhuvmat.axes3,'Tag','calib_marker');% delete calib points and markers
269    if ~isempty(hhh)
270        delete(hhh);     
271    end
272    hhh=findobj(hhuvmat.axes3,'Tag','calib_points');
273    if ~isempty(hhh)
274        delete(hhh);
275    end
276    set(hhuvmat.FixLimits,'Value',0)% put FixedLimits option to 'off'
277    set(hhuvmat.FixLimits,'BackgroundColor',[0.7 0.7 0.7])
278    UserData=get(handles.geometry_calib,'UserData');
279    UserData.XmlInputFile=outputfile;%save the current xml file name
280    set(handles.geometry_calib,'UserData',UserData)
281    uvmat('RootPath_Callback',hObject,eventdata,hhuvmat); %file input with xml reading  in uvmat, show the image in phys coordinates
282    MenuPlot_Callback(hObject, eventdata, handles)
283    set(handles.ListCoord,'Value',index)% indicate in the list the point with max deviation (possible mistake)
284    ListCoord_Callback(hObject, eventdata, handles)
285    figure(handles.geometry_calib)
286end
287
288%------------------------------------------------------------------
289% --- Executes on button press in calibrate_lin.
290
291function REPLICATE_Callback(hObject, eventdata, handles)
292%------------------------------------------------------------------------
293
294%% Apply calibration
295calib_cell=get(handles.calib_type,'String'); %#ok<NASGU>
296val=get(handles.calib_type,'Value'); %#ok<NASGU>
297
298%read the current calibration points
299Coord_cell=get(handles.ListCoord,'String');
300Object=read_geometry_calib(Coord_cell);
301Coord=Object.Coord;
302
303% apply the calibration, whose type is selected in  handles.calib_type
304if ~isempty(Coord)
305    calib_cell=get(handles.calib_type,'String');
306    val=get(handles.calib_type,'Value');
307    GeometryCalib=feval(['calib_' calib_cell{val}],Coord,handles);
308else
309    msgbox_uvmat('ERROR','No calibration points, abort')
310    return
311end
312
313if ~isempty(Coord)
314    %check error
315    X=Coord(:,1);
316    Y=Coord(:,2);
317    Z=Coord(:,3);
318    x_ima=Coord(:,4);
319    y_ima=Coord(:,5);
320    [Xpoints,Ypoints]=px_XYZ(GeometryCalib,X,Y,Z);
321    GeometryCalib.ErrorRms(1)=sqrt(mean((Xpoints-x_ima).*(Xpoints-x_ima)));
322    [GeometryCalib.ErrorMax(1),index(1)]=max(abs(Xpoints-x_ima));
323    GeometryCalib.ErrorRms(2)=sqrt(mean((Ypoints-y_ima).*(Ypoints-y_ima)));
324    [GeometryCalib.ErrorMax(2),index(2)]=max(abs(Ypoints-y_ima));
325    [EM,ind_dim]=max(GeometryCalib.ErrorMax);
326%     index=index(ind_dim);
327    %set the Z position of the reference plane used for calibration
328    Z_plane=[];
329    if isequal(max(Z),min(Z))
330        Z_plane=Z(1);
331    end
332    answer_1=msgbox_uvmat('INPUT_TXT',' Z= ',num2str(Z_plane));
333    Z_plane=str2double(answer_1);
334    GeometryCalib.NbSlice=1;
335    GeometryCalib.SliceCoord=[0 0 Z_plane];
336    %set the coordinate unit
337    unitlist=get(handles.CoordUnit,'String');
338    unit=unitlist{get(handles.CoordUnit,'value')};
339    GeometryCalib.CoordUnit=unit;
340    %record the points
341    GeometryCalib.SourceCalib.PointCoord=Coord;
342end
343
344%% display calibration paprameters
345display_intrinsic(GeometryCalib,handles)%display calibration intrinsic parameters
346
347% Display extrinsinc parameters (rotation and translation of camera with  respect to the phys coordiantes)
348set(handles.Tx,'String',num2str(GeometryCalib.Tx_Ty_Tz(1),4))
349set(handles.Ty,'String',num2str(GeometryCalib.Tx_Ty_Tz(2),4))
350set(handles.Tz,'String',num2str(GeometryCalib.Tx_Ty_Tz(3),4))
351set(handles.Phi,'String',num2str(GeometryCalib.omc(1),4))
352set(handles.Theta,'String',num2str(GeometryCalib.omc(2),4))
353set(handles.Psi,'String',num2str(GeometryCalib.omc(3),4))
354
355%% open the GUI dataview
356h_dataview=findobj(allchild(0),'name','dataview');
357if ~isempty(h_dataview)
358    delete(h_dataview)
359end
360CalibData=get(handles.geometry_calib,'UserData');%read the calibration image source on the interface userdata
361InputFile='';
362if isfield(CalibData,'XmlInputFile')
363    InputDir=fileparts(CalibData.XmlInputFile);
364    [InputDir,DirName]=fileparts(InputDir);
365end
366SubCampaignTest='n'; %default
367testup=0;
368if isfield(CalibData,'SubCampaign')
369    SubCampaignTest='y';
370    dir_ref=CalibData.SubCampaign;
371    testup=1;
372elseif isfield(CalibData,'Campaign')
373    dir_ref=CalibData.Campaign;
374    testup=1;
375end
376while testup
377    [InputDir,DirName]=fileparts(InputDir);
378    if strcmp(DirName,dir_ref)
379        break
380    end
381end
382InputDir=fullfile(InputDir,DirName);
383answer=msgbox_uvmat('INPUT_TXT','Campaign ?',InputDir);
384if strcmp(answer,'Cancel')
385    return
386end
387
388dataview(answer,SubCampaignTest,GeometryCalib);
389       
390%     if isfield(Heading,'Device') && isequal([filename ext],Heading.Device)
391%         [XmlInput,filename,ext]=fileparts(XmlInput);
392%         Device=Heading.Device;
393%     end
394%     if isfield(Heading,'Experiment') && isequal([filename ext],Heading.Experiment)
395%         [PP,filename,ext]=fileparts(XmlInput);
396%     end
397%     testinput=0;
398%     if isfield(Heading,'SubCampaign') && isequal([filename ext],Heading.SubCampaign)
399%         SubCampaignTest='y';
400%         testinput=1;
401%     elseif isfield(Heading,'Campaign') && isequal([filename ext],Heading.Campaign)
402%         testinput=1;
403% %     end
404% end
405% if ~testinput
406%     filename='PROJETS';%default
407%     if isfield(CalibData,'XmlInputFile')
408%          [pp,filename]=fileparts(CalibData.XmlInputFile);
409%     end
410%     while ~isequal(filename,'PROJETS') && numel(filename)>1
411%         filename_1=filename;
412%         pp_1=pp;
413%         [pp,filename]=fileparts(pp);
414%     end
415%     XmlInput=fullfile(pp_1,filename_1);
416%     testinput=1;
417% end
418% if testinput
419%     outcome=dataview(XmlInput,SubCampaignTest,GeometryCalib);
420% end
421
422%------------------------------------------------------------------------
423% determine the parameters for a calibration by an affine function (rescaling and offset, no rotation)
424function GeometryCalib=calib_rescale(Coord,handles)
425%------------------------------------------------------------------------
426X=Coord(:,1);
427Y=Coord(:,2);% Z not used
428x_ima=Coord(:,4);
429y_ima=Coord(:,5);
430[px,sx]=polyfit(X,x_ima,1);
431[py,sy]=polyfit(Y,y_ima,1);
432T_x=px(2);
433T_y=py(2);
434GeometryCalib.CalibrationType='rescale';
435GeometryCalib.fx_fy=[px(1) py(1)];%.fx_fy corresponds to pxcm along x and y
436GeometryCalib.CoordUnit=[];% default value, to be updated by the calling function
437GeometryCalib.Tx_Ty_Tz=[px(2)/px(1) py(2)/py(1) 1];
438%GeometryCalib.R=[1,0,0;0,1,0;0,0,0];
439GeometryCalib.omc=[0 0 0];
440
441%------------------------------------------------------------------------
442% determine the parameters for a calibration by a linear transform matrix (rescale and rotation)
443function GeometryCalib=calib_linear(Coord,handles)
444%------------------------------------------------------------------------
445X=Coord(:,1);
446Y=Coord(:,2);% Z not used
447x_ima=Coord(:,4);
448y_ima=Coord(:,5);
449XY_mat=[ones(size(X)) X Y];
450a_X1=XY_mat\x_ima; %transformation matrix for X
451% x1=XY_mat*a_X1;%reconstruction
452% err_X1=max(abs(x1-x_ima));%error
453a_Y1=XY_mat\y_ima;%transformation matrix for X
454% y1=XY_mat*a_Y1;
455% err_Y1=max(abs(y1-y_ima));%error
456% R=[a_X1(2),a_X1(3),0;a_Y1(2),a_Y1(3),0;0,0,1];
457R=[a_X1(2),a_X1(3);a_Y1(2),a_Y1(3)];
458norm=abs(det(R));
459GeometryCalib.CalibrationType='linear';
460if (a_X1(2)/a_Y1(3))>0
461    epsilon=1;
462GeometryCalib.fx_fy(1)=sqrt((a_X1(2)/a_Y1(3))*norm);
463else
464    GeometryCalib.fx_fy(1)=-sqrt((-a_X1(2)/a_Y1(3))*norm);
465      epsilon=-1;
466end
467GeometryCalib.fx_fy(2)=(a_Y1(3)/a_X1(2))*GeometryCalib.fx_fy(1);
468GeometryCalib.CoordUnit=[];% default value, to be updated by the calling function
469%GeometryCalib.Tx_Ty_Tz=[a_X1(1) a_Y1(1) 1];
470GeometryCalib.Tx_Ty_Tz=[a_X1(1)/GeometryCalib.fx_fy(1) a_Y1(1)/GeometryCalib.fx_fy(2) 1];
471R(1,:)=epsilon*R(1,:)/GeometryCalib.fx_fy(1);
472R(2,:)=R(2,:)/GeometryCalib.fx_fy(2);
473R=[R;[0 0]];
474GeometryCalib.R=[R [0;0;-1]];
475GeometryCalib.omc=(180/pi)*[acos(GeometryCalib.R(1,1)) 0 0]
476%------------------------------------------------------------------------
477% determine the tsai parameters for a view normal to the grid plane
478% NOT USED
479function GeometryCalib=calib_normal(Coord,handles)
480%------------------------------------------------------------------------
481Calib.f1=str2num(get(handles.fx,'String'));
482Calib.f2=str2num(get(handles.fy,'String'));
483Calib.k=str2num(get(handles.kc,'String'));
484Calib.Cx=str2num(get(handles.Cx,'String'));
485Calib.Cy=str2num(get(handles.Cy,'String'));
486%default
487if isempty(Calib.f1)
488    Calib.f1=25/0.012;
489end
490if isempty(Calib.f2)
491    Calib.f2=25/0.012;
492end
493if isempty(Calib.k)
494    Calib.k=0;
495end
496if isempty(Calib.Cx)||isempty(Calib.Cy)
497    huvmat=findobj(allchild(0),'Tag','uvmat');
498    hhuvmat=guidata(huvmat);
499    Calib.Cx=str2num(get(hhuvmat.npx,'String'))/2;
500    Calib.Cx=str2num(get(hhuvmat.npy,'String'))/2;
501end   
502%tsai parameters
503Calib.dpx=0.012;%arbitrary
504Calib.dpy=0.012;
505Calib.sx=Calib.f1*Calib.dpx/(Calib.f2*Calib.dpy);
506Calib.f=Calib.f2*Calib.dpy;
507Calib.kappa1=Calib.k/(Calib.f*Calib.f);
508
509%initial guess
510X=Coord(:,1);
511Y=Coord(:,2);
512Zmean=mean(Coord(:,3));
513x_ima=Coord(:,4)-Calib.Cx;
514y_ima=Coord(:,5)-Calib.Cy;
515XY_mat=[ones(size(X)) X Y];
516a_X1=XY_mat\x_ima; %transformation matrix for X
517a_Y1=XY_mat\y_ima;%transformation matrix for Y
518R=[a_X1(2),a_X1(3),0;a_Y1(2),a_Y1(3),0;0,0,-1];% rotation+ z axis reversal (upward)
519norm=sqrt(det(-R));
520calib_param(1)=0;% quadratic distortion
521calib_param(2)=a_X1(1);
522calib_param(3)=a_Y1(1);
523calib_param(4)=Calib.f/(norm*Calib.dpx)-R(3,3)*Zmean;
524calib_param(5)=angle(a_X1(2)+1i*a_X1(3));
525display(['initial guess=' num2str(calib_param)])
526
527%optimise the parameters: minimisation of error
528calib_param = fminsearch(@(calib_param) error_calib(calib_param,Calib,Coord),calib_param);
529
530GeometryCalib.CalibrationType='tsai_normal';
531GeometryCalib.focal=Calib.f;
532GeometryCalib.dpx_dpy=[Calib.dpx Calib.dpy];
533GeometryCalib.Cx_Cy=[Calib.Cx Calib.Cy];
534GeometryCalib.sx=Calib.sx;
535GeometryCalib.kappa1=calib_param(1);
536GeometryCalib.CoordUnit=[];% default value, to be updated by the calling function
537GeometryCalib.Tx_Ty_Tz=[calib_param(2) calib_param(3) calib_param(4)];
538alpha=calib_param(5);
539GeometryCalib.R=[cos(alpha) sin(alpha) 0;-sin(alpha) cos(alpha) 0;0 0 -1];
540
541%------------------------------------------------------------------------
542function GeometryCalib=calib_3D_linear(Coord,handles)
543%------------------------------------------------------------------
544path_uvmat=which('uvmat');% check the path detected for source file uvmat
545path_UVMAT=fileparts(path_uvmat); %path to UVMAT
546huvmat=findobj(allchild(0),'Tag','uvmat');
547hhuvmat=guidata(huvmat);
548coord_files=get(handles.coord_files,'String');
549if ischar(coord_files)
550    coord_files={coord_files};
551end
552if isempty(coord_files{1}) || isequal(coord_files,{''})
553    coord_files={};
554end
555%retrieve the calibration points stored in the files listed in the popup list coord_files
556x_1=Coord(:,4:5)';%px coordinates of the ref points
557nx=str2num(get(hhuvmat.npx,'String'));
558ny=str2num(get(hhuvmat.npy,'String'));
559x_1(2,:)=ny-x_1(2,:);%reverse the y image coordinates
560X_1=Coord(:,1:3)';%phys coordinates of the ref points
561n_ima=numel(coord_files)+1;
562if ~isempty(coord_files)
563    msgbox_uvmat('CONFIRMATION',['The xy coordinates of the calibration points in ' num2str(n_ima) ' planes will be used'])
564    for ifile=1:numel(coord_files)
565    t=xmltree(coord_files{ifile});
566    s=convert(t);%convert to matlab structure
567        if isfield(s,'GeometryCalib')
568            if isfield(s.GeometryCalib,'SourceCalib')
569                if isfield(s.GeometryCalib.SourceCalib,'PointCoord')
570                PointCoord=s.GeometryCalib.SourceCalib.PointCoord;
571                Coord_file=zeros(length(PointCoord),5);%default
572                for i=1:length(PointCoord)
573                    line=str2num(PointCoord{i});
574                    Coord_file(i,4:5)=line(4:5);%px x
575                    Coord_file(i,1:3)=line(1:3);%phys x
576                end
577                eval(['x_' num2str(ifile+1) '=Coord_file(:,4:5)'';']);
578                eval(['x_' num2str(ifile+1) '(2,:)=ny-x_' num2str(ifile+1) '(2,:);' ]);
579                eval(['X_' num2str(ifile+1) '=Coord_file(:,1:3)'';']);
580                end
581            end
582        end
583    end
584end
585n_ima=numel(coord_files)+1;
586est_dist=[0;0;0;0;0];
587est_aspect_ratio=0;
588est_fc=[1;1];
589%fc=[25;25]/0.012;
590center_optim=0;
591run(fullfile(path_UVMAT,'toolbox_calib','go_calib_optim'));
592GeometryCalib.CalibrationType='3D_linear';
593GeometryCalib.fx_fy=fc';
594%GeometryCalib.focal=fc(2);
595%GeometryCalib.dpx_dpy=[1 1];
596GeometryCalib.Cx_Cy=cc';
597%GeometryCalib.sx=fc(1)/fc(2);
598GeometryCalib.kc=kc(1);
599%GeometryCalib.kappa1=-kc(1)/fc(2)^2;
600GeometryCalib.CoordUnit=[];% default value, to be updated by the calling function
601GeometryCalib.Tx_Ty_Tz=Tc_1';
602GeometryCalib.R=Rc_1;
603GeometryCalib.R(2,1:3)=-GeometryCalib.R(2,1:3);%inversion of the y image coordinate
604GeometryCalib.Tx_Ty_Tz(2)=-GeometryCalib.Tx_Ty_Tz(2);%inversion of the y image coordinate
605GeometryCalib.Cx_Cy(2)=ny-GeometryCalib.Cx_Cy(2);%inversion of the y image coordinate
606GeometryCalib.omc=(180/pi)*omc_1;%angles in degrees
607GeometryCalib.ErrorRMS=[];
608GeometryCalib.ErrorMax=[];
609
610%------------------------------------------------------------------------
611function GeometryCalib=calib_3D_quadr(Coord,handles)
612%------------------------------------------------------------------
613
614path_uvmat=which('uvmat');% check the path detected for source file uvmat
615path_UVMAT=fileparts(path_uvmat); %path to UVMAT
616huvmat=findobj(allchild(0),'Tag','uvmat');
617hhuvmat=guidata(huvmat);
618% check_cond=0;
619coord_files=get(handles.coord_files,'String');
620if ischar(coord_files)
621    coord_files={coord_files};
622end
623if isempty(coord_files{1}) || isequal(coord_files,{''})
624    coord_files={};
625end
626
627%retrieve the calibration points stored in the files listed in the popup list coord_files
628x_1=Coord(:,4:5)';%px coordinates of the ref points
629nx=str2num(get(hhuvmat.npx,'String'));
630ny=str2num(get(hhuvmat.npy,'String'));
631x_1(2,:)=ny-x_1(2,:);%reverse the y image coordinates
632X_1=Coord(:,1:3)';%phys coordinates of the ref points
633n_ima=numel(coord_files)+1;
634if ~isempty(coord_files)
635    msgbox_uvmat('CONFIRMATION',['The xy coordinates of the calibration points in ' num2str(n_ima) ' planes will be used'])
636    for ifile=1:numel(coord_files)
637    t=xmltree(coord_files{ifile});
638    s=convert(t);%convert to matlab structure
639        if isfield(s,'GeometryCalib')
640            if isfield(s.GeometryCalib,'SourceCalib')
641                if isfield(s.GeometryCalib.SourceCalib,'PointCoord')
642                PointCoord=s.GeometryCalib.SourceCalib.PointCoord;
643                Coord_file=zeros(length(PointCoord),5);%default
644                for i=1:length(PointCoord)
645                    line=str2num(PointCoord{i});
646                    Coord_file(i,4:5)=line(4:5);%px x
647                    Coord_file(i,1:3)=line(1:3);%phys x
648                end
649                eval(['x_' num2str(ifile+1) '=Coord_file(:,4:5)'';']);
650                eval(['x_' num2str(ifile+1) '(2,:)=ny-x_' num2str(ifile+1) '(2,:);' ]);
651                eval(['X_' num2str(ifile+1) '=Coord_file(:,1:3)'';']);
652                end
653            end
654        end
655    end
656end
657n_ima=numel(coord_files)+1;
658est_dist=[1;0;0;0;0];
659est_aspect_ratio=1;
660%est_fc=[0;0];
661%fc=[25;25]/0.012;
662center_optim=0;
663run(fullfile(path_UVMAT,'toolbox_calib','go_calib_optim'));
664
665GeometryCalib.CalibrationType='3D_quadr';
666GeometryCalib.fx_fy=fc';
667%GeometryCalib.focal=fc(2);
668%GeometryCalib.dpx_dpy=[1 1];
669GeometryCalib.Cx_Cy=cc';
670%GeometryCalib.sx=fc(1)/fc(2);
671GeometryCalib.kc=kc(1);
672%GeometryCalib.kappa1=-kc(1)/fc(2)^2;
673GeometryCalib.CoordUnit=[];% default value, to be updated by the calling function
674GeometryCalib.Tx_Ty_Tz=Tc_1';
675GeometryCalib.R=Rc_1;
676GeometryCalib.R(2,1:3)=-GeometryCalib.R(2,1:3);%inversion of the y image coordinate
677GeometryCalib.Tx_Ty_Tz(2)=-GeometryCalib.Tx_Ty_Tz(2);%inversion of the y image coordinate
678GeometryCalib.Cx_Cy(2)=ny-GeometryCalib.Cx_Cy(2);%inversion of the y image coordinate
679GeometryCalib.omc=(180/pi)*omc_1;%angles in degrees
680GeometryCalib.ErrorRMS=[];
681GeometryCalib.ErrorMax=[];
682
683
684%------------------------------------------------------------------------
685function GeometryCalib=calib_3D_extrinsic(Coord,handles)
686%------------------------------------------------------------------
687path_uvmat=which('geometry_calib');% check the path detected for source file uvmat
688path_UVMAT=fileparts(path_uvmat); %path to UVMAT
689x_1=double(Coord(:,4:5)');%image coordiantes
690X_1=double(Coord(:,1:3)');% phys coordinates
691huvmat=findobj(allchild(0),'Tag','uvmat');
692hhuvmat=guidata(huvmat);
693ny=str2double(get(hhuvmat.npy,'String'));
694x_1(2,:)=ny-x_1(2,:);%reverse the y image coordinates
695n_ima=1;
696GeometryCalib.CalibrationType='3D_extrinsic';
697GeometryCalib.fx_fy(1)=str2num(get(handles.fx,'String'));
698GeometryCalib.fx_fy(2)=str2num(get(handles.fy,'String'));
699GeometryCalib.Cx_Cy(1)=str2num(get(handles.Cx,'String'));
700GeometryCalib.Cx_Cy(2)=str2num(get(handles.Cy,'String'));
701GeometryCalib.kc=str2num(get(handles.kc,'String'));
702fct_path=fullfile(path_UVMAT,'toolbox_calib');
703addpath(fct_path)
704GeometryCalib.Cx_Cy(2)=ny-GeometryCalib.Cx_Cy(2);%reverse Cx_Cy(2) for calibration (inversion of px ordinate)
705% [omc1,Tc1,Rc1,H,x,ex,JJ] = compute_extrinsic(x_1,X_1,...
706%     [Calib.f Calib.f*Calib.sx]',...
707%     [Calib.Cx Calib.Cy]',...
708%     [-Calib.kappa1*Calib.f^2 0 0 0 0]);
709[omc,Tc1,Rc1,H,x,ex,JJ] = compute_extrinsic(x_1,X_1,...
710    (GeometryCalib.fx_fy)',GeometryCalib.Cx_Cy',[GeometryCalib.kc 0 0 0 0]);
711rmpath(fct_path);
712GeometryCalib.CoordUnit=[];% default value, to be updated by the calling function
713GeometryCalib.Tx_Ty_Tz=Tc1';
714%inversion of z axis
715GeometryCalib.R=Rc1;
716GeometryCalib.R(2,1:3)=-GeometryCalib.R(2,1:3);%inversion of the y image coordinate
717GeometryCalib.Tx_Ty_Tz(2)=-GeometryCalib.Tx_Ty_Tz(2);%inversion of the y image coordinate
718GeometryCalib.Cx_Cy(2)=ny-GeometryCalib.Cx_Cy(2);%inversion of the y image coordinate
719GeometryCalib.omc=(180/pi)*omc';
720%GeometryCalib.R(3,1:3)=-GeometryCalib.R(3,1:3);%inversion for z upward
721
722
723
724%------------------------------------------------------------------------
725%function GeometryCalib=calib_tsai_heikkila(Coord)
726% TEST: NOT IMPLEMENTED
727%------------------------------------------------------------------
728% path_uvmat=which('uvmat');% check the path detected for source file uvmat
729% path_UVMAT=fileparts(path_uvmat); %path to UVMAT
730% path_calib=fullfile(path_UVMAT,'toolbox_calib_heikkila');
731% addpath(path_calib)
732% npoints=size(Coord,1);
733% Coord(:,1:3)=10*Coord(:,1:3);
734% Coord=[Coord zeros(npoints,2) -ones(npoints,1)];
735% [par,pos,iter,res,er,C]=cacal('dalsa',Coord);
736% GeometryCalib.CalibrationType='tsai';
737% GeometryCalib.focal=par(2);
738
739
740%--------------------------------------------------------------------------
741function GeometryCalib=calib_tsai(Coord,handles)% OBSOLETE: old version using gauthier's bianry ccal_fo
742% NOT USED
743%------------------------------------------------------------------------
744%TSAI
745path_uvmat=which('uvmat');% check the path detected for source file uvmat
746path_UVMAT=fileparts(path_uvmat); %path to UVMAT
747xmlfile=fullfile(path_UVMAT,'PARAM.xml');%name of the file containing names of binary executables
748if exist(xmlfile,'file')
749    t=xmltree(xmlfile);% read the (xml) file containing names of binary executables
750    sparam=convert(t);% convert to matlab structure
751end
752if ~isfield(sparam,'GeometryCalibBin')
753    msgbox_uvmat('ERROR',['calibration program <GeometryCalibBin> undefined in parameter file ' xmlfile])
754    return
755end
756Tsai_exe=sparam.GeometryCalibBin;
757if ~exist(Tsai_exe,'file')%the binary is defined in /bin, default setting
758     Tsai_exe=fullfile(path_UVMAT,Tsai_exe);
759end
760if ~exist(Tsai_exe,'file')
761    msgbox_uvmat('ERROR',['calibration program ' sparam.GeometryCalibBin ' defined in PARAM.xml does not exist'])
762    return
763end
764
765textcoord=num2str(Coord,4);
766dlmwrite('t.txt',textcoord,''); 
767% ['!' Tsai_exe ' -fx 0 -fy t.txt']
768eval(['!' Tsai_exe ' -f t.txt > tsaicalib.log']);
769if ~exist('calib.dat','file')
770    msgbox_uvmat('ERROR','no output from calibration program Tsai_exe: possibly too few points')
771end
772calibdat=dlmread('calib.dat');
773delete('calib.dat')
774%delete('t.txt')
775GeometryCalib.CalibrationType='tsai';
776GeometryCalib.focal=calibdat(10);
777GeometryCalib.dpx_dpy=[calibdat(5) calibdat(6)];
778GeometryCalib.Cx_Cy=[calibdat(7) calibdat(8)];
779GeometryCalib.sx=calibdat(9);
780GeometryCalib.kappa1=calibdat(11);
781GeometryCalib.CoordUnit=[];% default value, to be updated by the calling function
782GeometryCalib.Tx_Ty_Tz=[calibdat(12) calibdat(13) calibdat(14)];
783Rx_Ry_Rz=calibdat(15:17);
784sa = sin(Rx_Ry_Rz(1)) ;
785ca=cos(Rx_Ry_Rz(1));
786sb=sin(Rx_Ry_Rz(2));
787cb =cos(Rx_Ry_Rz(2));
788sg =sin(Rx_Ry_Rz(3));
789cg =cos(Rx_Ry_Rz(3));
790r1 = cb * cg;
791r2 = cg * sa * sb - ca * sg;
792r3 = sa * sg + ca * cg * sb;
793r4 = cb * sg;
794r5 = sa * sb * sg + ca * cg;
795r6 = ca * sb * sg - cg * sa;
796r7 = -sb;
797r8 = cb * sa;
798r9 = ca * cb;
799%EN DEDUIRE MATRICE R ??
800GeometryCalib.R=[r1,r2,r3;r4,r5,r6;r7,r8,r9];
801
802%------------------------------------------------------------------------
803% --- determine the rms of calibration error
804function ErrorRms=error_calib(calib_param,Calib,Coord)
805%calib_param: vector of free calibration parameters (to optimise)
806%Calib: structure of the given calibration parameters
807%Coord: list of phys coordinates (columns 1-3, and pixel coordinates (columns 4-5)
808Calib.f=25;
809Calib.dpx=0.012;
810Calib.dpy=0.012;
811Calib.sx=1;
812Calib.Cx=512;
813Calib.Cy=512;
814Calib.kappa1=calib_param(1);
815Calib.Tx=calib_param(2);
816Calib.Ty=calib_param(3);
817Calib.Tz=calib_param(4);
818alpha=calib_param(5);
819Calib.R=[cos(alpha) sin(alpha) 0;-sin(alpha) cos(alpha) 0;0 0 -1];
820
821X=Coord(:,1);
822Y=Coord(:,2);
823Z=Coord(:,3);
824x_ima=Coord(:,4);
825y_ima=Coord(:,5);
826[Xpoints,Ypoints]=px_XYZ(Calib,X,Y,Z);
827ErrorRms(1)=sqrt(mean((Xpoints-x_ima).*(Xpoints-x_ima)));
828ErrorRms(2)=sqrt(mean((Ypoints-y_ima).*(Ypoints-y_ima)));
829ErrorRms=mean(ErrorRms);
830
831%------------------------------------------------------------------------
832function XImage_Callback(hObject, eventdata, handles)
833%------------------------------------------------------------------------
834update_list(hObject, eventdata,handles)
835
836%------------------------------------------------------------------------
837function YImage_Callback(hObject, eventdata, handles)
838%------------------------------------------------------------------------
839update_list(hObject, eventdata,handles)
840
841%------------------------------------------------------------------------
842% --- Executes on button press in STORE.
843function STORE_Callback(hObject, eventdata, handles)
844Coord_cell=get(handles.ListCoord,'String');
845Object=read_geometry_calib(Coord_cell);
846unitlist=get(handles.CoordUnit,'String');
847unit=unitlist{get(handles.CoordUnit,'value')};
848GeometryCalib.CoordUnit=unit;
849GeometryCalib.SourceCalib.PointCoord=Object.Coord;
850huvmat=findobj(allchild(0),'Name','uvmat');
851hhuvmat=guidata(huvmat);%handles of elements in the GUI uvmat
852% RootPath='';
853% RootFile='';
854if ~isempty(hhuvmat.RootPath)&& ~isempty(hhuvmat.RootFile)
855    testhandle=1;
856    RootPath=get(hhuvmat.RootPath,'String');
857    RootFile=get(hhuvmat.RootFile,'String');
858    filebase=fullfile(RootPath,RootFile);
859    while exist([filebase '.xml'],'file')
860        filebase=[filebase '~'];
861    end
862    outputfile=[filebase '.xml'];
863    errormsg=update_imadoc(GeometryCalib,outputfile);
864    if ~strcmp(errormsg,'')
865        msgbox_uvmat('ERROR',errormsg);
866    end
867    listfile=get(handles.coord_files,'string');
868    if isequal(listfile,{''})
869        listfile={outputfile};
870    else
871        listfile=[listfile;{outputfile}];%update the list of coord files
872    end
873    set(handles.coord_files,'string',listfile);
874end
875set(handles.ListCoord,'Value',1)% refresh the display of coordinates
876set(handles.ListCoord,'String',{'......'})
877
878% --------------------------------------------------------------------
879% --- Executes on button press in CLEAR_PTS: clear the list of calibration points
880function CLEAR_PTS_Callback(hObject, eventdata, handles)
881% --------------------------------------------------------------------
882set(handles.ListCoord,'Value',1)% refresh the display of coordinates
883set(handles.ListCoord,'String',{'......'})
884MenuPlot_Callback(hObject, eventdata, handles)
885
886%------------------------------------------------------------------------
887% --- Executes on button press in CLEAR.
888function CLEAR_Callback(hObject, eventdata, handles)
889%------------------------------------------------------------------------
890set(handles.coord_files,'Value',1)
891set(handles.coord_files,'String',{''})
892
893%------------------------------------------------------------------------
894function XObject_Callback(hObject, eventdata, handles)
895%------------------------------------------------------------------------
896update_list(hObject, eventdata,handles)
897
898%------------------------------------------------------------------------
899function YObject_Callback(hObject, eventdata, handles)
900%------------------------------------------------------------------------
901update_list(hObject, eventdata,handles)
902
903%------------------------------------------------------------------------
904function ZObject_Callback(hObject, eventdata, handles)
905%------------------------------------------------------------------------
906update_list(hObject, eventdata,handles)
907
908%------------------------------------------------------------------------
909function update_list(hObject, eventdata, handles)
910%------------------------------------------------------------------------
911newval(4)=str2double(get(handles.XImage,'String'));
912newval(5)=str2double(get(handles.YImage,'String'));
913newval(1)=str2double(get(handles.XObject,'String'));
914newval(2)=str2double(get(handles.YObject,'String'));
915newval(3)=str2double(get(handles.ZObject,'String'));
916if isnan(newval(3))
917    newval(3)=0;%put z to 0 by default
918end
919Coord=get(handles.ListCoord,'String');
920Coord(end)=[]; %remove last string '.....'
921val=get(handles.ListCoord,'Value');
922data=read_geometry_calib(Coord);
923data.Coord(val,:)=newval;
924for i=1:size(data.Coord,1)
925    for j=1:5
926          Coord_cell{i,j}=num2str(data.Coord(i,j),4);%display coordiantes with 4 digits
927    end
928end
929
930Tabchar=cell2tab(Coord_cell,' | ');
931Tabchar=[Tabchar ;{'......'}];
932set(handles.ListCoord,'String',Tabchar)
933
934%update the plot
935ListCoord_Callback(hObject, eventdata, handles)
936MenuPlot_Callback(hObject, eventdata, handles)
937
938%------------------------------------------------------------------------
939% --- Executes on selection change in ListCoord.
940function ListCoord_Callback(hObject, eventdata, handles)
941%------------------------------------------------------------------------
942huvmat=findobj(allchild(0),'Name','uvmat');%find the current uvmat interface handle
943hplot=findobj(huvmat,'Tag','axes3');%main plotting axis of uvmat
944hhh=findobj(hplot,'Tag','calib_marker');
945Coord_cell=get(handles.ListCoord,'String');
946val=get(handles.ListCoord,'Value');
947if numel(val)>1
948    return %no action if several lines have been selected
949end
950coord_str=Coord_cell{val};
951k=findstr(' | ',coord_str);
952if isempty(k)%last line '.....' selected
953    if ~isempty(hhh)
954        delete(hhh)%delete the circle marker
955    end
956    return
957end
958%fill the edit boxex
959set(handles.XObject,'String',coord_str(1:k(1)-1))
960set(handles.YObject,'String',coord_str(k(1)+3:k(2)-1))
961set(handles.ZObject,'String',coord_str(k(2)+3:k(3)-1))
962set(handles.XImage,'String',coord_str(k(3)+3:k(4)-1))
963set(handles.YImage,'String',coord_str(k(4)+3:end))
964h_menu_coord=findobj(huvmat,'Tag','transform_fct');
965menu=get(h_menu_coord,'String');
966choice=get(h_menu_coord,'Value');
967if iscell(menu)
968    option=menu{choice};
969else
970    option='px'; %default
971end
972if isequal(option,'phys')
973    XCoord=str2double(coord_str(1:k(1)-1));
974    YCoord=str2double(coord_str(k(1)+3:k(2)-1));
975elseif isequal(option,'px')|| isequal(option,'')
976    XCoord=str2double(coord_str(k(3)+3:k(4)-1));
977    YCoord=str2double(coord_str(k(4)+3:end));
978else
979    msgbox_uvmat('ERROR','the choice in menu_coord of uvmat must be px or phys ')
980end
981if isempty(XCoord)||isempty(YCoord)
982     if ~isempty(hhh)
983        delete(hhh)%delete the circle marker
984    end
985    return
986end
987xlim=get(hplot,'XLim');
988ylim=get(hplot,'YLim');
989ind_range=max(abs(xlim(2)-xlim(1)),abs(ylim(end)-ylim(1)))/20;%defines the size of the circle marker
990if isempty(hhh)
991    set(0,'CurrentFig',huvmat)
992    set(huvmat,'CurrentAxes',hplot)
993    rectangle('Curvature',[1 1],...
994              'Position',[XCoord-ind_range/2 YCoord-ind_range/2 ind_range ind_range],'EdgeColor','m',...
995              'LineStyle','-','Tag','calib_marker');
996else
997    set(hhh,'Position',[XCoord-ind_range/2 YCoord-ind_range/2 ind_range ind_range])
998end
999
1000%------------------------------------------------------------------------
1001% --- Executes on selection change in edit_append.
1002function edit_append_Callback(hObject, eventdata, handles)
1003%------------------------------------------------------------------------
1004choice=get(handles.edit_append,'Value');
1005if choice
1006    set(handles.edit_append,'BackgroundColor',[1 1 0])
1007    huvmat=findobj(allchild(0),'tag','uvmat');
1008    if ishandle(huvmat)
1009        hhuvmat=guidata(huvmat);
1010        set(hhuvmat.edit_object,'Value',0)
1011        set(hhuvmat.edit_object,'BackgroundColor',[0.7 0.7 0.7])
1012    end
1013else
1014    set(handles.edit_append,'BackgroundColor',[0.7 0.7 0.7])
1015end
1016   
1017function NEW_Callback(hObject, eventdata, handles)
1018%A METTRE SOUS UN BOUTON
1019huvmat=findobj(allchild(0),'Name','uvmat');
1020hchild=get(huvmat,'children');
1021hcoord=findobj(hchild,'Tag','menu_coord');
1022coordtype=get(hcoord,'Value');
1023haxes=findobj(hchild,'Tag','axes3');
1024AxeData=get(haxes,'UserData');
1025if ~isequal(hcoord,2)
1026    set(hcoord,'Value',2)
1027    huvmat=uvmat(AxeData);
1028    'relancer uvmat';
1029end
1030if ~isfield(AxeData,'ZoomAxes')
1031    msgbox_uvmat('ERROR','first draw a window around a grid marker')
1032    return
1033end
1034XLim=get(AxeData.ZoomAxes,'XLim');
1035YLim=get(AxeData.ZoomAxes,'YLim');
1036np=size(AxeData.A);
1037ind_sub_x=round(XLim);
1038ind_sub_y=np(1)-round(YLim);
1039Mfiltre=AxeData.A(ind_sub_y(2):ind_sub_y(1) ,ind_sub_x,:);
1040Mfiltre_norm=double(Mfiltre);
1041Mfiltre_norm=Mfiltre_norm/sum(sum(Mfiltre_norm));
1042Mfiltre_norm=100*(Mfiltre_norm-mean(mean(Mfiltre_norm)));
1043Atype=class(AxeData.A);
1044Data.NbDim=2;
1045Data.A=filter2(Mfiltre_norm,double(AxeData.A));
1046Data.A=feval(Atype,Data.A);
1047Data.AName='image';
1048Data.AX=AxeData.AX;
1049Data.AY=AxeData.AY;
1050Data.CoordType='px';
1051plot_field(Data)
1052
1053%------------------------------------------------------------------------
1054function MenuPlot_Callback(hObject, eventdata, handles)
1055%------------------------------------------------------------------------
1056huvmat=findobj(allchild(0),'Name','uvmat');%find the current uvmat interface handle
1057%UvData=get(huvmat,'UserData');%Data associated to the current uvmat interface
1058hhuvmat=guidata(huvmat); %handles of GUI elements in uvmat
1059%hplot=findobj(huvmat,'Tag','axes3');%main plotting axis of uvmat
1060h_menu_coord=findobj(huvmat,'Tag','transform_fct');
1061menu=get(h_menu_coord,'String');
1062choice=get(h_menu_coord,'Value');
1063if iscell(menu)
1064    option=menu{choice};
1065else
1066    option='px'; %default
1067end
1068Coord_cell=get(handles.ListCoord,'String');
1069ObjectData=read_geometry_calib(Coord_cell);
1070%ObjectData=read_geometry_calib(handles);%read the interface input parameters defining the object
1071if ~isempty(ObjectData.Coord)
1072    if isequal(option,'phys')
1073        ObjectData.Coord=ObjectData.Coord(:,1:3);
1074    elseif isequal(option,'px')||isequal(option,'')
1075        ObjectData.Coord=ObjectData.Coord(:,4:5);
1076    else
1077        msgbox_uvmat('ERROR','the choice in menu_coord of uvmat must be '''', px or phys ')
1078    end
1079end
1080%axes(hhuvmat.axes3)
1081set(0,'CurrentFigure',huvmat)
1082set(huvmat,'CurrentAxes',hhuvmat.axes3)
1083hh=findobj('Tag','calib_points');
1084if  ~isempty(ObjectData.Coord) && isempty(hh)
1085    hh=line(ObjectData.Coord(:,1),ObjectData.Coord(:,2),'Color','m','Tag','calib_points','LineStyle','.','Marker','+');
1086elseif isempty(ObjectData.Coord)%empty list of points, suppress the plot
1087    delete(hh)
1088else
1089    set(hh,'XData',ObjectData.Coord(:,1))
1090    set(hh,'YData',ObjectData.Coord(:,2))
1091end
1092pause(.1)
1093figure(handles.geometry_calib)
1094
1095% --------------------------------------------------------------------
1096function MenuHelp_Callback(hObject, eventdata, handles)
1097path_to_uvmat=which('uvmat');% check the path of uvmat
1098pathelp=fileparts(path_to_uvmat);
1099helpfile=fullfile(pathelp,'uvmat_doc','uvmat_doc.html');
1100if isempty(dir(helpfile)), msgbox_uvmat('ERROR','Please put the help file uvmat_doc.html in the sub-directory /uvmat_doc of the UVMAT package')
1101else
1102   addpath (fullfile(pathelp,'uvmat_doc'))
1103   web([helpfile '#geometry_calib'])
1104end
1105
1106%------------------------------------------------------------------------
1107function MenuCreateGrid_Callback(hObject, eventdata, handles)
1108%------------------------------------------------------------------------
1109%hcalib=get(handles.calib_type,'parent');%handles of the GUI geometry_calib
1110CalibData=get(handles.geometry_calib,'UserData');
1111Tinput=[];%default
1112if isfield(CalibData,'grid')
1113    Tinput=CalibData.grid;
1114end
1115[T,CalibData.grid]=create_grid(Tinput);%display the GUI create_grid
1116set(handles.geometry_calib,'UserData',CalibData)
1117
1118%grid in phys space
1119Coord=get(handles.ListCoord,'String');
1120val=get(handles.ListCoord,'Value');
1121data=read_geometry_calib(Coord);
1122%nbpoints=size(data.Coord,1); %nbre of calibration points
1123data.Coord(val:val+size(T,1)-1,1:3)=T(end:-1:1,:);%update the existing list of phys coordinates from the GUI create_grid
1124% for i=1:nbpoints
1125%    for j=1:5
1126%           Coord{i,j}=num2str(data.Coord(i,j),4);%display coordiantes with 4 digits
1127%    end
1128% end
1129%update the phys coordinates starting from the selected point (down in the
1130Coord(end,:)=[]; %remove last string '.....'
1131for i=1:size(data.Coord,1)
1132    for j=1:5
1133          Coord{i,j}=num2str(data.Coord(i,j),4);%display coordiantes with 4 digits
1134    end
1135end
1136
1137%size(data.Coord,1)
1138Tabchar=cell2tab(Coord,' | ');
1139Tabchar=[Tabchar ;{'......'}];
1140set(handles.ListCoord,'String',Tabchar)
1141
1142% -----------------------------------------------------------------------
1143% --- automatic grid dectection from local maxima of the images
1144function MenuDetectGrid_Callback(hObject, eventdata, handles)
1145%------------------------------------------------------------------------
1146%% read the four last point coordinates in pixels
1147Coord_cell=get(handles.ListCoord,'String');%read list of coordinates on geometry_calib
1148data=read_geometry_calib(Coord_cell);
1149nbpoints=size(data.Coord,1); %nbre of calibration points
1150if nbpoints~=4
1151    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')
1152    return
1153end
1154corners_X=(data.Coord(end:-1:end-3,4)); %pixel absissa of the four corners
1155corners_Y=(data.Coord(end:-1:end-3,5));
1156
1157%reorder the last two points (the two first in the list) if needed
1158angles=angle((corners_X-corners_X(1))+1i*(corners_Y-corners_Y(1)));
1159if abs(angles(4)-angles(2))>abs(angles(3)-angles(2))
1160      X_end=corners_X(4);
1161      Y_end=corners_Y(4);
1162      corners_X(4)=corners_X(3);
1163      corners_Y(4)=corners_Y(3);
1164      corners_X(3)=X_end;
1165      corners_Y(3)=Y_end;
1166end
1167
1168%% initiate the grid
1169CalibData=get(handles.geometry_calib,'UserData');%get information stored on the GUI geometry_calib
1170grid_input=[];%default
1171if isfield(CalibData,'grid')
1172    grid_input=CalibData.grid;%retrieve the previously used grid
1173end
1174[T,CalibData.grid,white_test]=create_grid(grid_input,'detect_grid');%display the GUI create_grid, read the set of phys coordinates T
1175set(handles.geometry_calib,'UserData',CalibData)%store the phys grid parameters for later use
1176
1177
1178
1179%% read the current image, displayed in the GUI uvmat
1180huvmat=findobj(allchild(0),'Name','uvmat');
1181UvData=get(huvmat,'UserData');
1182A=UvData.Field.A;
1183npxy=size(A);
1184X=[CalibData.grid.x_0 CalibData.grid.x_1 CalibData.grid.x_0 CalibData.grid.x_1]';%corner absissa in the phys coordinates (cm)
1185Y=[CalibData.grid.y_0 CalibData.grid.y_0 CalibData.grid.y_1 CalibData.grid.y_1]';%corner ordinates in the phys coordinates (cm)
1186
1187%calculate transform matrices for plane projection
1188% reference: http://alumni.media.mit.edu/~cwren/interpolator/ by Christopher R. Wren
1189B = [ X Y ones(size(X)) zeros(4,3)        -X.*corners_X -Y.*corners_X ...
1190      zeros(4,3)        X Y ones(size(X)) -X.*corners_Y -Y.*corners_Y ];
1191B = reshape (B', 8 , 8 )';
1192D = [ corners_X , corners_Y ];
1193D = reshape (D', 8 , 1 );
1194l = (B' * B)\B' * D;
1195Amat = reshape([l(1:6)' 0 0 1 ],3,3)';
1196C = [l(7:8)' 1];
1197
1198% transform grid image into 'phys' coordinates
1199GeometryCalib.fx_fy=[1 1];
1200GeometryCalib.Tx_Ty_Tz=[Amat(1,3) Amat(2,3) 1];
1201GeometryCalib.R=[Amat(1,1),Amat(1,2),0;Amat(2,1),Amat(2,2),0;C(1),C(2),0];
1202GeometryCalib.CoordUnit='cm';
1203path_uvmat=which('uvmat');% check the path detected for source file uvmat
1204path_UVMAT=fileparts(path_uvmat); %path to UVMAT
1205addpath(fullfile(path_UVMAT,'transform_field'))
1206Data.ListVarName={'AY','AX','A'};
1207Data.VarDimName={'AY','AX',{'AY','AX'}};
1208if ndims(A)==3
1209    A=mean(A,3);
1210end
1211Data.A=A-min(min(A));
1212Data.AY=[npxy(1)-0.5 0.5];
1213Data.AX=[0.5 npxy(2)];
1214Data.CoordUnit='pixel';
1215Calib.GeometryCalib=GeometryCalib;
1216DataOut=phys(Data,Calib);
1217rmpath(fullfile(path_UVMAT,'transform_field'))
1218Amod=DataOut.A;
1219Rangx=DataOut.AX;
1220Rangy=DataOut.AY;
1221if white_test
1222    Amod=double(Amod);%case of white grid markers: will look for image maxima
1223else
1224    Amod=-double(Amod);%case of black grid markers: will look for image minima
1225end
1226% figure(12) %display corrected image
1227% Amax=max(max(Amod));
1228% image(Rangx,Rangy,uint8(255*Amod/Amax))
1229
1230%% detection of local image extrema in each direction
1231Dx=(Rangx(2)-Rangx(1))/(npxy(2)-1); %x mesh in real space
1232Dy=(Rangy(2)-Rangy(1))/(npxy(1)-1); %y mesh in real space
1233ind_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
1234ind_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
1235nbpoints=size(T,1);
1236for ipoint=1:nbpoints
1237    i0=1+round((T(ipoint,1)-Rangx(1))/Dx);%round(Xpx(ipoint));
1238    j0=1+round((T(ipoint,2)-Rangy(1))/Dy);%round(Xpx(ipoint));
1239    j0min=max(j0-ind_range_y,1);
1240    j0max=min(j0+ind_range_y,size(Amod,1));
1241    i0min=max(i0-ind_range_x,1);
1242    i0max=min(i0+ind_range_x,size(Amod,2));
1243    Asub=Amod(j0min:j0max,i0min:i0max);
1244    x_profile=sum(Asub,1);
1245    y_profile=sum(Asub,2);
1246    [Amax,ind_x_max]=max(x_profile);
1247    [Amax,ind_y_max]=max(y_profile);
1248    %sub-pixel improvement using moments
1249    x_shift=0;
1250    y_shift=0;
1251    if ind_x_max+2<=numel(x_profile) && ind_x_max-2>=1
1252        Atop=x_profile(ind_x_max-2:ind_x_max+2);
1253        x_shift=sum(Atop.*[-2 -1 0 1 2])/sum(Atop);
1254    end
1255    if ind_y_max+2<=numel(y_profile) && ind_y_max-2>=1
1256        Atop=y_profile(ind_y_max-2:ind_y_max+2);
1257        y_shift=sum(Atop.*[-2 -1 0 1 2]')/sum(Atop);
1258    end
1259    Delta(ipoint,1)=(x_shift+ind_x_max+i0min-i0-1)*Dx;%shift from the initial guess
1260    Delta(ipoint,2)=(y_shift+ind_y_max+j0min-j0-1)*Dy;
1261end
1262Tmod=T(:,(1:2))+Delta;
1263[Xpx,Ypx]=px_XYZ(GeometryCalib,Tmod(:,1),Tmod(:,2));
1264for ipoint=1:nbpoints
1265     Coord{ipoint,1}=num2str(T(ipoint,1),4);%display coordiantes with 4 digits
1266     Coord{ipoint,2}=num2str(T(ipoint,2),4);%display coordiantes with 4 digits
1267     Coord{ipoint,3}=num2str(T(ipoint,3),4);%display coordiantes with 4 digits;
1268     Coord{ipoint,4}=num2str(Xpx(ipoint),4);%display coordiantes with 4 digits
1269     Coord{ipoint,5}=num2str(Ypx(ipoint),4);%display coordiantes with 4 digits
1270end
1271Tabchar=cell2tab(Coord(end:-1:1,:),' | ');
1272Tabchar=[Tabchar ;{'......'}];
1273set(handles.ListCoord,'Value',1)
1274set(handles.ListCoord,'String',Tabchar)
1275MenuPlot_Callback(hObject, eventdata, handles)
1276
1277%-----------------------------------------------------------------------
1278function MenuTranslatePoints_Callback(hObject, eventdata, handles)
1279%-----------------------------------------------------------------------
1280%hcalib=get(handles.calib_type,'parent');%handles of the GUI geometry_calib
1281CalibData=get(handles.geometry_calib,'UserData');
1282Tinput=[];%default
1283if isfield(CalibData,'translate')
1284    Tinput=CalibData.translate;
1285end
1286T=translate_points(Tinput);%display translate_points GUI and get shift parameters
1287CalibData.translate=T;
1288set(handles.geometry_calib,'UserData',CalibData)
1289%translation
1290Coord_cell=get(handles.ListCoord,'String');
1291data=read_geometry_calib(Coord_cell);
1292data.Coord(:,1)=T(1)+data.Coord(:,1);
1293data.Coord(:,2)=T(2)+data.Coord(:,2);
1294data.Coord(:,3)=T(3)+data.Coord(:,3);
1295data.Coord(:,[4 5])=data.Coord(:,[4 5]);
1296for i=1:size(data.Coord,1)
1297    for j=1:5
1298          Coord{i,j}=num2str(data.Coord(i,j),4);%phys x,y,z
1299   end
1300end
1301Tabchar=cell2tab(Coord,' | ');
1302Tabchar=[Tabchar; {'.....'}];
1303%set(handles.ListCoord,'Value',1)
1304set(handles.ListCoord,'String',Tabchar)
1305
1306
1307% --------------------------------------------------------------------
1308function MenuRotatePoints_Callback(hObject, eventdata, handles)
1309%hcalib=get(handles.calib_type,'parent');%handles of the GUI geometry_calib
1310CalibData=get(handles.geometry_calib,'UserData');
1311Tinput=[];%default
1312if isfield(CalibData,'rotate')
1313    Tinput=CalibData.rotate;
1314end
1315T=rotate_points(Tinput);%display translate_points GUI and get shift parameters
1316CalibData.rotate=T;
1317set(handles.geometry_calib,'UserData',CalibData)
1318%-----------------------------------------------------
1319%rotation
1320Phi=T(1);
1321O_x=0;%default
1322O_y=0;%default
1323if numel(T)>=2
1324    O_x=T(2);%default
1325end
1326if numel(T)>=3
1327    O_y=T(3);%default
1328end
1329Coord_cell=get(handles.ListCoord,'String');
1330data=read_geometry_calib(Coord_cell);
1331r1=cos(pi*Phi/180);
1332r2=-sin(pi*Phi/180);
1333r3=sin(pi*Phi/180);
1334r4=cos(pi*Phi/180);
1335x=data.Coord(:,1)-O_x;
1336y=data.Coord(:,2)-O_y;
1337data.Coord(:,1)=r1*x+r2*y;
1338data.Coord(:,2)=r3*x+r4*y;
1339% data.Coord(:,[4 5])=data.Coord(:,[4 5]);
1340for i=1:size(data.Coord,1)
1341    for j=1:5
1342          Coord{i,j}=num2str(data.Coord(i,j),4);%phys x,y,z
1343   end
1344end
1345Tabchar=cell2tab(Coord,' | ');
1346Tabchar=[Tabchar;{'......'}];
1347set(handles.ListCoord,'Value',1)
1348set(handles.ListCoord,'String',Tabchar)
1349
1350
1351% %------------------------------------------------------------------------
1352% % --- Executes on button press in rotation.
1353% function rotation_Callback(hObject, eventdata, handles)
1354% %------------------------------------------------------------------------
1355% angle_rot=(pi/180)*str2num(get(handles.Phi,'String'));
1356% Coord_cell=get(handles.ListCoord,'String');
1357% data=read_geometry_calib(Coord_cell);
1358% data.Coord(:,1)=cos(angle_rot)*data.Coord(:,1)+sin(angle_rot)*data.Coord(:,2);
1359% data.Coord(:,1)=-sin(angle_rot)*data.Coord(:,1)+cos(angle_rot)*data.Coord(:,2);
1360% set(handles.XObject,'String',num2str(data.Coord(:,1),4));
1361% set(handles.YObject,'String',num2str(data.Coord(:,2),4));
1362
1363
1364%------------------------------------------------------------------------
1365% image transform from px to phys
1366%INPUT:
1367%Zindex: index of plane
1368% function [A_out,Rangx,Rangy]=phys_Ima(A,Calib,ZIndex)
1369% %------------------------------------------------------------------------
1370% xcorner=[];
1371% ycorner=[];
1372% npx=[];
1373% npy=[];
1374% siz=size(A)
1375% npx=[npx siz(2)];
1376% npy=[npy siz(1)]
1377% xima=[0.5 siz(2)-0.5 0.5 siz(2)-0.5];%image coordinates of corners
1378% yima=[0.5 0.5 siz(1)-0.5 siz(1)-0.5];
1379% [xcorner,ycorner]=phys_XYZ(Calib,xima,yima,ZIndex);%corresponding physical coordinates
1380% Rangx(1)=min(xcorner);
1381% Rangx(2)=max(xcorner);
1382% Rangy(2)=min(ycorner);
1383% Rangy(1)=max(ycorner);
1384% test_multi=(max(npx)~=min(npx)) | (max(npy)~=min(npy));
1385% npx=max(npx);
1386% npy=max(npy);
1387% x=linspace(Rangx(1),Rangx(2),npx);
1388% y=linspace(Rangy(1),Rangy(2),npy);
1389% [X,Y]=meshgrid(x,y);%grid in physical coordiantes
1390% vec_B=[];
1391%
1392% zphys=0; %default
1393% if isfield(Calib,'SliceCoord') %.Z= index of plane
1394%    SliceCoord=Calib.SliceCoord(ZIndex,:);
1395%    zphys=SliceCoord(3); %to generalize for non-parallel planes
1396% end
1397% [XIMA,YIMA]=px_XYZ(Calib,X,Y,zphys);%corresponding image indices for each point in the real space grid
1398% XIMA=reshape(round(XIMA),1,npx*npy);%indices reorganized in 'line'
1399% YIMA=reshape(round(YIMA),1,npx*npy);
1400% flagin=XIMA>=1 & XIMA<=npx & YIMA >=1 & YIMA<=npy;%flagin=1 inside the original image
1401% testuint8=isa(A,'uint8');
1402% testuint16=isa(A,'uint16');
1403% if numel(siz)==2 %(B/W images)
1404%     vec_A=reshape(A,1,npx*npy);%put the original image in line
1405%     ind_in=find(flagin);
1406%     ind_out=find(~flagin);
1407%     ICOMB=((XIMA-1)*npy+(npy+1-YIMA));
1408%     ICOMB=ICOMB(flagin);%index corresponding to XIMA and YIMA in the aligned original image vec_A
1409%     vec_B(ind_in)=vec_A(ICOMB);
1410%     vec_B(ind_out)=zeros(size(ind_out));
1411%     A_out=reshape(vec_B,npy,npx);%new image in real coordinates
1412% elseif numel(siz)==3     
1413%     for icolor=1:siz(3)
1414%         vec_A=reshape(A{icell}(:,:,icolor),1,npx*npy);%put the original image in line
1415%         ind_in=find(flagin);
1416%         ind_out=find(~flagin);
1417%         ICOMB=((XIMA-1)*npy+(npy+1-YIMA));
1418%         ICOMB=ICOMB(flagin);%index corresponding to XIMA and YIMA in the aligned original image vec_A
1419%         vec_B(ind_in)=vec_A(ICOMB);
1420%         vec_B(ind_out)=zeros(size(ind_out));
1421%         A_out(:,:,icolor)=reshape(vec_B,npy,npx);%new image in real coordinates
1422%     end
1423% end
1424% if testuint8
1425%     A_out=uint8(A_out);
1426% end
1427% if testuint16
1428%     A_out=uint16(A_out);
1429% end
1430
1431%------------------------------------------------------------------------
1432% pointwise transform from px to phys
1433%INPUT:
1434%Z: index of plane
1435% function [Xphys,Yphys,Zphys]=phys_XYZ(Calib,X,Y,Z)
1436% %------------------------------------------------------------------------
1437% if exist('Z','var')& isequal(Z,round(Z))& Z>0 & isfield(Calib,'SliceCoord')&length(Calib.SliceCoord)>=Z
1438%     Zindex=Z;
1439%     Zphys=Calib.SliceCoord(Zindex,3);%GENERALISER AUX CAS AVEC ANGLE
1440% else
1441%     Zphys=0;
1442% end
1443% if ~exist('X','var')||~exist('Y','var')
1444%     Xphys=[];
1445%     Yphys=[];%default
1446%     return
1447% end
1448% Xphys=X;%default
1449% Yphys=Y;
1450% %image transform
1451% if isfield(Calib,'R')
1452%     R=(Calib.R)';
1453%     Dx=R(5)*R(7)-R(4)*R(8);
1454%     Dy=R(1)*R(8)-R(2)*R(7);
1455%     D0=Calib.f*(R(2)*R(4)-R(1)*R(5));
1456%     Z11=R(6)*R(8)-R(5)*R(9);
1457%     Z12=R(2)*R(9)-R(3)*R(8); 
1458%     Z21=R(4)*R(9)-R(6)*R(7);
1459%     Z22=R(3)*R(7)-R(1)*R(9);
1460%     Zx0=R(3)*R(5)-R(2)*R(6);
1461%     Zy0=R(1)*R(6)-R(3)*R(4);
1462%     A11=R(8)*Calib.Ty-R(5)*Calib.Tz+Z11*Zphys;
1463%     A12=R(2)*Calib.Tz-R(8)*Calib.Tx+Z12*Zphys;
1464%     A21=-R(7)*Calib.Ty+R(4)*Calib.Tz+Z21*Zphys;
1465%     A22=-R(1)*Calib.Tz+R(7)*Calib.Tx+Z11*Zphys;
1466%     X0=Calib.f*(R(5)*Calib.Tx-R(2)*Calib.Ty+Zx0*Zphys);
1467%     Y0=Calib.f*(-R(4)*Calib.Tx+R(1)*Calib.Ty+Zy0*Zphys);
1468%         %px to camera:
1469%     Xd=(Calib.dpx/Calib.sx)*(X-Calib.Cx); % sensor coordinates
1470%     Yd=Calib.dpy*(Y-Calib.Cy);
1471%     dist_fact=1+Calib.kappa1*(Xd.*Xd+Yd.*Yd); %distortion factor
1472%     Xu=dist_fact.*Xd;%undistorted sensor coordinates
1473%     Yu=dist_fact.*Yd;
1474%     denom=Dx*Xu+Dy*Yu+D0;
1475%     % denom2=denom.*denom;
1476%     Xphys=(A11.*Xu+A12.*Yu+X0)./denom;%world coordinates
1477%     Yphys=(A21.*Xu+A22.*Yu+Y0)./denom;
1478% end
1479
1480
1481% --------------------------------------------------------------------
1482function MenuImportPoints_Callback(hObject, eventdata, handles)
1483fileinput=browse_xml(hObject, eventdata, handles);
1484if isempty(fileinput)
1485    return
1486end
1487[s,errormsg]=imadoc2struct(fileinput,'GeometryCalib');
1488GeometryCalib=s.GeometryCalib;
1489%GeometryCalib=load_calib(hObject, eventdata, handles)
1490calib=reshape(GeometryCalib.PointCoord,[],1);
1491for ilist=1:numel(calib)
1492    CoordCell{ilist}=num2str(calib(ilist));
1493end
1494CoordCell=reshape(CoordCell,[],5);
1495Tabchar=cell2tab(CoordCell,' | ');%transform cells into table ready for display
1496Tabchar=[Tabchar;{'......'}];
1497set(handles.ListCoord,'Value',1)
1498set(handles.ListCoord,'String',Tabchar)
1499MenuPlot_Callback(handles.geometry_calib, [], handles)
1500
1501% -----------------------------------------------------------------------
1502function MenuImportIntrinsic_Callback(hObject, eventdata, handles)
1503%------------------------------------------------------------------------
1504fileinput=browse_xml(hObject, eventdata, handles);
1505if isempty(fileinput)
1506    return
1507end
1508[s,errormsg]=imadoc2struct(fileinput,'GeometryCalib');
1509GeometryCalib=s.GeometryCalib;
1510display_intrinsic(GeometryCalib,handles)
1511
1512% -----------------------------------------------------------------------
1513function MenuImportAll_Callback(hObject, eventdata, handles)
1514%------------------------------------------------------------------------
1515fileinput=browse_xml(hObject, eventdata, handles);
1516if ~isempty(fileinput)
1517    loadfile(handles,fileinput)
1518end
1519
1520% -----------------------------------------------------------------------
1521% --- Executes on menubar option Import/Grid file: introduce previous grid files
1522function MenuGridFile_Callback(hObject, eventdata, handles)
1523% -----------------------------------------------------------------------
1524inputfile=browse_xml(hObject, eventdata, handles);
1525listfile=get(handles.coord_files,'string');
1526if isequal(listfile,{''})
1527    listfile={inputfile};
1528else
1529    listfile=[listfile;{inputfile}];%update the list of coord files
1530end
1531set(handles.coord_files,'string',listfile);
1532
1533%------------------------------------------------------------------------
1534% --- 'key_press_fcn:' function activated when a key is pressed on the keyboard
1535function key_press_fcn(hObject,eventdata,handles)
1536%------------------------------------------------------------------------
1537xx=double(get(handles.geometry_calib,'CurrentCharacter')); %get the keyboard character
1538if ismember(xx,[8 127])%backspace or delete
1539    Coord_cell=get(handles.ListCoord,'String');
1540    val=get(handles.ListCoord,'Value');
1541     if max(val)<numel(Coord_cell) % the last element '...' has not been selected
1542        Coord_cell(val)=[];%remove the selected line
1543        set(handles.ListCoord,'Value',min(val))
1544        set(handles.ListCoord,'String',Coord_cell)         
1545        ListCoord_Callback(hObject, eventdata, handles)
1546        MenuPlot_Callback(hObject,eventdata,handles)
1547     end
1548end
1549
1550%------------------------------------------------------------------------
1551function fileinput=browse_xml(hObject, eventdata, handles)
1552%------------------------------------------------------------------------
1553fileinput=[];%default
1554oldfile=''; %default
1555UserData=get(handles.geometry_calib,'UserData');
1556if isfield(UserData,'XmlInputFile')
1557    oldfile=UserData.XmlInputFile;
1558end
1559[FileName, PathName, filterindex] = uigetfile( ...
1560       {'*.xml;*.mat', ' (*.xml,*.mat)';
1561       '*.xml',  '.xml files '; ...
1562        '*.mat',  '.mat matlab files '}, ...
1563        'Pick a file',oldfile);
1564fileinput=[PathName FileName];%complete file name
1565testblank=findstr(fileinput,' ');%look for blanks
1566if ~isempty(testblank)
1567    msgbox_uvmat('ERROR','forbidden input file name or path: no blank character allowed')
1568    return
1569end
1570sizf=size(fileinput);
1571if (~ischar(fileinput)||~isequal(sizf(1),1)),return;end
1572UserData.XmlInputFile=fileinput;
1573set(handles.geometry_calib,'UserData',UserData)%record current file foer further use of browser
1574
1575% -----------------------------------------------------------------------
1576function Heading=loadfile(handles,fileinput)
1577%------------------------------------------------------------------------
1578Heading=[];%default
1579[s,errormsg]=imadoc2struct(fileinput,'GeometryCalib');
1580if ~isempty(errormsg)
1581    msgbox_uvmat('ERROR',['Error for reading ' fileinput ': '  errormsg])
1582    return
1583end
1584if ~isempty(s.Heading)
1585    Heading=s.Heading;
1586end
1587   
1588GeometryCalib=s.GeometryCalib;
1589fx=1;fy=1;Cx=0;Cy=0;kc=0; %default
1590%     Tabchar={};
1591CoordCell={};
1592%     kc=0;%default
1593%     f1=1000;
1594%     f2=1000;
1595%     hhuvmat=guidata(findobj(allchild(0),'Name','uvmat'));
1596%     Cx=str2num(get(hhuvmat.npx,'String'))/2;
1597%     Cy=str2num(get(hhuvmat.npy,'String'))/2;
1598Tabchar={};%default
1599val_cal=1;%default
1600if ~isempty(GeometryCalib)
1601    % choose the calibration option
1602    if isfield(GeometryCalib,'CalibrationType')
1603       calib_list=get(handles.calib_type,'String');
1604       for ilist=1:numel(calib_list)
1605           if strcmp(calib_list{ilist},GeometryCalib.CalibrationType)
1606               val_cal=ilist;
1607               break
1608           end
1609       end
1610    end
1611    display_intrinsic(GeometryCalib,handles)%intrinsic param
1612    %extrinsic param
1613    if isfield(GeometryCalib,'Tx_Ty_Tz')
1614        Tx_Ty_Tz=GeometryCalib.Tx_Ty_Tz;
1615        set(handles.Tx,'String',num2str(GeometryCalib.Tx_Ty_Tz(1),4))
1616        set(handles.Ty,'String',num2str(GeometryCalib.Tx_Ty_Tz(2),4))
1617        set(handles.Tz,'String',num2str(GeometryCalib.Tx_Ty_Tz(3),4))
1618    end
1619    if isfield(GeometryCalib,'omc')
1620        set(handles.Phi,'String',num2str(GeometryCalib.omc(1),4))
1621        set(handles.Theta,'String',num2str(GeometryCalib.omc(2),4))
1622        set(handles.Psi,'String',num2str(GeometryCalib.omc(3),4))
1623    end
1624    calib=reshape(GeometryCalib.PointCoord,[],1);
1625    for ilist=1:numel(calib)
1626        CoordCell{ilist}=num2str(calib(ilist));
1627    end
1628    CoordCell=reshape(CoordCell,[],5);
1629    Tabchar=cell2tab(CoordCell,' | ');%transform cells into table ready for display
1630    MenuPlot_Callback(handles.geometry_calib, [], handles)
1631end
1632set(handles.calib_type,'Value',val_cal)
1633Tabchar=[Tabchar;{'......'}];
1634set(handles.ListCoord,'Value',1)
1635set(handles.ListCoord,'String',Tabchar)
1636
1637if isempty(CoordCell)% allow mouse action by default in the absence of input points
1638    set(handles.edit_append,'Value',1)
1639    set(handles.edit_append,'BackgroundColor',[1 1 0])
1640else % does not allow mouse action by default in the presence of input points
1641    set(handles.edit_append,'Value',0)
1642    set(handles.edit_append,'BackgroundColor',[0.7 0.7 0.7])
1643end
1644
1645%------------------------------------------------------------------------
1646%---display calibration intrinsic parameters
1647function display_intrinsic(GeometryCalib,handles)
1648%------------------------------------------------------------------------
1649fx=[];
1650fy=[];
1651if isfield(GeometryCalib,'fx_fy')
1652    fx=GeometryCalib.fx_fy(1);
1653    fy=GeometryCalib.fx_fy(2);
1654end
1655Cx_Cy=[0 0];%default
1656if isfield(GeometryCalib,'Cx_Cy')
1657    Cx_Cy=GeometryCalib.Cx_Cy;
1658end
1659kc=0;
1660if isfield(GeometryCalib,'kc')
1661    kc=GeometryCalib.kc; %* GeometryCalib.focal*GeometryCalib.focal;
1662end
1663set(handles.fx,'String',num2str(fx,5))
1664set(handles.fy,'String',num2str(fy,5))
1665set(handles.Cx,'String',num2str(Cx_Cy(1),'%1.1f'))
1666set(handles.Cy,'String',num2str(Cx_Cy(2),'%1.1f'))
1667set(handles.kc,'String',num2str(kc,'%1.4f'))
1668
1669
Note: See TracBrowser for help on using the repository browser.