source: trunk/src/geometry_calib.m @ 839

Last change on this file since 839 was 838, checked in by sommeria, 9 years ago

bug corrected in geometry_calib

File size: 58.4 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%=======================================================================
13% Copyright 2008-2014, LEGI UMR 5519 / CNRS UJF G-INP, Grenoble, France
14%   http://www.legi.grenoble-inp.fr
15%   Joel.Sommeria - Joel.Sommeria (A) legi.cnrs.fr
16%
17%     This file is part of the toolbox UVMAT.
18%
19%     UVMAT is free software; you can redistribute it and/or modify
20%     it under the terms of the GNU General Public License as published
21%     by the Free Software Foundation; either version 2 of the license,
22%     or (at your option) any later version.
23%
24%     UVMAT is distributed in the hope that it will be useful,
25%     but WITHOUT ANY WARRANTY; without even the implied warranty of
26%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
27%     GNU General Public License (see LICENSE.txt) for more details.
28%=======================================================================
29
30function varargout = geometry_calib(varargin)
31% GEOMETRY_CALIB M-file for geometry_calib.fig
32%      GEOMETRY_CALIB, by itself, creates a MenuCoord GEOMETRY_CALIB or raises the existing
33%      singleton*.
34%
35%      H = GEOMETRY_CALIB returns the handle to a MenuCoord GEOMETRY_CALIB or the handle to
36%      the existing singleton*.
37%
38%      GEOMETRY_CALIB('CALLBACK',hObject,eventData,handles,...) calls the local
39%      function named CALLBACK in GEOMETRY_CALIB.M with the given input arguments.
40%
41%      GEOMETRY_CALIB('Property','Value',...) creates a MenuCoord GEOMETRY_CALIB or raises the
42%      existing singleton*.  Starting from the left, property value pairs are
43%      applied to the GUI before geometry_calib_OpeningFunction gets called.  An
44%      unrecognized property name or invalid value makes property application
45%      stop.  All inputs are passed to geometry_calib_OpeningFcn via varargin.
46%
47%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
48%      instance to run (singleton)".
49%
50% See also: GUIDE, GUIDATA, GUIHANDLES
51
52% Edit the above text to modify the response to help geometry_calib
53
54% Last Modified by GUIDE v2.5 07-Dec-2014 15:50:44
55
56% Begin initialization code - DO NOT edit
57gui_Singleton = 1;
58gui_State = struct('gui_Name',       mfilename, ...
59                   'gui_Singleton',  gui_Singleton, ...
60                   'gui_OpeningFcn', @geometry_calib_OpeningFcn, ...
61                   'gui_OutputFcn',  @geometry_calib_OutputFcn, ...
62                   'gui_LayoutFcn',  [] , ...
63                   'gui_Callback',   []);
64if nargin
65   [pp,ff]=fileparts(which(varargin{1})); % name of the input file
66   if strcmp(ff,mfilename)% if we are activating a sub-function of geometry_calib
67   % ~isempty(regexp(varargin{1},'_Callback','once'))
68    gui_State.gui_Callback = str2func(varargin{1});
69   end
70end
71
72if nargout
73    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
74else
75    gui_mainfcn(gui_State, varargin{:});
76end
77% End initialization code - DO NOT edit
78
79
80% --- Executes just before geometry_calib is made visible.
81%INPUT:
82%handles: handles of the geometry_calib interface elements
83% PlotHandles: set of handles of the elements contolling the plotting
84% parameters on the uvmat interface (obtained by 'get_plot_handle.m')
85%------------------------------------------------------------------------
86function geometry_calib_OpeningFcn(hObject, eventdata, handles,inputfile)
87%------------------------------------------------------------------------
88% Choose default command line output for geometry_calib
89
90handles.output = hObject;
91
92% Update handles structure
93guidata(hObject, handles);
94set(hObject,'DeleteFcn',{@closefcn})%
95%set(hObject,'WindowButtonDownFcn',{'mouse_alt_gui',handles}) % allows mouse action with right button (zoom for uicontrol display)
96
97%% position
98set(0,'Unit','pixels')
99ScreenSize=get(0,'ScreenSize');% get the size of the screen, to put the fig on the upper right
100Left=ScreenSize(3)- 460; %right edge close to the right, with margin=40 (GUI width=420 px)
101if ScreenSize(4)>920
102    Height=840;%default height of the GUI
103    Bottom=ScreenSize(4)-Height-40; %put fig at top right
104else
105    Height=ScreenSize(4)-80;
106    Bottom=40; % GUI lies o the screen bottom (with margin =40)
107end
108set(handles.calib_type,'Position',[1 Height-40 194 30])%  rank 1
109set(handles.APPLY,'Position',[197 Height-40 110 30])%  rank 1
110set(handles.REPLICATE,'Position',[309 Height-40 110 30])%  rank 1
111set(handles.Intrinsic,'Position',[1 Height-40-2-92 418 92])%  rank 2
112set(handles.Extrinsic,'Position',[1 Height-40-4-92-75 418 75])%  rank 3
113set(handles.PointLists,'Position',[1 Height-40-6-92-75-117 418 117]) %  rank 4
114set(handles.CheckEnableMouse,'Position',[3 Height-362 208 30])%  rank 5
115set(handles.PLOT,'Position',[3 Height-394 120 30])%  rank 6
116set(handles.Copy,'Position',[151 Height-394 120 30])%  rank 6
117set(handles.ClearAll,'Position',[297 Height-394 120 30])%  rank 6
118set(handles.ClearPoint,'Position',[297 Height-362 120 30])%  rank 6
119set(handles.CoordLine,'Position',[211 Height-362 86 30])%  rank 6
120set(handles.phys_title,'Position',[38 Height-426 125 20])%  rank 7
121set(handles.CoordUnit,'Position',[151 Height-426 120 30])%  rank 7
122set(handles.px_title,'Position',[272 Height-426 125 20])%  rank 7
123set(handles.ListCoord,'Position',[1 20 418 Height-446])% rank 8
124set(handles.geometry_calib,'Position',[Left Bottom 420 Height])
125
126%set menu of calibration options
127set(handles.calib_type,'String',{'rescale';'linear';'3D_linear';'3D_quadr';'3D_extrinsic'})
128if exist('inputfile','var')&& ~isempty(inputfile)
129    [RootPath,SubDir,RootFile,tild,tild,tild,tild,FileExt]=fileparts_uvmat(inputfile);
130    struct.XmlInputFile=find_imadoc(RootPath,SubDir,RootFile,FileExt);
131    set(handles.ListCoord,'Data',[])
132    if exist(struct.XmlInputFile,'file')
133        Heading=loadfile(handles,struct.XmlInputFile);% load data from the xml file and fill the GUI
134        if isfield(Heading,'Campaign')&& ischar(Heading.Campaign)
135            struct.Campaign=Heading.Campaign;
136        end
137    end   
138    set(hObject,'UserData',struct)
139end
140
141%------------------------------------------------------------------------
142% --- Outputs from this function are returned to the command line.
143function varargout = geometry_calib_OutputFcn(~, eventdata, handles)
144%------------------------------------------------------------------------
145% Get default command line output from handles structure
146varargout{1} = handles.output;
147varargout{2}=handles;
148%
149%------------------------------------------------------------------------
150% executed when closing: set the parent interface button to value 0
151function closefcn(gcbo,eventdata)
152%------------------------------------------------------------------------
153huvmat=findobj(allchild(0),'Name','uvmat');
154if ~isempty(huvmat)
155    handles=guidata(huvmat);
156    set(handles.MenuCalib,'Checked','off')
157    hobject=findobj(handles.PlotAxes,'tag','calib_points');
158    if ~isempty(hobject)
159        delete(hobject)
160    end
161    hobject=findobj(handles.PlotAxes,'tag','calib_marker');
162    if ~isempty(hobject)
163        delete(hobject)
164    end   
165end
166
167%------------------------------------------------------------------------
168% --- Executes on button press APPLY (used to launch the calibration).
169function APPLY_Callback(hObject, eventdata, handles)
170%------------------------------------------------------------------------
171%% look for the GUI uvmat and check for an image as input
172set(handles.APPLY,'BackgroundColor',[1 1 0])
173huvmat=findobj(allchild(0),'Name','uvmat');
174hhuvmat=guidata(huvmat);%handles of elements in the GUI uvmat
175
176RootPath='';
177if ~isempty(hhuvmat.RootPath)&& ~isempty(hhuvmat.RootFile)
178    RootPath=get(hhuvmat.RootPath,'String');
179    SubDirBase=regexprep(get(hhuvmat.SubDir,'String'),'\..+$','');
180    outputfile=[fullfile(RootPath,SubDirBase) '.xml'];%xml file associated with the currently displayed image
181else
182    question={'save the calibration data and point coordinates in'};
183    def={fullfile(RootPath,'ObjectCalib.xml')};
184    options.Resize='on';
185    answer=inputdlg(question,'',1,def,options);
186    outputfile=answer{1};
187end
188[GeometryCalib,index]=calibrate(handles,hhuvmat);% apply calibration
189
190if isempty(GeometryCalib) % if calibration cancelled
191    set(handles.APPLY,'BackgroundColor',[1 0 1])
192else   % if calibration confirmed
193   
194    %% copy the xml file from the old location if appropriate, then update with the calibration parameters
195    if ~exist(outputfile,'file') && ~isempty(SubDirBase)
196        oldxml=[fullfile(RootPath,SubDirBase,get(hhuvmat.RootFile,'String')) '.xml'];
197        if exist(oldxml,'file')
198            [success,message]=copyfile(oldxml,outputfile);%copy the old xml file to a new one with the new convention
199        end
200    end
201    errormsg=update_imadoc(GeometryCalib,outputfile,'GeometryCalib');% introduce the calibration data in the xml file
202    if ~strcmp(errormsg,'')
203        msgbox_uvmat('ERROR',errormsg);
204    end
205   
206    %% display image with new calibration in the currently opened uvmat interface
207    FieldList=get(hhuvmat.FieldName,'String');
208    val=get(hhuvmat.FieldName,'Value');
209    if strcmp(FieldList{val},'image')
210        set(hhuvmat.CheckFixLimits,'Value',0)% put FixedLimits option to 'off' to plot the whole image
211        UserData=get(handles.geometry_calib,'UserData');
212        UserData.XmlInputFile=outputfile;%save the current xml file name
213        set(handles.geometry_calib,'UserData',UserData)
214        uvmat('InputFileREFRESH_Callback',hObject,eventdata,hhuvmat); %file input with xml reading  in uvmat, show the image in phys coordinates
215        PLOT_Callback(hObject, eventdata, handles)
216        set(handles.CoordLine,'string',num2str(index))
217        Coord=get(handles.ListCoord,'Data');
218        update_calib_marker(Coord(index,:)); %indicate the point with max deviations from phys coord to calibration
219        figure(handles.geometry_calib)% put the GUI geometry_calib in front
220        set(handles.APPLY,'BackgroundColor',[1 0 0]) % set APPLY button to red color
221    else
222        msgbox_uvmat('WARNING','open the image to see the effect of the new calibration')
223    end
224end
225
226%------------------------------------------------------------------------
227% --- Executes on button press in REPLICATE
228function REPLICATE_Callback(hObject, eventdata, handles)
229%------------------------------------------------------------------------
230
231%% look for the GUI uvmat and check for an image as input
232huvmat=findobj(allchild(0),'Name','uvmat');
233hhuvmat=guidata(huvmat);%handles of elements in the GUI uvmat
234GeometryCalib=calibrate(handles,hhuvmat);% apply calibration
235
236%% open the GUI browse_data
237CalibData=get(handles.geometry_calib,'UserData');%read the calibration image source on the interface userdata
238if isfield(CalibData,'XmlInputFile')
239    InputDir=fileparts(fileparts(CalibData.XmlInputFile));
240end
241SubProject=uigetfile_uvmat('open folder of subproject to calibrate',InputDir,'uigetdir');
242% answer=msgbox_uvmat('INPUT_TXT','Campaign to calibrate?',InputDir);
243% if strcmp(answer,'Cancel')
244%     return
245% end
246OutPut=browse_data(SubProject);
247nbcalib=0;
248for ilist=1:numel(OutPut.Experiment)
249    SubDirBase=regexprep(OutPut.DataSeries{1},'\..+$','');
250    XmlName=fullfile(OutPut.Campaign,OutPut.Experiment{ilist},[SubDirBase '.xml']);
251    % copy the xml file from the old location if appropriate, then update with the calibration parameters
252    if ~exist(XmlName,'file') && ~isempty(SubDirBase)
253        oldxml=fullfile(OutPut.Campaign,OutPut.Experiment{ilist},SubDirBase,[get(hhuvmat.RootFile,'String') '.xml']);
254        if exist(oldxml,'file')
255            [success,message]=copyfile(oldxml,XmlName);%copy the old xml file to a new one with the new convention
256        end
257    end
258    errormsg=update_imadoc(GeometryCalib,XmlName,'GeometryCalib');% introduce the calibration data in the xml file
259    if ~strcmp(errormsg,'')
260        msgbox_uvmat('ERROR',errormsg);
261    else
262        display([XmlName ' updated with calibration parameters'])
263        nbcalib=nbcalib+1;
264    end
265end
266msgbox_uvmat('CONFIMATION',[SubDirBase ' calibrated for ' num2str(nbcalib) ' experiments']);
267
268%------------------------------------------------------------------------
269% --- activate calibration and store parameters in ouputfile .
270function [GeometryCalib,index]=calibrate(handles,hhuvmat)
271%------------------------------------------------------------------------
272set(handles.CheckEnableMouse,'Value',0)% desactivate mouse (to avoid spurious creation of new points)
273%% read the current calibration points
274index=[];
275Coord=get(handles.ListCoord,'Data');
276Coord(:,6)=[];
277% apply the calibration, whose type is selected in  handles.calib_type
278GeometryCalib=[];
279if ~isempty(Coord)
280    calib_cell=get(handles.calib_type,'String');
281    val=get(handles.calib_type,'Value');
282    GeometryCalib=feval(['calib_' calib_cell{val}],Coord,handles);
283else
284    msgbox_uvmat('ERROR','No calibration points, abort')
285end
286if isempty(GeometryCalib)
287    return
288end
289Z_plane=[];
290if ~isempty(Coord)
291    %check error
292    X=Coord(:,1);
293    Y=Coord(:,2);
294    Z=Coord(:,3);
295    x_ima=Coord(:,4);
296    y_ima=Coord(:,5);
297    [Xpoints,Ypoints]=px_XYZ(GeometryCalib,X,Y,Z);
298    GeometryCalib.ErrorRms(1)=sqrt(mean((Xpoints-x_ima).*(Xpoints-x_ima)));
299    [GeometryCalib.ErrorMax(1),index(1)]=max(abs(Xpoints-x_ima));
300    GeometryCalib.ErrorRms(2)=sqrt(mean((Ypoints-y_ima).*(Ypoints-y_ima)));
301    [GeometryCalib.ErrorMax(2),index(2)]=max(abs(Ypoints-y_ima));
302    [tild,ind_dim]=max(GeometryCalib.ErrorMax);
303    index=index(ind_dim);
304    %set the Z position of the reference plane used for calibration
305    if isequal(max(Z),min(Z))%Z constant
306        Z_plane=Z(1);
307        GeometryCalib.NbSlice=1;
308        GeometryCalib.SliceCoord=[0 0 Z_plane];
309    end
310end
311%set the coordinate unit
312unitlist=get(handles.CoordUnit,'String');
313unit=unitlist{get(handles.CoordUnit,'value')};
314GeometryCalib.CoordUnit=unit;
315%record the points
316GeometryCalib.SourceCalib.PointCoord=Coord;
317display_intrinsic(GeometryCalib,handles)%display calibration intrinsic parameters
318
319% Display extrinsinc parameters (rotation and translation of camera with  respect to the phys coordiantes)
320set(handles.Tx,'String',num2str(GeometryCalib.Tx_Ty_Tz(1),4))
321set(handles.Ty,'String',num2str(GeometryCalib.Tx_Ty_Tz(2),4))
322set(handles.Tz,'String',num2str(GeometryCalib.Tx_Ty_Tz(3),4))
323set(handles.Phi,'String',num2str(GeometryCalib.omc(1),4))
324set(handles.Theta,'String',num2str(GeometryCalib.omc(2),4))
325set(handles.Psi,'String',num2str(GeometryCalib.omc(3),4))
326
327%% store the calibration data, by default in the xml file of the currently displayed image
328UvData=get(hhuvmat.uvmat,'UserData');
329% NbSlice_j=1;%default
330% ZStart=Z_plane;
331% ZEnd=Z_plane;
332% volume_scan='n';
333% if isfield(UvData,'XmlData')
334%     if isfield(UvData.XmlData,'TranslationMotor')
335%         NbSlice_j=UvData.XmlData.TranslationMotor.Nbslice;
336%         ZStart=UvData.XmlData.TranslationMotor.ZStart/10;
337%         ZEnd=UvData.XmlData.TranslationMotor.ZEnd/10;
338%         volume_scan='y';
339%     end
340% end
341
342answer=msgbox_uvmat('INPUT_Y-N',{'store calibration data';...
343    ['Error rms (along x,y)=' num2str(GeometryCalib.ErrorRms) ' pixels'];...
344    ['Error max (along x,y)=' num2str(GeometryCalib.ErrorMax) ' pixels']});
345
346%% get plane position(s)
347if ~strcmp(answer,'Yes')
348    GeometryCalib=[];
349    index=1;
350    return
351end
352if strcmp(calib_cell{val}(1:2),'3D')%set the plane position for 3D (projection) calibration
353    msgbox_uvmat('CONFIRMATION',{['The current image series is assumed by default in the plane of the calib points z=' num2str(Z_plane) ] ; 'can be modified by MenuSetSlice in the upper bar menu of uvmat'})
354%     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'};
355%     input_val=[{num2str(ZEnd)} {num2str(ZStart)} {num2str(ZStart)} {'1.333'} num2str(NbSlice_j) {volume_scan} {'0'} {'0'}];
356%     answer=inputdlg(input_key,'slice position(s)',ones(1,8), input_val,'on');
357%     GeometryCalib.NbSlice=str2double(answer{5});
358%     GeometryCalib.VolumeScan=answer{6};
359%     if isempty(answer)
360%         Z_plane=0; %default
361%     else
362%         Z_plane=linspace(str2double(answer{1}),str2double(answer{2}),GeometryCalib.NbSlice);
363%     end
364     GeometryCalib.SliceCoord=Z_plane'*[0 0 1];
365%     GeometryCalib.SliceAngle(:,3)=0;
366%     GeometryCalib.SliceAngle(:,2)=str2double(answer{7})*ones(GeometryCalib.NbSlice,1);%rotation around y axis (to generalise)
367%     GeometryCalib.SliceAngle(:,1)=str2double(answer{8})*ones(GeometryCalib.NbSlice,1);%rotation around x axis (to generalise)
368%     GeometryCalib.InterfaceCoord=[0 0 str2double(answer{3})];
369%     GeometryCalib.RefractionIndex=str2double(answer{4});
370end
371
372%------------------------------------------------------------------------
373% --- determine the parameters for a calibration by an affine function (rescaling and offset, no rotation)
374function GeometryCalib=calib_rescale(Coord,handles)
375%------------------------------------------------------------------------
376X=Coord(:,1);
377Y=Coord(:,2);% Z not used
378x_ima=Coord(:,4);
379y_ima=Coord(:,5);
380[px]=polyfit(X,x_ima,1);
381[py]=polyfit(Y,y_ima,1);
382% T_x=px(2);
383% T_y=py(2);
384GeometryCalib.CalibrationType='rescale';
385GeometryCalib.fx_fy=[px(1) py(1)];%.fx_fy corresponds to pxcm along x and y
386GeometryCalib.CoordUnit=[];% default value, to be updated by the calling function
387GeometryCalib.Tx_Ty_Tz=[px(2)/px(1) py(2)/py(1) 1];
388GeometryCalib.omc=[0 0 0];
389
390%------------------------------------------------------------------------
391% --- determine the parameters for a calibration by a linear transform matrix (rescale and rotation)
392function GeometryCalib=calib_linear(Coord,handles)
393%------------------------------------------------------------------------
394X=Coord(:,1);
395Y=Coord(:,2);% Z not used
396x_ima=Coord(:,4);
397y_ima=Coord(:,5);
398XY_mat=[ones(size(X)) X Y];
399a_X1=XY_mat\x_ima; %transformation matrix for X
400a_Y1=XY_mat\y_ima;%transformation matrix for X
401R=[a_X1(2),a_X1(3);a_Y1(2),a_Y1(3)];
402epsilon=sign(det(R));
403norm=abs(det(R));
404GeometryCalib.CalibrationType='linear';
405if (a_X1(2)/a_Y1(3))>0
406    GeometryCalib.fx_fy(1)=sqrt((a_X1(2)/a_Y1(3))*norm);
407else
408    GeometryCalib.fx_fy(1)=-sqrt(-(a_X1(2)/a_Y1(3))*norm);
409end
410GeometryCalib.fx_fy(2)=(a_Y1(3)/a_X1(2))*GeometryCalib.fx_fy(1);
411GeometryCalib.CoordUnit=[];% default value, to be updated by the calling function
412GeometryCalib.Tx_Ty_Tz=[a_X1(1)/GeometryCalib.fx_fy(1) a_Y1(1)/GeometryCalib.fx_fy(2) 1];
413R(1,:)=R(1,:)/GeometryCalib.fx_fy(1);
414R(2,:)=R(2,:)/GeometryCalib.fx_fy(2);
415R=[R;[0 0]];
416GeometryCalib.R=[R [0;0;-epsilon]];
417GeometryCalib.omc=(180/pi)*[acos(GeometryCalib.R(1,1)) 0 0];
418
419%------------------------------------------------------------------------
420% --- determine the tsai parameters for a view normal to the grid plane
421% NOT USED
422function GeometryCalib=calib_normal(Coord,handles)
423%------------------------------------------------------------------------
424Calib.f1=str2num(get(handles.fx,'String'));
425Calib.f2=str2num(get(handles.fy,'String'));
426Calib.k=str2num(get(handles.kc,'String'));
427Calib.Cx=str2num(get(handles.Cx,'String'));
428Calib.Cy=str2num(get(handles.Cy,'String'));
429%default
430if isempty(Calib.f1)
431    Calib.f1=25/0.012;
432end
433if isempty(Calib.f2)
434    Calib.f2=25/0.012;
435end
436if isempty(Calib.k)
437    Calib.k=0;
438end
439if isempty(Calib.Cx)||isempty(Calib.Cy)
440    huvmat=findobj(allchild(0),'Tag','uvmat');
441    hhuvmat=guidata(huvmat);
442    Calib.Cx=str2num(get(hhuvmat.num_Npx,'String'))/2;
443    Calib.Cx=str2num(get(hhuvmat.num_Npy,'String'))/2;
444end   
445%tsai parameters
446Calib.dpx=0.012;%arbitrary
447Calib.dpy=0.012;
448Calib.sx=Calib.f1*Calib.dpx/(Calib.f2*Calib.dpy);
449Calib.f=Calib.f2*Calib.dpy;
450Calib.kappa1=Calib.k/(Calib.f*Calib.f);
451
452%initial guess
453X=Coord(:,1);
454Y=Coord(:,2);
455Zmean=mean(Coord(:,3));
456x_ima=Coord(:,4)-Calib.Cx;
457y_ima=Coord(:,5)-Calib.Cy;
458XY_mat=[ones(size(X)) X Y];
459a_X1=XY_mat\x_ima; %transformation matrix for X
460a_Y1=XY_mat\y_ima;%transformation matrix for Y
461R=[a_X1(2),a_X1(3),0;a_Y1(2),a_Y1(3),0;0,0,-1];% rotation+ z axis reversal (upward)
462norm=sqrt(det(-R));
463calib_param(1)=0;% quadratic distortion
464calib_param(2)=a_X1(1);
465calib_param(3)=a_Y1(1);
466calib_param(4)=Calib.f/(norm*Calib.dpx)-R(3,3)*Zmean;
467calib_param(5)=angle(a_X1(2)+1i*a_X1(3));
468display(['initial guess=' num2str(calib_param)])
469
470%optimise the parameters: minimisation of error
471calib_param = fminsearch(@(calib_param) error_calib(calib_param,Calib,Coord),calib_param);
472
473GeometryCalib.CalibrationType='tsai_normal';
474GeometryCalib.focal=Calib.f;
475GeometryCalib.dpx_dpy=[Calib.dpx Calib.dpy];
476GeometryCalib.Cx_Cy=[Calib.Cx Calib.Cy];
477GeometryCalib.sx=Calib.sx;
478GeometryCalib.kappa1=calib_param(1);
479GeometryCalib.CoordUnit=[];% default value, to be updated by the calling function
480GeometryCalib.Tx_Ty_Tz=[calib_param(2) calib_param(3) calib_param(4)];
481alpha=calib_param(5);
482GeometryCalib.R=[cos(alpha) sin(alpha) 0;-sin(alpha) cos(alpha) 0;0 0 -1];
483
484%------------------------------------------------------------------------
485function GeometryCalib=calib_3D_linear(Coord,handles)
486%------------------------------------------------------------------------
487path_uvmat=which('uvmat');% check the path detected for source file uvmat
488path_UVMAT=fileparts(path_uvmat); %path to UVMAT
489huvmat=findobj(allchild(0),'Tag','uvmat');
490hhuvmat=guidata(huvmat);
491coord_files=get(handles.ListCoordFiles,'String');
492if ischar(coord_files)
493    coord_files={coord_files};
494end
495if isempty(coord_files{1}) || isequal(coord_files,{''})
496    coord_files={};
497end
498%retrieve the calibration points stored in the files listed in the popup list ListCoordFiles
499x_1=Coord(:,4:5)';%px coordinates of the ref points
500if ~strcmp(get(hhuvmat.Scalar,'Visible'),'on')
501    msgbox_uvmat('ERROR','An image needs to be opened in uvmat for calibration')
502  return
503end
504nx=str2num(get(hhuvmat.num_Npx,'String'));
505ny=str2num(get(hhuvmat.num_Npy,'String'));
506x_1(2,:)=ny-x_1(2,:);%reverse the y image coordinates
507X_1=Coord(:,1:3)';%phys coordinates of the ref points
508n_ima=numel(coord_files)+1;
509if ~isempty(coord_files)
510    msgbox_uvmat('CONFIRMATION',['The xy coordinates of the calibration points in ' num2str(n_ima) ' planes will be used'])
511    for ifile=1:numel(coord_files)
512    t=xmltree(coord_files{ifile});
513    s=convert(t);%convert to matlab structure
514        if isfield(s,'GeometryCalib')
515            if isfield(s.GeometryCalib,'SourceCalib')
516                if isfield(s.GeometryCalib.SourceCalib,'PointCoord')
517                PointCoord=s.GeometryCalib.SourceCalib.PointCoord;
518                Coord_file=zeros(length(PointCoord),5);%default
519                for i=1:length(PointCoord)
520                    line=str2num(PointCoord{i});
521                    Coord_file(i,4:5)=line(4:5);%px x
522                    Coord_file(i,1:3)=line(1:3);%phys x
523                end
524                eval(['x_' num2str(ifile+1) '=Coord_file(:,4:5)'';']);
525                eval(['x_' num2str(ifile+1) '(2,:)=ny-x_' num2str(ifile+1) '(2,:);' ]);
526                eval(['X_' num2str(ifile+1) '=Coord_file(:,1:3)'';']);
527                end
528            end
529        end
530    end
531end
532n_ima=numel(coord_files)+1;
533est_dist=[0;0;0;0;0];
534est_aspect_ratio=0;
535est_fc=[1;1];
536center_optim=0;
537run(fullfile(path_UVMAT,'toolbox_calib','go_calib_optim'));% apply fct 'toolbox_calib/go_calib_optim'
538if exist('Rc_1','var')
539    GeometryCalib.CalibrationType='3D_linear';
540    GeometryCalib.fx_fy=fc';
541    GeometryCalib.Cx_Cy=cc';
542    GeometryCalib.kc=kc(1);
543    GeometryCalib.CoordUnit=[];% default value, to be updated by the calling function
544    GeometryCalib.Tx_Ty_Tz=Tc_1';
545    GeometryCalib.R=Rc_1;
546    GeometryCalib.R(2,1:3)=-GeometryCalib.R(2,1:3);%inversion of the y image coordinate
547    GeometryCalib.Tx_Ty_Tz(2)=-GeometryCalib.Tx_Ty_Tz(2);%inversion of the y image coordinate
548    GeometryCalib.Cx_Cy(2)=ny-GeometryCalib.Cx_Cy(2);%inversion of the y image coordinate
549    GeometryCalib.omc=(180/pi)*omc_1;%angles in degrees
550    GeometryCalib.ErrorRMS=[];
551    GeometryCalib.ErrorMax=[];
552else
553    msgbox_uvmat('ERROR',['calibration function ' fullfile('toolbox_calib','go_calib_optim') ' did not converge: use multiple views or option 3D_extrinsic'])
554    GeometryCalib=[];
555end
556
557%------------------------------------------------------------------------
558function GeometryCalib=calib_3D_quadr(Coord,handles)
559%------------------------------------------------------------------
560
561path_uvmat=which('uvmat');% check the path detected for source file uvmat
562path_UVMAT=fileparts(path_uvmat); %path to UVMAT
563huvmat=findobj(allchild(0),'Tag','uvmat');
564hhuvmat=guidata(huvmat);
565if ~strcmp(get(hhuvmat.Scalar,'Visible'),'on')
566    msgbox_uvmat('ERROR','An image needs to be opened in uvmat for calibration')
567  return
568end
569% check_cond=0;
570coord_files=get(handles.ListCoordFiles,'String');
571if ischar(coord_files)
572    coord_files={coord_files};
573end
574if isempty(coord_files{1}) || isequal(coord_files,{''})
575    coord_files={};
576end
577
578%retrieve the calibration points stored in the files listed in the popup list ListCoordFiles
579x_1=Coord(:,4:5)';%px coordinates of the ref points
580nx=str2num(get(hhuvmat.num_Npx,'String'));
581ny=str2num(get(hhuvmat.num_Npy,'String'));
582x_1(2,:)=ny-x_1(2,:);%reverse the y image coordinates
583X_1=Coord(:,1:3)';%phys coordinates of the ref points
584n_ima=numel(coord_files)+1;
585if ~isempty(coord_files)
586    msgbox_uvmat('CONFIRMATION',['The xy coordinates of the calibration points in ' num2str(n_ima) ' planes will be used'])
587    for ifile=1:numel(coord_files)
588    t=xmltree(coord_files{ifile});
589    s=convert(t);%convert to matlab structure
590        if isfield(s,'GeometryCalib')
591            if isfield(s.GeometryCalib,'SourceCalib')
592                if isfield(s.GeometryCalib.SourceCalib,'PointCoord')
593                PointCoord=s.GeometryCalib.SourceCalib.PointCoord;
594                Coord_file=zeros(length(PointCoord),5);%default
595                for i=1:length(PointCoord)
596                    line=str2num(PointCoord{i});
597                    Coord_file(i,4:5)=line(4:5);%px x
598                    Coord_file(i,1:3)=line(1:3);%phys x
599                end
600                eval(['x_' num2str(ifile+1) '=Coord_file(:,4:5)'';']);
601                eval(['x_' num2str(ifile+1) '(2,:)=ny-x_' num2str(ifile+1) '(2,:);' ]);
602                eval(['X_' num2str(ifile+1) '=Coord_file(:,1:3)'';']);
603                end
604            end
605        end
606    end
607end
608n_ima=numel(coord_files)+1;
609est_dist=[1;0;0;0;0];
610est_aspect_ratio=1;
611center_optim=0;
612run(fullfile(path_UVMAT,'toolbox_calib','go_calib_optim'));% apply fct 'toolbox_calib/go_calib_optim'
613
614if exist('Rc_1','var')
615    GeometryCalib.CalibrationType='3D_quadr';
616    GeometryCalib.fx_fy=fc';
617    GeometryCalib.Cx_Cy=cc';
618    GeometryCalib.kc=kc(1);
619    GeometryCalib.CoordUnit=[];% default value, to be updated by the calling function
620    GeometryCalib.Tx_Ty_Tz=Tc_1';
621    GeometryCalib.R=Rc_1;
622    GeometryCalib.R(2,1:3)=-GeometryCalib.R(2,1:3);%inversion of the y image coordinate
623    GeometryCalib.Tx_Ty_Tz(2)=-GeometryCalib.Tx_Ty_Tz(2);%inversion of the y image coordinate
624    GeometryCalib.Cx_Cy(2)=ny-GeometryCalib.Cx_Cy(2);%inversion of the y image coordinate
625    GeometryCalib.omc=(180/pi)*omc_1;%angles in degrees
626    GeometryCalib.ErrorRMS=[];
627    GeometryCalib.ErrorMax=[];
628else
629    msgbox_uvmat('ERROR',['calibration function ' fullfile('toolbox_calib','go_calib_optim') ' did not converge: use multiple views or option 3D_extrinsic'])
630    GeometryCalib=[];
631end
632
633%------------------------------------------------------------------------
634function GeometryCalib=calib_3D_extrinsic(Coord,handles)
635%------------------------------------------------------------------
636path_uvmat=which('geometry_calib');% check the path detected for source file uvmat
637path_UVMAT=fileparts(path_uvmat); %path to UVMAT
638x_1=double(Coord(:,4:5)');%image coordinates
639X_1=double(Coord(:,1:3)');% phys coordinates
640huvmat=findobj(allchild(0),'Tag','uvmat');
641hhuvmat=guidata(huvmat);
642if ~strcmp(get(hhuvmat.Scalar,'Visible'),'on')
643    msgbox_uvmat('ERROR','An image needs to be opened in uvmat for calibration')
644  return
645end
646ny=str2double(get(hhuvmat.num_Npy,'String'));
647x_1(2,:)=ny-x_1(2,:);%reverse the y image coordinates
648n_ima=1;
649GeometryCalib.CalibrationType='3D_extrinsic';
650fx=str2num(get(handles.fx,'String'));
651fy=str2num(get(handles.fy,'String'));
652Cx=str2num(get(handles.Cx,'String'));
653Cy=str2num(get(handles.Cy,'String'));
654errormsg='';
655if isempty(fx)
656    errormsg='focal length fx needs to be introduced';
657elseif isempty(fy)
658    errormsg='focal length fy needs to be introduced';
659elseif isempty(Cx)
660    errormsg='shift Cx to image centre needs to be introduced';
661elseif isempty(Cy)
662    errormsg='shift Cy to image centre needs to be introduced';
663end
664if ~isempty(errormsg)
665    GeometryCalib=[];
666    msgbox_uvmat('ERROR',errormsg)
667    return
668end
669GeometryCalib.fx_fy(1)=str2num(get(handles.fx,'String'));
670GeometryCalib.fx_fy(2)=str2num(get(handles.fy,'String'));
671GeometryCalib.Cx_Cy(1)=str2num(get(handles.Cx,'String'));
672GeometryCalib.Cx_Cy(2)=str2num(get(handles.Cy,'String'));
673GeometryCalib.kc=str2num(get(handles.kc,'String'));
674fct_path=fullfile(path_UVMAT,'toolbox_calib');
675addpath(fct_path)
676GeometryCalib.Cx_Cy(2)=ny-GeometryCalib.Cx_Cy(2);%reverse Cx_Cy(2) for calibration (inversion of px ordinate)
677[omc,Tc1,Rc1,H,x,ex,JJ] = compute_extrinsic(x_1,X_1,...
678   (GeometryCalib.fx_fy)',GeometryCalib.Cx_Cy',[GeometryCalib.kc 0 0 0 0]);
679rmpath(fct_path);
680GeometryCalib.CoordUnit=[];% default value, to be updated by the calling function
681GeometryCalib.Tx_Ty_Tz=Tc1';
682%inversion of z axis
683GeometryCalib.R=Rc1;
684GeometryCalib.R(2,1:3)=-GeometryCalib.R(2,1:3);%inversion of the y image coordinate
685GeometryCalib.Tx_Ty_Tz(2)=-GeometryCalib.Tx_Ty_Tz(2);%inversion of the y image coordinate
686GeometryCalib.Cx_Cy(2)=ny-GeometryCalib.Cx_Cy(2);%inversion of the y image coordinate
687GeometryCalib.omc=(180/pi)*omc';
688
689%------------------------------------------------------------------------
690%function GeometryCalib=calib_tsai_heikkila(Coord)
691% TEST: NOT IMPLEMENTED
692%------------------------------------------------------------------
693% path_uvmat=which('uvmat');% check the path detected for source file uvmat
694% path_UVMAT=fileparts(path_uvmat); %path to UVMAT
695% path_calib=fullfile(path_UVMAT,'toolbox_calib_heikkila');
696% addpath(path_calib)
697% npoints=size(Coord,1);
698% Coord(:,1:3)=10*Coord(:,1:3);
699% Coord=[Coord zeros(npoints,2) -ones(npoints,1)];
700% [par,pos,iter,res,er,C]=cacal('dalsa',Coord);
701% GeometryCalib.CalibrationType='tsai';
702% GeometryCalib.focal=par(2);
703
704
705%------------------------------------------------------------------------
706% --- determine the rms of calibration error
707function ErrorRms=error_calib(calib_param,Calib,Coord)
708%------------------------------------------------------------------------
709%calib_param: vector of free calibration parameters (to optimise)
710%Calib: structure of the given calibration parameters
711%Coord: list of phys coordinates (columns 1-3, and pixel coordinates (columns 4-5)
712Calib.f=25;
713Calib.dpx=0.012;
714Calib.dpy=0.012;
715Calib.sx=1;
716Calib.Cx=512;
717Calib.Cy=512;
718Calib.kappa1=calib_param(1);
719Calib.Tx=calib_param(2);
720Calib.Ty=calib_param(3);
721Calib.Tz=calib_param(4);
722alpha=calib_param(5);
723Calib.R=[cos(alpha) sin(alpha) 0;-sin(alpha) cos(alpha) 0;0 0 -1];
724
725X=Coord(:,1);
726Y=Coord(:,2);
727Z=Coord(:,3);
728x_ima=Coord(:,4);
729y_ima=Coord(:,5);
730[Xpoints,Ypoints]=px_XYZ(Calib,X,Y,Z);
731ErrorRms(1)=sqrt(mean((Xpoints-x_ima).*(Xpoints-x_ima)));
732ErrorRms(2)=sqrt(mean((Ypoints-y_ima).*(Ypoints-y_ima)));
733ErrorRms=mean(ErrorRms);
734
735
736%------------------------------------------------------------------------
737% --- Executes on button press in STORE.
738function STORE_Callback(hObject, eventdata, handles)
739%------------------------------------------------------------------------
740Coord=get(handles.ListCoord,'Data');
741%Object=read_geometry_calib(Coord_cell);
742unitlist=get(handles.CoordUnit,'String');
743unit=unitlist{get(handles.CoordUnit,'value')};
744GeometryCalib.CoordUnit=unit;
745GeometryCalib.SourceCalib.PointCoord=Coord(:,1:5);
746huvmat=findobj(allchild(0),'Name','uvmat');
747hhuvmat=guidata(huvmat);%handles of elements in the GUI uvmat
748% RootPath='';
749% RootFile='';
750if ~isempty(hhuvmat.RootPath)&& ~isempty(hhuvmat.RootFile)
751%     testhandle=1;
752    RootPath=get(hhuvmat.RootPath,'String');
753    RootFile=get(hhuvmat.RootFile,'String');
754    filebase=[fullfile(RootPath,RootFile) '~'];
755    while exist([filebase '.xml'],'file')
756        filebase=[filebase '~'];
757    end
758    outputfile=[filebase '.xml'];
759    errormsg=update_imadoc(GeometryCalib,outputfile,'GeometryCalib');
760    if ~strcmp(errormsg,'')
761        msgbox_uvmat('ERROR',errormsg);
762    end
763    listfile=get(handles.ListCoordFiles,'string');
764    if isequal(listfile,{''})
765        listfile={outputfile};
766    else
767        listfile=[listfile;{outputfile}];%update the list of coord files
768    end
769    set(handles.ListCoordFiles,'string',listfile);
770end
771ClearAll_Callback(hObject, eventdata, handles)% clear the current list and point plots
772
773% --------------------------------------------------------------------
774% --- Executes on button press in ClearAll: clear the list of calibration points
775function ClearAll_Callback(hObject, eventdata, handles)
776% --------------------------------------------------------------------
777set(handles.ListCoord,'Data',[])
778PLOT_Callback(hObject, eventdata, handles)
779update_calib_marker([]);%remove circle marker
780set(handles.APPLY,'backgroundColor',[1 0 0])% set APPLY button to red color: no calibration wanted without points
781set(handles.CheckEnableMouse,'value',1); %activate mouse to pick new points
782
783%------------------------------------------------------------------------
784% --- Executes on button press in CLEAR LIST
785function CLEAR_Callback(hObject, eventdata, handles)
786%------------------------------------------------------------------------
787set(handles.ListCoordFiles,'Value',1)
788set(handles.ListCoordFiles,'String',{''})
789
790%------------------------------------------------------------------------
791% --- Executes on selection change in CheckEnableMouse.
792function CheckEnableMouse_Callback(hObject, eventdata, handles)
793%------------------------------------------------------------------------
794choice=get(handles.CheckEnableMouse,'Value');
795if choice
796    huvmat=findobj(allchild(0),'tag','uvmat');
797    if ishandle(huvmat)
798        hhuvmat=guidata(huvmat);
799        set(hhuvmat.MenuRuler,'checked','off')%desactivate ruler
800        if get(hhuvmat.CheckEditObject,'Value')
801            set(hhuvmat.CheckEditObject,'Value',0)
802            uvmat('CheckEditObject_Callback',hhuvmat.CheckEditObject,[],hhuvmat)
803        end
804        set(hhuvmat.MenuRuler,'checked','off')%desactivate ruler
805    end
806end
807
808% --------------------------------------------------------------------
809function MenuHelp_Callback(hObject, eventdata, handles)
810web('http://servforge.legi.grenoble-inp.fr/projects/soft-uvmat/wiki/UvmatHelp#GeometryCalib')
811
812% --------------------------------------------------------------------
813function MenuSetScale_Callback(hObject, eventdata, handles)
814
815answer=msgbox_uvmat('INPUT_TXT','scale pixel/cm?','');
816%create test points
817huvmat=findobj(allchild(0),'Name','uvmat');%find the current uvmat interface handle
818hhuvmat=guidata(huvmat);
819if ~strcmp(get(hhuvmat.Scalar,'Visible'),'on')
820    msgbox_uvmat('ERROR','An image needs to be opened in uvmat for calibration')
821    return
822end
823set(handles.calib_type,'Value',1)% set calib option to 'rescale'
824npx=str2num(get(hhuvmat.num_Npx,'String'))/2;
825npy=str2num(get(hhuvmat.num_Npy,'String'))/2;
826Xima=[0.25*npx 0.75*npx 0.75*npx 0.25*npx]';
827Yima=[0.25*npy 0.25*npy 0.75*npy 0.75*npy]';
828x=Xima/str2num(answer);
829y=Yima/str2num(answer);
830Coord=[x y zeros(4,1) Xima Yima zeros(4,1)];
831set(handles.ListCoord,'Data',Coord)
832set(handles.APPLY,'BackgroundColor',[1 0 1])
833set(handles.CheckEnableMouse,'value',0); %desactivate mouse to avoid spurious points
834
835%------------------------------------------------------------------------
836function MenuCreateGrid_Callback(hObject, eventdata, handles)
837%------------------------------------------------------------------------
838CalibData=get(handles.geometry_calib,'UserData');
839Tinput=[];%default
840if isfield(CalibData,'grid')
841    Tinput=CalibData.grid;
842end
843[T,CalibData.grid]=create_grid(Tinput);%display the GUI create_grid
844set(handles.geometry_calib,'UserData',CalibData)
845
846%grid in phys space
847Coord=get(handles.ListCoord,'Data');
848Coord(1:size(T,1),1:3)=T;%update the existing list of phys coordinates from the GUI create_grid
849set(handles.ListCoord,'Data',Coord)
850set(handles.APPLY,'BackgroundColor',[1 0 1])
851set(handles.CheckEnableMouse,'value',0); %desactivate mouse to avoid spurious points
852
853% -----------------------------------------------------------------------
854% --- automatic grid dectection from local maxima of the images
855function MenuDetectGrid_Callback(hObject, eventdata, handles)
856%------------------------------------------------------------------------
857%% read the four last point coordinates in pixels
858Coord=get(handles.ListCoord,'Data');%read list of coordinates on geometry_calib
859nbpoints=size(Coord,1); %nbre of calibration points
860if nbpoints~=4
861    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')
862    return
863end
864% corners_X=(Coord(end:-1:end-3,4)); %pixel absissa of the four corners
865% corners_Y=(Coord(end:-1:end-3,5));
866corners_X=(Coord(:,4)); %pixel absissa of the four corners
867corners_Y=(Coord(:,5));
868
869%%%%%%
870%   corners_X=1000*[1.5415  1.7557 1.7539 1.5415]';
871%   corners_Y=1000*[1.1515 1.1509 1.3645  1.3639]';
872
873%reorder the last two points (the two first in the list) if needed
874angles=angle((corners_X-corners_X(1))+1i*(corners_Y-corners_Y(1)));
875if abs(angles(4)-angles(2))>abs(angles(3)-angles(2))
876      X_end=corners_X(4);
877      Y_end=corners_Y(4);
878      corners_X(4)=corners_X(3);
879      corners_Y(4)=corners_Y(3);
880      corners_X(3)=X_end;
881      corners_Y(3)=Y_end;
882end
883
884%% initiate the grid in phys coordinates
885CalibData=get(handles.geometry_calib,'UserData');%get information stored on the GUI geometry_calib
886grid_input=[];%default
887if isfield(CalibData,'grid')
888    grid_input=CalibData.grid;%retrieve the previously used grid
889end
890[T,CalibData.grid,CalibData.grid.CheckWhite]=create_grid(grid_input,'detect_grid');%display the GUI create_grid, read the set of phys coordinates T
891set(handles.geometry_calib,'UserData',CalibData)%store the phys grid parameters for later use
892X=[CalibData.grid.x_0 CalibData.grid.x_1 CalibData.grid.x_0 CalibData.grid.x_1]';%corner absissa in the phys coordinates (cm)
893Y=[CalibData.grid.y_0 CalibData.grid.y_0 CalibData.grid.y_1 CalibData.grid.y_1]';%corner ordinates in the phys coordinates (cm)
894
895%% read the current image, displayed in the GUI uvmat
896huvmat=findobj(allchild(0),'Name','uvmat');
897UvData=get(huvmat,'UserData');
898A=UvData.Field.A;%currently displayed image
899npxy=size(A);
900
901%% calculate transform matrices for plane projection: rectangle assumed to be viewed in perspective
902% reference: http://alumni.media.mit.edu/~cwren/interpolator/ by Christopher R. Wren
903B = [ X Y ones(size(X)) zeros(4,3)        -X.*corners_X -Y.*corners_X ...
904      zeros(4,3)        X Y ones(size(X)) -X.*corners_Y -Y.*corners_Y ];
905B = reshape (B', 8 , 8 )';
906D = [ corners_X , corners_Y ];
907D = reshape (D', 8 , 1 );
908l = (B' * B)\B' * D;
909Amat = reshape([l(1:6)' 0 0 1 ],3,3)';
910C = [l(7:8)' 1];
911
912%% transform grid image into 'phys' coordinates
913GeometryCalib.CalibrationType='3D_linear';
914GeometryCalib.fx_fy=[1 1];
915GeometryCalib.Tx_Ty_Tz=[Amat(1,3) Amat(2,3) 1];
916GeometryCalib.R=[Amat(1,1),Amat(1,2),0;Amat(2,1),Amat(2,2),0;C(1),C(2),0];
917GeometryCalib.CoordUnit='cm';
918path_uvmat=which('uvmat');% check the path detected for source file uvmat
919path_UVMAT=fileparts(path_uvmat); %path to UVMAT
920addpath(fullfile(path_UVMAT,'transform_field'))
921Data.ListVarName={'Coord_y','Coord_x','A'};
922Data.VarDimName={'Coord_y','Coord_x',{'Coord_y','Coord_x'}};
923if ndims(A)==3
924    A=mean(A,3);
925end
926Data.A=A-min(min(A));
927Data.Coord_y=[npxy(1)-0.5 0.5];
928Data.Coord_x=[0.5 npxy(2)];
929Data.CoordUnit='pixel';
930Calib.GeometryCalib=GeometryCalib;
931DataOut=phys(Data,Calib);
932rmpath(fullfile(path_UVMAT,'transform_field'))
933Amod=DataOut.A;% current image expressed in 'phys' coord
934Rangx=DataOut.Coord_x;% x coordinates of first and last pixel centres in phys
935Rangy=DataOut.Coord_y;% y coordinates of first and last pixel centres in phys
936if CalibData.grid.CheckWhite
937    Amod=double(Amod);%case of white grid markers: will look for image maxima
938else
939    Amod=-double(Amod);%case of black grid markers: will look for image minima
940end
941
942%% detection of local image extrema in each direction
943Dx=(Rangx(2)-Rangx(1))/(npxy(2)-1); %x mesh in real space
944Dy=(Rangy(2)-Rangy(1))/(npxy(1)-1); %y mesh in real space
945ind_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
946ind_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
947nbpoints=size(T,1);
948TIndex=ones(size(T));% image indices corresponding to point coordinates
949%look for image maxima around each expected grid point
950for ipoint=1:nbpoints
951    i0=1+round((T(ipoint,1)-Rangx(1))/Dx);% x index of the expected point in the phys image Amod
952    j0=1+round((T(ipoint,2)-Rangy(1))/Dy);% y index of the expected point in the phys image Amod
953    j0min=max(j0-ind_range_y,1);% min y index selected for the subimage (cut at the edge to avoid index <1)
954    j0max=min(j0+ind_range_y,size(Amod,1));% max y index selected for the subimage (cut at the edge to avoid index > size)
955    i0min=max(i0-ind_range_x,1);% min x index selected for the subimage (cut at the edge to avoid index <1)
956    i0max=min(i0+ind_range_x,size(Amod,2));% max x index selected for the subimage (cut at the edge to avoid index > size)
957    Asub=Amod(j0min:j0max,i0min:i0max); %subimage used to find brigthness extremum
958    x_profile=sum(Asub,1);%profile of subimage summed over y
959    y_profile=sum(Asub,2);%profile of subimage summed over x
960
961    [tild,ind_x_max]=max(x_profile);% index of max for the x profile
962    [tild,ind_y_max]=max(y_profile);% index of max for the y profile
963    %sub-pixel improvement using moments
964    x_shift=0;
965    y_shift=0;
966    if ind_x_max+2<=numel(x_profile) && ind_x_max-2>=1
967        Atop=x_profile(ind_x_max-2:ind_x_max+2);% extract x profile around the max
968        x_shift=sum(Atop.*[-2 -1 0 1 2])/sum(Atop);
969    end
970    if ind_y_max+2<=numel(y_profile) && ind_y_max-2>=1
971        Atop=y_profile(ind_y_max-2:ind_y_max+2);% extract y profile around the max
972        y_shift=sum(Atop.*[-2 -1 0 1 2]')/sum(Atop);
973    end
974        %%%%
975%     if ipoint==9
976%                 figure(11)
977%   imagesc(Asub)
978%     figure(12)
979%     plot(x_profile,'r')
980%     hold on
981%     plot(y_profile,'b')
982%     grid on
983%     end
984    %%%%
985    TIndex(ipoint,1)=(i0min+ind_x_max-1+x_shift);% x position of the maximum (in index of Amod)
986    TIndex(ipoint,2)=(j0min+ind_y_max-1+y_shift);% y position of the maximum (in index of Amod)
987end
988Tmod(:,1)=(TIndex(:,1)-1)*Dx+Rangx(1);
989Tmod(:,2)=(TIndex(:,2)-1)*Dy+Rangy(1);
990%Tmod=T(:,(1:2))+Delta;% 'phys' coordinates of the detected points
991[Xpx,Ypx]=px_XYZ(GeometryCalib,Tmod(:,1),Tmod(:,2));% image coordinates of the detected points
992Coord=[T Xpx Ypx zeros(size(T,1),1)];
993set(handles.ListCoord,'Data',Coord)
994PLOT_Callback(hObject, eventdata, handles)
995set(handles.APPLY,'BackgroundColor',[1 0 1])
996set(handles.CheckEnableMouse,'value',0); %desactivate mouse to avoid spurious points
997
998
999%-----------------------------------------------------------------------
1000function MenuTranslatePoints_Callback(hObject, eventdata, handles)
1001%-----------------------------------------------------------------------
1002%hcalib=get(handles.calib_type,'parent');%handles of the GUI geometry_calib
1003CalibData=get(handles.geometry_calib,'UserData');
1004Tinput=[];%default
1005if isfield(CalibData,'translate')
1006    Tinput=CalibData.translate;
1007end
1008T=translate_points(Tinput);%display translate_points GUI and get shift parameters
1009CalibData.translate=T;
1010set(handles.geometry_calib,'UserData',CalibData)
1011%translation
1012Coord=get(handles.ListCoord,'Data');
1013Coord(:,1)=T(1)+Coord(:,1);
1014Coord(:,2)=T(2)+Coord(:,2);
1015Coord(:,3)=T(3)+Coord(:,3);
1016set(handles.ListCoord,'Data',Coord);
1017set(handles.APPLY,'BackgroundColor',[1 0 1])
1018
1019% --------------------------------------------------------------------
1020function MenuRotatePoints_Callback(hObject, eventdata, handles)
1021%hcalib=get(handles.calib_type,'parent');%handles of the GUI geometry_calib
1022CalibData=get(handles.geometry_calib,'UserData');
1023Tinput=[];%default
1024if isfield(CalibData,'rotate')
1025    Tinput=CalibData.rotate;
1026end
1027T=rotate_points(Tinput);%display rotate_points GUI to introduce rotation parameters
1028CalibData.rotate=T;
1029set(handles.geometry_calib,'UserData',CalibData)
1030%-----------------------------------------------------
1031%rotation
1032Phi=T(1);
1033O_x=0;%default
1034O_y=0;%default
1035if numel(T)>=2
1036    O_x=T(2);%default
1037end
1038if numel(T)>=3
1039    O_y=T(3);%default
1040end
1041Coord=get(handles.ListCoord,'Data');
1042r1=cos(pi*Phi/180);
1043r2=-sin(pi*Phi/180);
1044r3=sin(pi*Phi/180);
1045r4=cos(pi*Phi/180);
1046x=Coord(:,1)-O_x;
1047y=Coord(:,2)-O_y;
1048Coord(:,1)=r1*x+r2*y;
1049Coord(:,2)=r3*x+r4*y;
1050set(handles.ListCoord,'Data',Coord)
1051set(handles.APPLY,'BackgroundColor',[1 0 1])
1052
1053% --------------------------------------------------------------------
1054function MenuImportPoints_Callback(hObject, eventdata, handles)
1055fileinput=browse_xml(hObject, eventdata, handles);
1056if isempty(fileinput)
1057    return
1058end
1059[s,errormsg]=imadoc2struct(fileinput,'GeometryCalib');
1060if ~isfield(s,'GeometryCalib')
1061    msgbox_uvmat('ERROR','invalid input file: no geometry_calib data')
1062    return
1063end
1064GeometryCalib=s.GeometryCalib;
1065if ~(isfield(GeometryCalib,'SourceCalib')&&isfield(GeometryCalib.SourceCalib,'PointCoord'))
1066        msgbox_uvmat('ERROR','invalid input file: no calibration points')
1067    return
1068end
1069Coord=GeometryCalib.SourceCalib.PointCoord;
1070Coord=[Coord zeros(size(Coord,1),1)];
1071set(handles.ListCoord,'Data',Coord)
1072PLOT_Callback(handles.geometry_calib, [], handles)
1073set(handles.APPLY,'BackgroundColor',[1 0 1])
1074set(handles.CheckEnableMouse,'value',0); %desactivate mouse to avoid modifications by default
1075
1076% -----------------------------------------------------------------------
1077function MenuImportIntrinsic_Callback(hObject, eventdata, handles)
1078%------------------------------------------------------------------------
1079fileinput=browse_xml(hObject, eventdata, handles);
1080if isempty(fileinput)
1081    return
1082end
1083[s,errormsg]=imadoc2struct(fileinput,'GeometryCalib');
1084GeometryCalib=s.GeometryCalib;
1085display_intrinsic(GeometryCalib,handles)
1086
1087% -----------------------------------------------------------------------
1088function MenuImportAll_Callback(hObject, eventdata, handles)
1089%------------------------------------------------------------------------
1090fileinput=browse_xml(hObject, eventdata, handles);
1091if ~isempty(fileinput)
1092    loadfile(handles,fileinput)
1093end
1094set(handles.CheckEnableMouse,'value',0); %desactivate mouse to avoid modifications by default
1095
1096% -----------------------------------------------------------------------
1097% --- Executes on menubar option Import/Grid file: introduce previous grid files
1098function MenuGridFile_Callback(hObject, eventdata, handles)
1099% -----------------------------------------------------------------------
1100inputfile=browse_xml(hObject, eventdata, handles);
1101listfile=get(handles.ListCoordFiles,'String');
1102if isequal(listfile,{''})
1103    listfile={inputfile};
1104else
1105    listfile=[listfile;{inputfile}];%update the list of coord files
1106end
1107set(handles.ListCoordFiles,'String',listfile);
1108
1109
1110%------------------------------------------------------------------------
1111function fileinput=browse_xml(hObject, eventdata, handles)
1112%------------------------------------------------------------------------
1113fileinput=[];%default
1114oldfile=''; %default
1115UserData=get(handles.geometry_calib,'UserData');
1116if isfield(UserData,'XmlInputFile')
1117    oldfile=UserData.XmlInputFile;
1118end
1119[FileName, PathName, filterindex] = uigetfile( ...
1120       {'*.xml;*.mat', ' (*.xml,*.mat)';
1121       '*.xml',  '.xml files '; ...
1122        '*.mat',  '.mat matlab files '}, ...
1123        'Pick a file',oldfile);
1124fileinput=[PathName FileName];%complete file name
1125testblank=findstr(fileinput,' ');%look for blanks
1126if ~isempty(testblank)
1127    msgbox_uvmat('ERROR','forbidden input file name or path: no blank character allowed')
1128    return
1129end
1130sizf=size(fileinput);
1131if (~ischar(fileinput)||~isequal(sizf(1),1)),return;end
1132UserData.XmlInputFile=fileinput;
1133set(handles.geometry_calib,'UserData',UserData)%record current file foer further use of browser
1134
1135% -----------------------------------------------------------------------
1136function Heading=loadfile(handles,fileinput)
1137%------------------------------------------------------------------------
1138Heading=[];%default
1139[s,errormsg]=imadoc2struct(fileinput,'Heading','GeometryCalib');
1140if ~isempty(errormsg)
1141    msgbox_uvmat('ERROR',errormsg)
1142    return
1143end
1144if ~isempty(s.Heading)
1145    Heading=s.Heading;
1146end
1147
1148GeometryCalib=s.GeometryCalib;
1149fx=1;fy=1;Cx=0;Cy=0;kc=0; %default
1150CoordCell={};
1151Tabchar={};%default
1152val_cal=1;%default
1153if ~isempty(GeometryCalib)
1154    % choose the calibration option
1155    if isfield(GeometryCalib,'CalibrationType')
1156        calib_list=get(handles.calib_type,'String');
1157        for ilist=1:numel(calib_list)
1158            if strcmp(calib_list{ilist},GeometryCalib.CalibrationType)
1159                val_cal=ilist;
1160                break
1161            end
1162        end
1163    end
1164    display_intrinsic(GeometryCalib,handles)%intrinsic param
1165    %extrinsic param
1166    if isfield(GeometryCalib,'Tx_Ty_Tz')
1167        Tx_Ty_Tz=GeometryCalib.Tx_Ty_Tz;
1168        set(handles.Tx,'String',num2str(GeometryCalib.Tx_Ty_Tz(1),4))
1169        set(handles.Ty,'String',num2str(GeometryCalib.Tx_Ty_Tz(2),4))
1170        set(handles.Tz,'String',num2str(GeometryCalib.Tx_Ty_Tz(3),4))
1171    end
1172    if isfield(GeometryCalib,'omc')
1173        set(handles.Phi,'String',num2str(GeometryCalib.omc(1),4))
1174        set(handles.Theta,'String',num2str(GeometryCalib.omc(2),4))
1175        set(handles.Psi,'String',num2str(GeometryCalib.omc(3),4))
1176    end
1177    if isfield(GeometryCalib,'SourceCalib')&& isfield(GeometryCalib.SourceCalib,'PointCoord')
1178        calib=GeometryCalib.SourceCalib.PointCoord;
1179        Coord=[calib zeros(size(calib,1),1)];
1180        set(handles.ListCoord,'Data',Coord)
1181    end
1182    PLOT_Callback(handles.geometry_calib, [], handles)
1183    set(handles.APPLY,'BackgroundColor',[1 0 1])
1184end
1185set(handles.calib_type,'Value',val_cal)
1186
1187if isempty(CoordCell)% allow mouse action by default in the absence of input points
1188    set(handles.CheckEnableMouse,'Value',1)
1189    set(handles.CheckEnableMouse,'BackgroundColor',[1 1 0])
1190else % does not allow mouse action by default in the presence of input points
1191    set(handles.CheckEnableMouse,'Value',0)
1192    set(handles.CheckEnableMouse,'BackgroundColor',[0.7 0.7 0.7])
1193end
1194
1195%------------------------------------------------------------------------
1196%---display calibration intrinsic parameters
1197function display_intrinsic(GeometryCalib,handles)
1198%------------------------------------------------------------------------
1199fx=[];
1200fy=[];
1201if isfield(GeometryCalib,'fx_fy')
1202    fx=GeometryCalib.fx_fy(1);
1203    fy=GeometryCalib.fx_fy(2);
1204end
1205Cx_Cy=[0 0];%default
1206if isfield(GeometryCalib,'Cx_Cy')
1207    Cx_Cy=GeometryCalib.Cx_Cy;
1208end
1209kc=0;
1210if isfield(GeometryCalib,'kc')
1211    kc=GeometryCalib.kc; %* GeometryCalib.focal*GeometryCalib.focal;
1212end
1213set(handles.fx,'String',num2str(fx,5))
1214set(handles.fy,'String',num2str(fy,5))
1215set(handles.Cx,'String',num2str(Cx_Cy(1),'%1.1f'))
1216set(handles.Cy,'String',num2str(Cx_Cy(2),'%1.1f'))
1217set(handles.kc,'String',num2str(kc,'%1.4f'))
1218
1219
1220% --- Executes when user attempts to close geometry_calib.
1221function geometry_calib_CloseRequestFcn(hObject, eventdata, handles)
1222
1223delete(hObject); % closes the figure
1224
1225%------------------------------------------------------------------------
1226% --- Executes on button press in PLOT.
1227%------------------------------------------------------------------------
1228function PLOT_Callback(hObject, eventdata, handles)
1229huvmat=findobj(allchild(0),'Name','uvmat');%find the current uvmat interface handle
1230hhuvmat=guidata(huvmat); %handles of GUI elements in uvmat
1231h_menu_coord=findobj(huvmat,'Tag','TransformName');
1232menu=get(h_menu_coord,'String');
1233choice=get(h_menu_coord,'Value');
1234option='';
1235if iscell(menu)
1236    option=menu{choice};
1237end
1238Coord=get(handles.ListCoord,'Data');
1239if ~isempty(Coord)
1240    if isequal(option,'phys')
1241        Coord_plot=Coord(:,1:3);
1242    elseif isempty(option);%optionoption,'px')||isequal(option,'')
1243        Coord_plot=Coord(:,4:5);
1244    else
1245        msgbox_uvmat('ERROR','the choice in menu_coord of uvmat must be blank or phys ')
1246    end
1247end
1248
1249set(0,'CurrentFigure',huvmat)
1250set(huvmat,'CurrentAxes',hhuvmat.PlotAxes)
1251hh=findobj('Tag','calib_points');
1252if  ~isempty(Coord) && isempty(hh)
1253    hh=line(Coord_plot(:,1),Coord_plot(:,2),'Color','m','Tag','calib_points','LineStyle','.','Marker','+','MarkerSize',10);
1254elseif isempty(Coord)%empty list of points, suppress the plot
1255    delete(hh)
1256else
1257    set(hh,'XData',Coord_plot(:,1))
1258    set(hh,'YData',Coord_plot(:,2))
1259end
1260pause(.1)
1261figure(handles.geometry_calib)
1262
1263%------------------------------------------------------------------------
1264% --- Executes on button press in Copy: display Coord on the Matlab work space
1265%------------------------------------------------------------------------
1266function Copy_Callback(hObject, eventdata, handles)
1267global Coord
1268evalin('base','global Coord')%make CurData global in the workspace
1269Coord=get(handles.ListCoord,'Data');
1270display('coordinates of calibration points (phys,px,marker) :')
1271evalin('base','Coord') %display CurData in the workspace
1272commandwindow; %brings the Matlab command window to the front
1273
1274%------------------------------------------------------------------------
1275% --- Executes when selected cell(s) is changed in ListCoord.
1276%------------------------------------------------------------------------
1277function ListCoord_CellSelectionCallback(hObject, eventdata, handles)
1278if ~isempty(eventdata.Indices)
1279    iline=eventdata.Indices(1);% selected line number
1280    set(handles.CoordLine,'String',num2str(iline))
1281     Data=get(handles.ListCoord,'Data');
1282     update_calib_marker(Data(iline,:))
1283end
1284
1285%------------------------------------------------------------------------
1286% --- Executes when entered data in editable cell(s) in ListCoord.
1287%------------------------------------------------------------------------
1288function ListCoord_CellEditCallback(hObject, eventdata, handles)
1289
1290Input=str2num(eventdata.EditData);%pasted input
1291Coord=get(handles.ListCoord,'Data');
1292iline=eventdata.Indices(1);% selected line number
1293if size(Coord,1)<iline+numel(Input)
1294    Coord=[Coord ; zeros(iline+numel(Input)-size(Coord,1),6)];% append zeros to fit the new column
1295end
1296Coord(iline:iline+numel(Input)-1,eventdata.Indices(2))=Input';
1297set(handles.ListCoord,'Data',Coord)
1298PLOT_Callback(hObject, eventdata, handles)
1299
1300%------------------------------------------------------------------------
1301% --- 'key_press_fcn:' function activated when a key is pressed on the keyboard
1302%------------------------------------------------------------------------
1303function ListCoord_KeyPressFcn(hObject, eventdata, handles)
1304iline=str2num(get(handles.CoordLine,'String'));
1305xx=double(get(handles.geometry_calib,'CurrentCharacter'));%get the keyboard character
1306if ismember(xx,[28 29 30 31])% directional arrow
1307    Coord=get(handles.ListCoord,'Data');
1308    switch xx
1309        case 30 % arrow upward
1310            iline=iline-1;
1311        case 31% arrow downward
1312            iline=iline+1;
1313    end
1314    if iline>=1 && iline<=size(Coord,1)
1315        set(handles.CoordLine,'String',num2str(iline))
1316        update_calib_marker(Coord(iline,1:5))% show the point corresponding to the selected line
1317    end
1318else
1319    set(handles.APPLY,'BackgroundColor',[1 0 1])% paint APPLY in magenta to indicate that the table content has be modified
1320end
1321
1322
1323%------------------------------------------------------------------------
1324% --- update the plot of calibration points
1325%------------------------------------------------------------------------
1326% draw a circle around the point defined by the input coordinates Coord as given by line in the table Listcoord
1327function update_calib_marker(Coord)
1328
1329%% read config on uvmat
1330huvmat=findobj(allchild(0),'Name','uvmat');%find the current uvmat interface handle
1331hhuvmat=guidata(huvmat);
1332hhh=findobj(hhuvmat.PlotAxes,'Tag','calib_marker');
1333if numel(Coord)<5
1334    if ~isempty(hhh)
1335        delete(hhh)%delete the circle marker in case of no valid input
1336    end
1337    return
1338end
1339menu=get(hhuvmat.TransformName,'String');
1340choice=get(hhuvmat.TransformName,'Value');
1341option='';
1342if iscell(menu)
1343    option=menu{choice};
1344end
1345
1346%% read appropriate coordinates (px or phys) in the table ListCoord
1347if isequal(option,'phys') % use phys coord
1348    XCoord=Coord(1);
1349    YCoord=Coord(2);
1350elseif isempty(option)% use coord in pixels
1351    XCoord=Coord(4);
1352    YCoord=Coord(5);
1353else
1354    msgbox_uvmat('ERROR','the choice in menu_coord of uvmat must be blank or phys ')
1355    return
1356end
1357
1358%% adjust the plot limits if needed
1359xlim=get(hhuvmat.PlotAxes,'XLim');
1360ylim=get(hhuvmat.PlotAxes,'YLim');
1361ind_range=max(abs(xlim(2)-xlim(1)),abs(ylim(end)-ylim(1)))/25;%defines the size of the circle marker
1362check_xlim=0;
1363if XCoord>xlim(2)
1364    xlim=xlim+XCoord-xlim(2)+ind_range;% translate plot limit
1365    check_xlim=1;
1366elseif XCoord<xlim(1)
1367    xlim=xlim-XCoord+xlim(1)-ind_range;% translate plot limit
1368    check_xlim=1;
1369end
1370if check_xlim
1371    set(hhuvmat.PlotAxes,'XLim',xlim);
1372    set(hhuvmat.num_MaxX,'String',num2str(xlim(2)));
1373    set(hhuvmat.num_MinX,'String',num2str(xlim(1)));
1374end
1375check_ylim=0;
1376if YCoord>ylim(2)
1377    ylim=ylim+YCoord-ylim(2)+ind_range;% translate plot limit
1378    check_ylim=1;
1379elseif YCoord<ylim(1)
1380    ylim=ylim-YCoord+ylim(1)-ind_range;% translate plot limit
1381    check_ylim=1;
1382end
1383if check_ylim
1384    set(hhuvmat.PlotAxes,'YLim',ylim);
1385    set(hhuvmat.num_MaxY,'String',num2str(ylim(2)));
1386    set(hhuvmat.num_MinY,'String',num2str(ylim(1)));
1387end
1388
1389%% plot a circle around the selected point
1390if isempty(hhh)
1391    set(0,'CurrentFig',huvmat)
1392    set(huvmat,'CurrentAxes',hhuvmat.PlotAxes)
1393    rectangle('Curvature',[1 1],...
1394        'Position',[XCoord-ind_range/2 YCoord-ind_range/2 ind_range ind_range],'EdgeColor','m',...
1395        'LineStyle','-','Tag','calib_marker');
1396else
1397    set(hhh,'Position',[XCoord-ind_range/2 YCoord-ind_range/2 ind_range ind_range])
1398end
1399
1400%------------------------------------------------------------------------
1401% --- Executes on button press in ClearPoint: remove the selected line in the table Coord
1402%------------------------------------------------------------------------
1403function ClearPoint_Callback(hObject, eventdata, handles)
1404
1405Coord=get(handles.ListCoord,'Data');
1406iline=str2num(get(handles.CoordLine,'String'));
1407if isempty(iline)
1408    msgbox_uvmat('WARNING','no line suppressed, select a line in the table')
1409else
1410    answer=msgbox_uvmat('INPUT_Y-N',['suppress line ' num2str(iline) '?']);
1411    if isequal(answer,'Yes')
1412        Coord(iline,:)=[];
1413        set(handles.APPLY,'BackgroundColor',[1 0 1])
1414        set(handles.ListCoord,'Data',Coord);
1415        set(handles.CoordLine,'String','')
1416        PLOT_Callback(hObject,eventdata,handles)
1417        update_calib_marker([]);%remove circle marker
1418    end
1419end
Note: See TracBrowser for help on using the repository browser.