source: trunk/src/geometry_calib.m @ 158

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

CoordType? not used, replaced by CoordUnit?
bug repair in check_field_structure

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