source: trunk/src/geometry_calib.m @ 196

Last change on this file since 196 was 196, checked in by sommeria, 13 years ago

bug corrections. Introduction of water wheight in calibration

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