source: trunk/src/geometry_calib.m @ 501

Last change on this file since 501 was 498, checked in by sommeria, 9 years ago

various bug corrections, compatibilty with older PIV data

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