source: trunk/src/geometry_calib.m @ 231

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

interactive test for piv introduced various bug corrections

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