source: trunk/src/geometry_calib.m @ 1006

Last change on this file since 1006 was 1006, checked in by campagne8a, 7 years ago

Bug corrected for geometry_calibration

File size: 64.3 KB
Line 
1%'geometry_calib': associated to the GUI geometry_calib to perform geometric calibration from a set of reference points
2%------------------------------------------------------------------------
3% function hgeometry_calib = geometry_calib(inputfile,pos)
4%
5%OUTPUT:
6% hgeometry_calib=current handles of the GUI geometry_calib.fig
7%
8%INPUT:
9% inputfile: (optional) name of an xml file containing coordinates of reference points
10% pos: (optional) 4 element vector setting the 'Position' of the GUI
11
12%=======================================================================
13% Copyright 2008-2017, LEGI UMR 5519 / CNRS UGA 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 16-Apr-2015 17:29:02
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)
170set(handles.CheckEnableMouse,'Value',0)% desactivate mouse (to avoid spurious creation of new points)
171
172%------------------------------------------------------------------------
173%% look for the GUI uvmat and check for an image as input
174set(handles.APPLY,'BackgroundColor',[1 1 0])% paint APPLY button in yellow to show activation
175huvmat=findobj(allchild(0),'Name','uvmat');% look for the GUI uvmat
176hhuvmat=guidata(huvmat);%handles of elements in the GUI uvmat
177if ~strcmp(get(hhuvmat.Scalar,'Visible'),'on')
178    msgbox_uvmat('ERROR','An image needs to be opened in uvmat for calibration')
179  return
180end
181
182RootPath='';
183if ~isempty(hhuvmat.RootPath)&& ~isempty(hhuvmat.RootFile)
184    RootPath=get(hhuvmat.RootPath,'String');% path to the currently displayed image
185    SubDirBase=regexprep(get(hhuvmat.SubDir,'String'),'\..+$','');
186    outputfile=[fullfile(RootPath,SubDirBase) '.xml'];%xml file associated with the currently displayed image
187else
188    question={'save the calibration data and point coordinates in'};
189    def={fullfile(RootPath,'ObjectCalib.xml')};
190    options.Resize='on';
191    answer=inputdlg(question,'',1,def,options);
192    outputfile=answer{1};
193end
194
195%% read coordinates of the calibration poinnts: Coord(:,1-3) in phys, Coord(:,4-5) image
196Coord=get(handles.ListCoord,'Data');
197
198 
199%% read the type of calibration
200calib_cell=get(handles.calib_type,'String');
201val=get(handles.calib_type,'Value');
202CalibFcn=['calib_' calib_cell{val}];
203
204%% read the intrinsic parameters
205Intrinsic.Npx=str2num(get(hhuvmat.num_Npx,'String'));
206Intrinsic.Npy=str2num(get(hhuvmat.num_Npy,'String'));
207Intrinsic.coord_files=get(handles.ListCoordFiles,'String');
208Intrinsic.f1=str2num(get(handles.fx,'String'));
209Intrinsic.f2=str2num(get(handles.fy,'String'));
210Intrinsic.k=str2num(get(handles.kc,'String'));
211Intrinsic.Cx=str2num(get(handles.Cx,'String'));
212Intrinsic.Cy=str2num(get(handles.Cy,'String'));
213if isempty(Intrinsic.k)
214    Intrinsic.k=0;
215end
216if isempty(Intrinsic.Cx)||isempty(Intrinsic.Cy)
217    Intrinsic.Cx=Intrinsic.Npx/2;
218    Intrinsic.Cy=Intrinsic.Npy/2;
219end 
220
221%% Apply calibration
222[GeometryCalib,index,Z_plane]=calibrate(Coord,CalibFcn,Intrinsic);% apply calibration
223
224%% record the coordinate unit
225unitlist=get(handles.CoordUnit,'String');
226unit=unitlist{get(handles.CoordUnit,'value')};
227GeometryCalib.CoordUnit=unit;
228
229%% record the coordinates of the calibration points
230GeometryCalib.SourceCalib.PointCoord=Coord;
231
232%% display calibration results on the GUI geometry_calib
233display_intrinsic(GeometryCalib,handles)%display calibration intrinsic parameters
234display_extrinsic(GeometryCalib,handles)%display calibration extrinsic parameters
235%     (rotation and translation of camera with  respect to the phys coordinates)
236
237%% store the calibration data, by default in the xml file of the currently displayed image
238answer=msgbox_uvmat('INPUT_Y-N',{'store calibration data';...
239    ['Error rms (along x,y)=' num2str(GeometryCalib.ErrorRms) ' pixels'];...
240    ['Error max (along x,y)=' num2str(GeometryCalib.ErrorMax) ' pixels']});
241if strcmp(answer,'Yes') %store the calibration data
242    if strcmp(calib_cell{val}(1:2),'3D')%set the plane position for 3D (projection) calibration
243        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'})
244        GeometryCalib.SliceCoord=Z_plane'*[0 0 1];
245    end   
246else
247    GeometryCalib=[];
248    index=1;
249end
250
251if isempty(GeometryCalib) % if calibration cancelled
252    set(handles.APPLY,'BackgroundColor',[1 0 1])
253else   % if calibration confirmed
254   
255    %% copy the xml file from the old location if appropriate, then update with the calibration parameters
256    if ~exist(outputfile,'file') && ~isempty(SubDirBase)
257        oldxml=[fullfile(RootPath,SubDirBase,get(hhuvmat.RootFile,'String')) '.xml'];
258        if exist(oldxml,'file')
259            [success,message]=copyfile(oldxml,outputfile);%copy the old xml file to a new one with the new convention
260        end
261    end
262    errormsg=update_imadoc(GeometryCalib,outputfile,'GeometryCalib');% introduce the calibration data in the xml file
263    if ~strcmp(errormsg,'')
264        msgbox_uvmat('ERROR',errormsg);
265    end
266   
267    %% display image with new calibration in the currently opened uvmat interface
268    FieldList=get(hhuvmat.FieldName,'String');
269    val=get(hhuvmat.FieldName,'Value');
270    if strcmp(FieldList{val},'image')
271        set(hhuvmat.CheckFixLimits,'Value',0)% put FixedLimits option to 'off' to plot the whole image
272        UserData=get(handles.geometry_calib,'UserData');
273        UserData.XmlInputFile=outputfile;%save the current xml file name
274        set(handles.geometry_calib,'UserData',UserData)
275        uvmat('InputFileREFRESH_Callback',hObject,eventdata,hhuvmat); %file input with xml reading  in uvmat, show the image in phys coordinates
276        PLOT_Callback(hObject, eventdata, handles)
277        set(handles.CoordLine,'string',num2str(index))
278        Coord=get(handles.ListCoord,'Data');
279        update_calib_marker(Coord(index,:)); %indicate the point with max deviations from phys coord to calibration
280        figure(handles.geometry_calib)% put the GUI geometry_calib in front
281        set(handles.APPLY,'BackgroundColor',[1 0 0]) % set APPLY button to red color
282    else
283        msgbox_uvmat('WARNING','open the image to see the effect of the new calibration')
284    end
285end
286
287%------------------------------------------------------------------------
288% --- Executes on button press in REPLICATE
289function REPLICATE_Callback(hObject, eventdata, handles)
290%------------------------------------------------------------------------
291set(handles.CheckEnableMouse,'Value',0)% desactivate mouse (to avoid spurious creation of new points)
292
293%% look for the GUI uvmat and check for an image as input
294huvmat=findobj(allchild(0),'Name','uvmat');
295hhuvmat=guidata(huvmat);%handles of elements in the GUI uvmat
296
297%% read coordinates of the calibration poinnts: Coord(:,1-3) in phys, Coord(:,4-5) image
298Coord=get(handles.ListCoord,'Data');
299 
300%% read the type of calibration
301calib_cell=get(handles.calib_type,'String');
302val=get(handles.calib_type,'Value');
303CalibFcn=['calib_' calib_cell{val}];
304
305%% read the intrinsic parameters
306Intrinsic.Npx=str2num(get(hhuvmat.num_Npx,'String'));
307Intrinsic.Npy=str2num(get(hhuvmat.num_Npy,'String'));
308Intrinsic.coord_files=get(handles.ListCoordFiles,'String');
309Intrinsic.f1=str2num(get(handles.fx,'String'));
310Intrinsic.f2=str2num(get(handles.fy,'String'));
311Intrinsic.k=str2num(get(handles.kc,'String'));
312Intrinsic.Cx=str2num(get(handles.Cx,'String'));
313Intrinsic.Cy=str2num(get(handles.Cy,'String'));
314if isempty(Intrinsic.k)
315    Intrinsic.k=0;
316end
317if isempty(Intrinsic.Cx)||isempty(Intrinsic.Cy)
318    Intrinsic.Cx=Intrinsic.Npx/2;
319    Intrinsic.Cy=Intrinsic.Npy/2;
320end
321
322%% apply to cropped images if requested
323answer=msgbox_uvmat('INPUT_Y-N','apply to cropped images?');
324if strcmp(answer,'Yes')
325    prompt = {'npy_lower'};
326    dlg_title = 'remove image the npy_lower image lines (removal of the upper linedoes not change calibration)';
327    num_lines= 1;
328    def     = {'0'};
329    answer = inputdlg(prompt,dlg_title,num_lines,def);
330    npy_crop=str2num(answer{1});
331    Intrinsic.Npy=Intrinsic.Npy-npy_crop; %size of the filtering window
332    Coord(:,5)=Coord(:,5)-npy_crop;% shift the image ordinates of the calibration points by removing the lower band
333end
334
335%% Apply calibration
336[GeometryCalib,index,Z_plane]=calibrate(Coord,CalibFcn,Intrinsic);% apply calibration
337
338
339%% record the coordinate unit
340unitlist=get(handles.CoordUnit,'String');
341unit=unitlist{get(handles.CoordUnit,'value')};
342GeometryCalib.CoordUnit=unit;
343
344%% record the coordinates of the calibration points
345GeometryCalib.SourceCalib.PointCoord=Coord;
346
347%% display calibration results on the GUI geometry_calib
348display_intrinsic(GeometryCalib,handles)%display calibration intrinsic parameters
349display_extrinsic(GeometryCalib,handles)%display calibration extrinsic parameters
350%     (rotation and translation of camera with  respect to the phys coordinates)
351
352%% store the calibration data, by default in the xml file of the currently displayed image
353answer=msgbox_uvmat('INPUT_Y-N',{'store calibration data';...
354    ['Error rms (along x,y)=' num2str(GeometryCalib.ErrorRms) ' pixels'];...
355    ['Error max (along x,y)=' num2str(GeometryCalib.ErrorMax) ' pixels']});
356if strcmp(answer,'Yes') %store the calibration data
357    if strcmp(calib_cell{val}(1:2),'3D')%set the plane position for 3D (projection) calibration
358        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'})
359        GeometryCalib.SliceCoord=Z_plane'*[0 0 1];
360    end   
361else
362    GeometryCalib=[];
363    index=1;
364end
365
366%% open the GUI browse_data
367CalibData=get(handles.geometry_calib,'UserData');%read the calibration image source on the interface userdata
368if isfield(CalibData,'XmlInputFile')
369    InputDir=fileparts(fileparts(CalibData.XmlInputFile));
370end
371DataSeries=uigetfile_uvmat('open a folder of images to calibrate',InputDir,'uigetdir');
372%SubProject=uigetfile_uvmat('open folder of subproject to calibrate',InputDir,'uigetdir');
373OutPut=browse_data(DataSeries);
374nbcalib=0;
375for ilist=1:numel(OutPut.Experiment)
376    SubDirBase=regexprep(OutPut.DataSeries{1},'\..+$','');
377    XmlName=fullfile(OutPut.Campaign,OutPut.Experiment{ilist},[SubDirBase '.xml']);
378    % copy the xml file from the old location if appropriate, then update with the calibration parameters
379    if ~exist(XmlName,'file') && ~isempty(SubDirBase)
380        oldxml=fullfile(OutPut.Campaign,OutPut.Experiment{ilist},SubDirBase,[get(hhuvmat.RootFile,'String') '.xml']);
381        if exist(oldxml,'file')
382            [success,message]=copyfile(oldxml,XmlName);%copy the old xml file to a new one with the new convention
383        end
384    end
385    errormsg=update_imadoc(GeometryCalib,XmlName,'GeometryCalib');% introduce the calibration data in the xml file
386    if ~strcmp(errormsg,'')
387        msgbox_uvmat('ERROR',errormsg);
388    else
389        display([XmlName ' updated with calibration parameters'])
390        nbcalib=nbcalib+1;
391    end
392end
393msgbox_uvmat('CONFIMATION',[SubDirBase ' calibrated for ' num2str(nbcalib) ' experiments']);
394
395%------------------------------------------------------------------------
396% --- activate calibration and store parameters in ouputfile .
397function [GeometryCalib,index,Z_plane]=calibrate(Coord,CalibFcn,Intrinsic)
398%------------------------------------------------------------------------
399
400index=[];
401
402% apply the calibration, whose type is selected in  handles.calib_type
403if ~isempty(Coord)
404    GeometryCalib=feval(CalibFcn,Coord,Intrinsic);
405else
406    GeometryCalib=[];
407    msgbox_uvmat('ERROR','No calibration points, abort')
408end
409if isempty(GeometryCalib)
410    return
411end
412Z_plane=[];
413if ~isempty(Coord)
414    %check error
415    X=Coord(:,1);
416    Y=Coord(:,2);
417    Z=Coord(:,3);
418    x_ima=Coord(:,4);
419    y_ima=Coord(:,5);
420    [Xpoints,Ypoints]=px_XYZ(GeometryCalib,X,Y,Z);
421    GeometryCalib.ErrorRms(1)=sqrt(mean((Xpoints-x_ima).*(Xpoints-x_ima)));
422    [GeometryCalib.ErrorMax(1),index(1)]=max(abs(Xpoints-x_ima));
423    GeometryCalib.ErrorRms(2)=sqrt(mean((Ypoints-y_ima).*(Ypoints-y_ima)));
424    [GeometryCalib.ErrorMax(2),index(2)]=max(abs(Ypoints-y_ima));
425    [tild,ind_dim]=max(GeometryCalib.ErrorMax);
426    index=index(ind_dim);
427    %set the Z position of the reference plane used for calibration
428    if isequal(max(Z),min(Z))%Z constant
429        Z_plane=Z(1);
430        GeometryCalib.NbSlice=1;
431        GeometryCalib.SliceCoord=[0 0 Z_plane];
432    end
433end
434
435
436%------------------------------------------------------------------------
437% --- determine the parameters for a calibration by an affine function (rescaling and offset, no rotation)
438function GeometryCalib=calib_rescale(Coord,Intrinsic)
439%------------------------------------------------------------------------
440X=Coord(:,1);
441Y=Coord(:,2);% Z not used
442x_ima=Coord(:,4);
443y_ima=Coord(:,5);
444[px]=polyfit(X,x_ima,1);
445[py]=polyfit(Y,y_ima,1);
446% T_x=px(2);
447% T_y=py(2);
448GeometryCalib.CalibrationType='rescale';
449GeometryCalib.fx_fy=[px(1) py(1)];%.fx_fy corresponds to pxcm along x and y
450GeometryCalib.CoordUnit=[];% default value, to be updated by the calling function
451GeometryCalib.Tx_Ty_Tz=[px(2)/px(1) py(2)/py(1) 1];
452GeometryCalib.omc=[0 0 0];
453
454%------------------------------------------------------------------------
455% --- determine the parameters for a calibration by a linear transform matrix (rescale and rotation)
456function GeometryCalib=calib_linear(Coord,Intrinsic)
457%------------------------------------------------------------------------
458X=Coord(:,1);
459Y=Coord(:,2);% Z not used
460x_ima=Coord(:,4);
461y_ima=Coord(:,5);
462XY_mat=[ones(size(X)) X Y];
463a_X1=XY_mat\x_ima; %transformation matrix for X
464a_Y1=XY_mat\y_ima;%transformation matrix for X
465R=[a_X1(2),a_X1(3);a_Y1(2),a_Y1(3)];
466epsilon=sign(det(R));
467norm=abs(det(R));
468GeometryCalib.CalibrationType='linear';
469if (a_X1(2)/a_Y1(3))>0
470    GeometryCalib.fx_fy(1)=sqrt((a_X1(2)/a_Y1(3))*norm);
471else
472    GeometryCalib.fx_fy(1)=-sqrt(-(a_X1(2)/a_Y1(3))*norm);
473end
474GeometryCalib.fx_fy(2)=(a_Y1(3)/a_X1(2))*GeometryCalib.fx_fy(1);
475GeometryCalib.CoordUnit=[];% default value, to be updated by the calling function
476GeometryCalib.Tx_Ty_Tz=[a_X1(1)/GeometryCalib.fx_fy(1) a_Y1(1)/GeometryCalib.fx_fy(2) 1];
477R(1,:)=R(1,:)/GeometryCalib.fx_fy(1);
478R(2,:)=R(2,:)/GeometryCalib.fx_fy(2);
479R=[R;[0 0]];
480GeometryCalib.R=[R [0;0;-epsilon]];
481GeometryCalib.omc=(180/pi)*[acos(GeometryCalib.R(1,1)) 0 0];
482
483%------------------------------------------------------------------------
484% --- determine the tsai parameters for a view normal to the grid plane
485% NOT USED
486function GeometryCalib=calib_normal(Coord,Intrinsic)
487%------------------------------------------------------------------------
488Calib.f1=str2num(get(handles.fx,'String'));
489Calib.f2=str2num(get(handles.fy,'String'));
490Calib.k=str2num(get(handles.kc,'String'));
491Calib.Cx=str2num(get(handles.Cx,'String'));
492Calib.Cy=str2num(get(handles.Cy,'String'));
493%default
494if isempty(Calib.f1)
495    Calib.f1=25/0.012;
496end
497if isempty(Calib.f2)
498    Calib.f2=25/0.012;
499end
500if isempty(Calib.k)
501    Calib.k=0;
502end
503if isempty(Calib.Cx)||isempty(Calib.Cy)
504    huvmat=findobj(allchild(0),'Tag','uvmat');
505    hhuvmat=guidata(huvmat);
506    Calib.Cx=str2num(get(hhuvmat.num_Npx,'String'))/2;
507    Calib.Cx=str2num(get(hhuvmat.num_Npy,'String'))/2;
508end   
509%tsai parameters
510Calib.dpx=0.012;%arbitrary
511Calib.dpy=0.012;
512Calib.sx=Calib.f1*Calib.dpx/(Calib.f2*Calib.dpy);
513Calib.f=Calib.f2*Calib.dpy;
514Calib.kappa1=Calib.k/(Calib.f*Calib.f);
515
516%initial guess
517X=Coord(:,1);
518Y=Coord(:,2);
519Zmean=mean(Coord(:,3));
520x_ima=Coord(:,4)-Calib.Cx;
521y_ima=Coord(:,5)-Calib.Cy;
522XY_mat=[ones(size(X)) X Y];
523a_X1=XY_mat\x_ima; %transformation matrix for X
524a_Y1=XY_mat\y_ima;%transformation matrix for Y
525R=[a_X1(2),a_X1(3),0;a_Y1(2),a_Y1(3),0;0,0,-1];% rotation+ z axis reversal (upward)
526norm=sqrt(det(-R));
527calib_param(1)=0;% quadratic distortion
528calib_param(2)=a_X1(1);
529calib_param(3)=a_Y1(1);
530calib_param(4)=Calib.f/(norm*Calib.dpx)-R(3,3)*Zmean;
531calib_param(5)=angle(a_X1(2)+1i*a_X1(3));
532display(['initial guess=' num2str(calib_param)])
533
534%optimise the parameters: minimisation of error
535calib_param = fminsearch(@(calib_param) error_calib(calib_param,Calib,Coord),calib_param);
536
537GeometryCalib.CalibrationType='tsai_normal';
538GeometryCalib.focal=Calib.f;
539GeometryCalib.dpx_dpy=[Calib.dpx Calib.dpy];
540GeometryCalib.Cx_Cy=[Calib.Cx Calib.Cy];
541GeometryCalib.sx=Calib.sx;
542GeometryCalib.kappa1=calib_param(1);
543GeometryCalib.CoordUnit=[];% default value, to be updated by the calling function
544GeometryCalib.Tx_Ty_Tz=[calib_param(2) calib_param(3) calib_param(4)];
545alpha=calib_param(5);
546GeometryCalib.R=[cos(alpha) sin(alpha) 0;-sin(alpha) cos(alpha) 0;0 0 -1];
547
548%------------------------------------------------------------------------
549function GeometryCalib=calib_3D_linear(Coord,Intrinsic)
550%------------------------------------------------------------------------
551coord_files=Intrinsic.coord_files;
552if ischar(Intrinsic.coord_files)
553    coord_files={coord_files};
554end
555if isempty(coord_files{1}) || isequal(coord_files,{''})
556    coord_files={};
557end
558%retrieve the calibration points stored in the files listed in the popup list ListCoordFiles
559x_1=Coord(:,4:5)';%px coordinates of the ref points
560
561nx=Intrinsic.Npx;
562ny=Intrinsic.Npy;
563x_1(2,:)=ny-x_1(2,:);%reverse the y image coordinates
564X_1=Coord(:,1:3)';%phys coordinates of the ref points
565n_ima=numel(coord_files)+1;
566if ~isempty(coord_files)
567    msgbox_uvmat('CONFIRMATION',['The xy coordinates of the calibration points in ' num2str(n_ima) ' planes will be used'])
568    for ifile=1:numel(coord_files)
569    t=xmltree(coord_files{ifile});
570    s=convert(t);%convert to matlab structure
571        if isfield(s,'GeometryCalib')
572            if isfield(s.GeometryCalib,'SourceCalib')
573                if isfield(s.GeometryCalib.SourceCalib,'PointCoord')
574                PointCoord=s.GeometryCalib.SourceCalib.PointCoord;
575                Coord_file=zeros(length(PointCoord),5);%default
576                for i=1:length(PointCoord)
577                    line=str2num(PointCoord{i});
578                    Coord_file(i,4:5)=line(4:5);%px x
579                    Coord_file(i,1:3)=line(1:3);%phys x
580                end
581                eval(['x_' num2str(ifile+1) '=Coord_file(:,4:5)'';']);
582                eval(['x_' num2str(ifile+1) '(2,:)=ny-x_' num2str(ifile+1) '(2,:);' ]);
583                eval(['X_' num2str(ifile+1) '=Coord_file(:,1:3)'';']);
584                end
585            end
586        end
587    end
588end
589n_ima=numel(coord_files)+1;
590est_dist=[0;0;0;0;0];
591est_aspect_ratio=0;
592est_fc=[1;1];
593center_optim=0;
594path_uvmat=which('uvmat');% check the path detected for source file uvmat
595path_UVMAT=fileparts(path_uvmat); %path to UVMAT
596run(fullfile(path_UVMAT,'toolbox_calib','go_calib_optim'));% apply fct 'toolbox_calib/go_calib_optim'
597if exist('Rc_1','var')
598    GeometryCalib.CalibrationType='3D_linear';
599    GeometryCalib.fx_fy=fc';
600    GeometryCalib.Cx_Cy=cc';
601    GeometryCalib.kc=kc(1);
602    GeometryCalib.CoordUnit=[];% default value, to be updated by the calling function
603    GeometryCalib.Tx_Ty_Tz=Tc_1';
604    GeometryCalib.R=Rc_1;
605    GeometryCalib.R(2,1:3)=-GeometryCalib.R(2,1:3);%inversion of the y image coordinate
606    GeometryCalib.Tx_Ty_Tz(2)=-GeometryCalib.Tx_Ty_Tz(2);%inversion of the y image coordinate
607    GeometryCalib.Cx_Cy(2)=ny-GeometryCalib.Cx_Cy(2);%inversion of the y image coordinate
608    GeometryCalib.omc=(180/pi)*omc_1;%angles in degrees
609    GeometryCalib.ErrorRMS=[];
610    GeometryCalib.ErrorMax=[];
611else
612    msgbox_uvmat('ERROR',['calibration function ' fullfile('toolbox_calib','go_calib_optim') ' did not converge: use multiple views or option 3D_extrinsic'])
613    GeometryCalib=[];
614end
615
616%------------------------------------------------------------------------
617function GeometryCalib=calib_3D_quadr(Coord,Intrinsic)
618%------------------------------------------------------------------
619
620path_uvmat=which('uvmat');% check the path detected for source file uvmat
621path_UVMAT=fileparts(path_uvmat); %path to UVMAT
622huvmat=findobj(allchild(0),'Tag','uvmat');
623hhuvmat=guidata(huvmat);
624if ~strcmp(get(hhuvmat.Scalar,'Visible'),'on')
625    msgbox_uvmat('ERROR','An image needs to be opened in uvmat for calibration')
626  return
627end
628% check_cond=0;
629
630coord_files=Intrinsic.coord_files;
631
632if ischar(coord_files)
633    coord_files={coord_files};
634end
635if isempty(coord_files{1}) || isequal(coord_files,{''})
636    coord_files={};
637end
638
639%retrieve the calibration points stored in the files listed in the popup list ListCoordFiles
640x_1=Coord(:,4:5)';%px coordinates of the ref points
641nx=str2num(get(hhuvmat.num_Npx,'String'));
642ny=str2num(get(hhuvmat.num_Npy,'String'));
643x_1(2,:)=ny-x_1(2,:);%reverse the y image coordinates
644X_1=Coord(:,1:3)';%phys coordinates of the ref points
645n_ima=numel(coord_files)+1;
646if ~isempty(coord_files)
647    msgbox_uvmat('CONFIRMATION',['The xy coordinates of the calibration points in ' num2str(n_ima) ' planes will be used'])
648    for ifile=1:numel(coord_files)
649    t=xmltree(coord_files{ifile});
650    s=convert(t);%convert to matlab structure
651        if isfield(s,'GeometryCalib')
652            if isfield(s.GeometryCalib,'SourceCalib')
653                if isfield(s.GeometryCalib.SourceCalib,'PointCoord')
654                PointCoord=s.GeometryCalib.SourceCalib.PointCoord;
655                Coord_file=zeros(length(PointCoord),5);%default
656                for i=1:length(PointCoord)
657                    line=str2num(PointCoord{i});
658                    Coord_file(i,4:5)=line(4:5);%px x
659                    Coord_file(i,1:3)=line(1:3);%phys x
660                end
661                eval(['x_' num2str(ifile+1) '=Coord_file(:,4:5)'';']);
662                eval(['x_' num2str(ifile+1) '(2,:)=ny-x_' num2str(ifile+1) '(2,:);' ]);
663                eval(['X_' num2str(ifile+1) '=Coord_file(:,1:3)'';']);
664                end
665            end
666        end
667    end
668end
669n_ima=numel(coord_files)+1;
670est_dist=[1;0;0;0;0];
671est_aspect_ratio=1;
672center_optim=0;
673run(fullfile(path_UVMAT,'toolbox_calib','go_calib_optim'));% apply fct 'toolbox_calib/go_calib_optim'
674
675if exist('Rc_1','var')
676    GeometryCalib.CalibrationType='3D_quadr';
677    GeometryCalib.fx_fy=fc';
678    GeometryCalib.Cx_Cy=cc';
679    GeometryCalib.kc=kc(1);
680    GeometryCalib.CoordUnit=[];% default value, to be updated by the calling function
681    GeometryCalib.Tx_Ty_Tz=Tc_1';
682    GeometryCalib.R=Rc_1;
683    GeometryCalib.R(2,1:3)=-GeometryCalib.R(2,1:3);%inversion of the y image coordinate
684    GeometryCalib.Tx_Ty_Tz(2)=-GeometryCalib.Tx_Ty_Tz(2);%inversion of the y image coordinate
685    GeometryCalib.Cx_Cy(2)=ny-GeometryCalib.Cx_Cy(2);%inversion of the y image coordinate
686    GeometryCalib.omc=(180/pi)*omc_1;%angles in degrees
687    GeometryCalib.ErrorRMS=[];
688    GeometryCalib.ErrorMax=[];
689else
690    msgbox_uvmat('ERROR',['calibration function ' fullfile('toolbox_calib','go_calib_optim') ' did not converge: use multiple views or option 3D_extrinsic'])
691    GeometryCalib=[];
692end
693
694%------------------------------------------------------------------------
695function GeometryCalib=calib_3D_extrinsic(Coord,Intrinsic)
696%------------------------------------------------------------------
697path_uvmat=which('geometry_calib');% check the path detected for source file uvmat
698path_UVMAT=fileparts(path_uvmat); %path to UVMAT
699x_1=double(Coord(:,4:5)');%image coordinates
700X_1=double(Coord(:,1:3)');% phys coordinates
701huvmat=findobj(allchild(0),'Tag','uvmat');
702hhuvmat=guidata(huvmat);
703if ~strcmp(get(hhuvmat.Scalar,'Visible'),'on')
704    msgbox_uvmat('ERROR','An image needs to be opened in uvmat for calibration')
705  return
706end
707ny=str2double(get(hhuvmat.num_Npy,'String'));
708x_1(2,:)=ny-x_1(2,:);%reverse the y image coordinates
709n_ima=1;
710GeometryCalib.CalibrationType='3D_extrinsic';
711fx=str2num(get(Intrinsic.fx,'String'));
712fy=str2num(get(Intrinsic.fy,'String'));
713Cx=str2num(get(Intrinsic.Cx,'String'));
714Cy=str2num(get(Intrinsic.Cy,'String'));
715errormsg='';
716if isempty(fx)
717    errormsg='focal length fx needs to be introduced';
718elseif isempty(fy)
719    errormsg='focal length fy needs to be introduced';
720elseif isempty(Cx)
721    errormsg='shift Cx to image centre needs to be introduced';
722elseif isempty(Cy)
723    errormsg='shift Cy to image centre needs to be introduced';
724end
725if ~isempty(errormsg)
726    GeometryCalib=[];
727    msgbox_uvmat('ERROR',errormsg)
728    return
729end
730GeometryCalib.fx_fy(1)=str2num(get(Intrinsic.fx,'String'));
731GeometryCalib.fx_fy(2)=str2num(get(Intrinsic.fy,'String'));
732GeometryCalib.Cx_Cy(1)=str2num(get(Intrinsic.Cx,'String'));
733GeometryCalib.Cx_Cy(2)=str2num(get(Intrinsic.Cy,'String'));
734GeometryCalib.kc=str2num(get(Intrinsic.kc,'String'));
735fct_path=fullfile(path_UVMAT,'toolbox_calib');
736addpath(fct_path)
737GeometryCalib.Cx_Cy(2)=ny-GeometryCalib.Cx_Cy(2);%reverse Cx_Cy(2) for calibration (inversion of px ordinate)
738[omc,Tc1,Rc1,H,x,ex,JJ] = compute_extrinsic(x_1,X_1,...
739   (GeometryCalib.fx_fy)',GeometryCalib.Cx_Cy',[GeometryCalib.kc 0 0 0 0]);
740rmpath(fct_path);
741GeometryCalib.CoordUnit=[];% default value, to be updated by the calling function
742GeometryCalib.Tx_Ty_Tz=Tc1';
743%inversion of z axis
744GeometryCalib.R=Rc1;
745GeometryCalib.R(2,1:3)=-GeometryCalib.R(2,1:3);%inversion of the y image coordinate
746GeometryCalib.Tx_Ty_Tz(2)=-GeometryCalib.Tx_Ty_Tz(2);%inversion of the y image coordinate
747GeometryCalib.Cx_Cy(2)=ny-GeometryCalib.Cx_Cy(2);%inversion of the y image coordinate
748GeometryCalib.omc=(180/pi)*omc';
749
750%------------------------------------------------------------------------
751%function GeometryCalib=calib_tsai_heikkila(Coord)
752% TEST: NOT IMPLEMENTED
753%------------------------------------------------------------------
754% path_uvmat=which('uvmat');% check the path detected for source file uvmat
755% path_UVMAT=fileparts(path_uvmat); %path to UVMAT
756% path_calib=fullfile(path_UVMAT,'toolbox_calib_heikkila');
757% addpath(path_calib)
758% npoints=size(Coord,1);
759% Coord(:,1:3)=10*Coord(:,1:3);
760% Coord=[Coord zeros(npoints,2) -ones(npoints,1)];
761% [par,pos,iter,res,er,C]=cacal('dalsa',Coord);
762% GeometryCalib.CalibrationType='tsai';
763% GeometryCalib.focal=par(2);
764
765
766%------------------------------------------------------------------------
767% --- determine the rms of calibration error
768function ErrorRms=error_calib(calib_param,Calib,Coord)
769%------------------------------------------------------------------------
770%calib_param: vector of free calibration parameters (to optimise)
771%Calib: structure of the given calibration parameters
772%Coord: list of phys coordinates (columns 1-3, and pixel coordinates (columns 4-5)
773Calib.f=25;
774Calib.dpx=0.012;
775Calib.dpy=0.012;
776Calib.sx=1;
777Calib.Cx=512;
778Calib.Cy=512;
779Calib.kappa1=calib_param(1);
780Calib.Tx=calib_param(2);
781Calib.Ty=calib_param(3);
782Calib.Tz=calib_param(4);
783alpha=calib_param(5);
784Calib.R=[cos(alpha) sin(alpha) 0;-sin(alpha) cos(alpha) 0;0 0 -1];
785
786X=Coord(:,1);
787Y=Coord(:,2);
788Z=Coord(:,3);
789x_ima=Coord(:,4);
790y_ima=Coord(:,5);
791[Xpoints,Ypoints]=px_XYZ(Calib,X,Y,Z);
792ErrorRms(1)=sqrt(mean((Xpoints-x_ima).*(Xpoints-x_ima)));
793ErrorRms(2)=sqrt(mean((Ypoints-y_ima).*(Ypoints-y_ima)));
794ErrorRms=mean(ErrorRms);
795
796
797%------------------------------------------------------------------------
798% --- Executes on button press in STORE.
799function STORE_Callback(hObject, eventdata, handles)
800%------------------------------------------------------------------------
801Coord=get(handles.ListCoord,'Data');
802%Object=read_geometry_calib(Coord_cell);
803unitlist=get(handles.CoordUnit,'String');
804unit=unitlist{get(handles.CoordUnit,'value')};
805GeometryCalib.CoordUnit=unit;
806GeometryCalib.SourceCalib.PointCoord=Coord(:,1:5);
807huvmat=findobj(allchild(0),'Name','uvmat');
808hhuvmat=guidata(huvmat);%handles of elements in the GUI uvmat
809% RootPath='';
810% RootFile='';
811if ~isempty(hhuvmat.RootPath)&& ~isempty(hhuvmat.RootFile)
812%     testhandle=1;
813    RootPath=get(hhuvmat.RootPath,'String');
814    RootFile=get(hhuvmat.RootFile,'String');
815    filebase=[fullfile(RootPath,RootFile) '~'];
816    while exist([filebase '.xml'],'file')
817        filebase=[filebase '~'];
818    end
819    outputfile=[filebase '.xml'];
820    errormsg=update_imadoc(GeometryCalib,outputfile,'GeometryCalib');
821    if ~strcmp(errormsg,'')
822        msgbox_uvmat('ERROR',errormsg);
823    end
824    listfile=get(handles.ListCoordFiles,'string');
825    if isequal(listfile,{''})
826        listfile={outputfile};
827    else
828        listfile=[listfile;{outputfile}];%update the list of coord files
829    end
830    set(handles.ListCoordFiles,'string',listfile);
831end
832ClearAll_Callback(hObject, eventdata, handles)% clear the current list and point plots
833
834% --------------------------------------------------------------------
835% --- Executes on button press in ClearAll: clear the list of calibration points
836function ClearAll_Callback(hObject, eventdata, handles)
837% --------------------------------------------------------------------
838set(handles.ListCoord,'Data',[])
839PLOT_Callback(hObject, eventdata, handles)
840update_calib_marker([]);%remove circle marker
841set(handles.APPLY,'backgroundColor',[1 0 0])% set APPLY button to red color: no calibration wanted without points
842set(handles.CheckEnableMouse,'value',1); %activate mouse to pick new points
843
844%------------------------------------------------------------------------
845% --- Executes on button press in CLEAR LIST
846function CLEAR_Callback(hObject, eventdata, handles)
847%------------------------------------------------------------------------
848set(handles.ListCoordFiles,'Value',1)
849set(handles.ListCoordFiles,'String',{''})
850
851%------------------------------------------------------------------------
852% --- Executes on selection change in CheckEnableMouse.
853function CheckEnableMouse_Callback(hObject, eventdata, handles)
854%------------------------------------------------------------------------
855choice=get(handles.CheckEnableMouse,'Value');
856if choice
857    huvmat=findobj(allchild(0),'tag','uvmat');
858    if ishandle(huvmat)
859        hhuvmat=guidata(huvmat);
860        set(hhuvmat.MenuRuler,'checked','off')%desactivate ruler
861        if get(hhuvmat.CheckEditObject,'Value')
862            set(hhuvmat.CheckEditObject,'Value',0)
863            uvmat('CheckEditObject_Callback',hhuvmat.CheckEditObject,[],hhuvmat)
864        end
865        set(hhuvmat.MenuRuler,'checked','off')%desactivate ruler
866    end
867end
868
869% --------------------------------------------------------------------
870function MenuHelp_Callback(hObject, eventdata, handles)
871web('http://servforge.legi.grenoble-inp.fr/projects/soft-uvmat/wiki/UvmatHelp#GeometryCalib')
872
873% --------------------------------------------------------------------
874function MenuSetScale_Callback(hObject, eventdata, handles)
875
876answer=msgbox_uvmat('INPUT_TXT','scale pixel/cm?','');
877%create test points
878huvmat=findobj(allchild(0),'Name','uvmat');%find the current uvmat interface handle
879hhuvmat=guidata(huvmat);
880if ~strcmp(get(hhuvmat.Scalar,'Visible'),'on')
881    msgbox_uvmat('ERROR','An image needs to be opened in uvmat for calibration')
882    return
883end
884set(handles.calib_type,'Value',1)% set calib option to 'rescale'
885npx=str2num(get(hhuvmat.num_Npx,'String'))/2;
886npy=str2num(get(hhuvmat.num_Npy,'String'))/2;
887Xima=[0.25*npx 0.75*npx 0.75*npx 0.25*npx]';
888Yima=[0.25*npy 0.25*npy 0.75*npy 0.75*npy]';
889x=Xima/str2num(answer);
890y=Yima/str2num(answer);
891Coord=[x y zeros(4,1) Xima Yima zeros(4,1)];
892set(handles.ListCoord,'Data',Coord)
893set(handles.APPLY,'BackgroundColor',[1 0 1])
894set(handles.CheckEnableMouse,'value',0); %desactivate mouse to avoid spurious points
895
896%------------------------------------------------------------------------
897function MenuCreateGrid_Callback(hObject, eventdata, handles)
898%------------------------------------------------------------------------
899CalibData=get(handles.geometry_calib,'UserData');
900Tinput=[];%default
901if isfield(CalibData,'grid')
902    Tinput=CalibData.grid;
903end
904[T,CalibData.grid]=create_grid(Tinput);%display the GUI create_grid
905set(handles.geometry_calib,'UserData',CalibData)
906
907%grid in phys space
908Coord=get(handles.ListCoord,'Data');
909Coord(1:size(T,1),1:3)=T;%update the existing list of phys coordinates from the GUI create_grid
910set(handles.ListCoord,'Data',Coord)
911set(handles.APPLY,'BackgroundColor',[1 0 1])
912set(handles.CheckEnableMouse,'value',0); %desactivate mouse to avoid spurious points
913
914% -----------------------------------------------------------------------
915% --- automatic grid dectection from local maxima of the images
916function MenuDetectGrid_Callback(hObject, eventdata, handles)
917%------------------------------------------------------------------------
918%% read the four last point coordinates in pixels
919Coord=get(handles.ListCoord,'Data');%read list of coordinates on geometry_calib
920nbpoints=size(Coord,1); %nbre of calibration points
921if nbpoints~=4
922    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')
923    return
924end
925% corners_X=(Coord(end:-1:end-3,4)); %pixel absissa of the four corners
926% corners_Y=(Coord(end:-1:end-3,5));
927corners_X=(Coord(:,4)); %pixel absissa of the four corners
928corners_Y=(Coord(:,5));
929
930%%%%%%
931%   corners_X=1000*[1.5415  1.7557 1.7539 1.5415]';
932%   corners_Y=1000*[1.1515 1.1509 1.3645  1.3639]';
933
934%reorder the last two points (the two first in the list) if needed
935angles=angle((corners_X-corners_X(1))+1i*(corners_Y-corners_Y(1)));
936if abs(angles(4)-angles(2))>abs(angles(3)-angles(2))
937      X_end=corners_X(4);
938      Y_end=corners_Y(4);
939      corners_X(4)=corners_X(3);
940      corners_Y(4)=corners_Y(3);
941      corners_X(3)=X_end;
942      corners_Y(3)=Y_end;
943end
944
945%% initiate the grid in phys coordinates
946CalibData=get(handles.geometry_calib,'UserData');%get information stored on the GUI geometry_calib
947grid_input=[];%default
948if isfield(CalibData,'grid')
949    grid_input=CalibData.grid;%retrieve the previously used grid
950end
951[T,CalibData.grid,CalibData.grid.CheckWhite,CalibData.grid.FilterWindow]=create_grid(grid_input,'detect_grid');%display the GUI create_grid, read the set of phys coordinates T
952set(handles.geometry_calib,'UserData',CalibData)%store the phys grid parameters for later use
953X=[CalibData.grid.x_0 CalibData.grid.x_1 CalibData.grid.x_0 CalibData.grid.x_1]';%corner absissa in the phys coordinates (cm)
954Y=[CalibData.grid.y_0 CalibData.grid.y_0 CalibData.grid.y_1 CalibData.grid.y_1]';%corner ordinates in the phys coordinates (cm)
955
956%% read the current image, displayed in the GUI uvmat
957huvmat=findobj(allchild(0),'Name','uvmat');
958UvData=get(huvmat,'UserData');
959A=UvData.Field.A;%currently displayed image
960npxy=size(A);
961
962%% calculate transform matrices for plane projection: rectangle assumed to be viewed in perspective
963% reference: http://alumni.media.mit.edu/~cwren/interpolator/ by Christopher R. Wren
964B = [ X Y ones(size(X)) zeros(4,3)        -X.*corners_X -Y.*corners_X ...
965      zeros(4,3)        X Y ones(size(X)) -X.*corners_Y -Y.*corners_Y ];
966B = reshape (B', 8 , 8 )';
967D = [ corners_X , corners_Y ];
968D = reshape (D', 8 , 1 );
969l = (B' * B)\B' * D;
970Amat = reshape([l(1:6)' 0 0 1 ],3,3)';
971C = [l(7:8)' 1];
972
973%% transform grid image into 'phys' coordinates
974GeometryCalib.CalibrationType='3D_linear';
975GeometryCalib.fx_fy=[1 1];
976GeometryCalib.Tx_Ty_Tz=[Amat(1,3) Amat(2,3) 1];
977GeometryCalib.R=[Amat(1,1),Amat(1,2),0;Amat(2,1),Amat(2,2),0;C(1),C(2),0];
978GeometryCalib.CoordUnit='cm';
979path_uvmat=which('uvmat');% check the path detected for source file uvmat
980path_UVMAT=fileparts(path_uvmat); %path to UVMAT
981addpath(fullfile(path_UVMAT,'transform_field'))
982Data.ListVarName={'Coord_y','Coord_x','A'};
983Data.VarDimName={'Coord_y','Coord_x',{'Coord_y','Coord_x'}};
984if ndims(A)==3
985    A=mean(A,3);
986end
987Data.A=A-min(min(A));
988Data.Coord_y=[npxy(1)-0.5 0.5];
989Data.Coord_x=[0.5 npxy(2)];
990Data.CoordUnit='pixel';
991Calib.GeometryCalib=GeometryCalib;
992DataOut=phys(Data,Calib);
993rmpath(fullfile(path_UVMAT,'transform_field'))
994Amod=DataOut.A;% current image expressed in 'phys' coord
995Rangx=DataOut.Coord_x;% x coordinates of first and last pixel centres in phys
996Rangy=DataOut.Coord_y;% y coordinates of first and last pixel centres in phys
997if CalibData.grid.CheckWhite
998    Amod=double(Amod);%case of white grid markers: will look for image maxima
999else
1000    Amod=-double(Amod);%case of black grid markers: will look for image minima
1001end
1002
1003%%%%%%filterfor i;proved detection of dots
1004if ~isequal(CalibData.grid.FilterWindow,0)
1005    %definition of the cos shape matrix filter
1006    FilterBoxSize_x=CalibData.grid.FilterWindow;
1007    FilterBoxSize_y=CalibData.grid.FilterWindow;
1008    ix=1/2-FilterBoxSize_x/2:-1/2+FilterBoxSize_x/2;%
1009    iy=1/2-FilterBoxSize_y/2:-1/2+FilterBoxSize_y/2;%
1010    %del=np/3;
1011    %fct=exp(-(ix/del).^2);
1012    fct2_x=cos(ix/((FilterBoxSize_x-1)/2)*pi/2);
1013    fct2_y=cos(iy/((FilterBoxSize_y-1)/2)*pi/2);
1014    %Mfiltre=(ones(5,5)/5^2);
1015    Mfiltre=fct2_y'*fct2_x;
1016    Mfiltre=Mfiltre/(sum(sum(Mfiltre)));%normalize filter
1017   
1018    if ndims(Amod)==3
1019        Amod=filter2(Mfiltre,sum(Amod,3));%filter the input image, after summation on the color component (for color images)
1020    else
1021        Amod=filter2(Mfiltre,Amod);
1022    end
1023end
1024%%%%%%%%%%%%%%
1025
1026
1027%% detection of local image extrema in each direction
1028Dx=(Rangx(2)-Rangx(1))/(npxy(2)-1); %x mesh in real space
1029Dy=(Rangy(2)-Rangy(1))/(npxy(1)-1); %y mesh in real space
1030ind_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
1031ind_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
1032nbpoints=size(T,1);
1033TIndex=ones(size(T));% image indices corresponding to point coordinates
1034%look for image maxima around each expected grid point
1035for ipoint=1:nbpoints
1036    i0=1+round((T(ipoint,1)-Rangx(1))/Dx);% x index of the expected point in the phys image Amod
1037    j0=1+round((T(ipoint,2)-Rangy(1))/Dy);% y index of the expected point in the phys image Amod
1038    j0min=max(j0-ind_range_y,1);% min y index selected for the subimage (cut at the edge to avoid index <1)
1039    j0max=min(j0+ind_range_y,size(Amod,1));% max y index selected for the subimage (cut at the edge to avoid index > size)
1040    i0min=max(i0-ind_range_x,1);% min x index selected for the subimage (cut at the edge to avoid index <1)
1041    i0max=min(i0+ind_range_x,size(Amod,2));% max x index selected for the subimage (cut at the edge to avoid index > size)
1042    Asub=Amod(j0min:j0max,i0min:i0max); %subimage used to find brigthness extremum
1043    x_profile=sum(Asub,1);%profile of subimage summed over y
1044    y_profile=sum(Asub,2);%profile of subimage summed over x
1045
1046    [tild,ind_x_max]=max(x_profile);% index of max for the x profile
1047    [tild,ind_y_max]=max(y_profile);% index of max for the y profile
1048    %sub-pixel improvement using moments
1049    x_shift=0;
1050    y_shift=0;
1051    if ind_x_max+2<=numel(x_profile) && ind_x_max-2>=1
1052        Atop=x_profile(ind_x_max-2:ind_x_max+2);% extract x profile around the max
1053        x_shift=sum(Atop.*[-2 -1 0 1 2])/sum(Atop);
1054    end
1055    if ind_y_max+2<=numel(y_profile) && ind_y_max-2>=1
1056        Atop=y_profile(ind_y_max-2:ind_y_max+2);% extract y profile around the max
1057        y_shift=sum(Atop.*[-2 -1 0 1 2]')/sum(Atop);
1058    end
1059        %%%%
1060%     if ipoint==9
1061%                 figure(11)
1062%   imagesc(Asub)
1063%     figure(12)
1064%     plot(x_profile,'r')
1065%     hold on
1066%     plot(y_profile,'b')
1067%     grid on
1068%     end
1069    %%%%
1070    TIndex(ipoint,1)=(i0min+ind_x_max-1+x_shift);% x position of the maximum (in index of Amod)
1071    TIndex(ipoint,2)=(j0min+ind_y_max-1+y_shift);% y position of the maximum (in index of Amod)
1072end
1073Tmod(:,1)=(TIndex(:,1)-1)*Dx+Rangx(1);
1074Tmod(:,2)=(TIndex(:,2)-1)*Dy+Rangy(1);
1075%Tmod=T(:,(1:2))+Delta;% 'phys' coordinates of the detected points
1076[Xpx,Ypx]=px_XYZ(GeometryCalib,Tmod(:,1),Tmod(:,2));% image coordinates of the detected points
1077Coord=[T Xpx Ypx zeros(size(T,1),1)];
1078set(handles.ListCoord,'Data',Coord)
1079PLOT_Callback(hObject, eventdata, handles)
1080set(handles.APPLY,'BackgroundColor',[1 0 1])
1081set(handles.CheckEnableMouse,'value',0); %desactivate mouse to avoid spurious points
1082
1083
1084%-----------------------------------------------------------------------
1085function MenuTranslatePoints_Callback(hObject, eventdata, handles)
1086%-----------------------------------------------------------------------
1087%hcalib=get(handles.calib_type,'parent');%handles of the GUI geometry_calib
1088CalibData=get(handles.geometry_calib,'UserData');
1089Tinput=[];%default
1090if isfield(CalibData,'translate')
1091    Tinput=CalibData.translate;
1092end
1093T=translate_points(Tinput);%display translate_points GUI and get shift parameters
1094CalibData.translate=T;
1095set(handles.geometry_calib,'UserData',CalibData)
1096%translation
1097Coord=get(handles.ListCoord,'Data');
1098Coord(:,1)=T(1)+Coord(:,1);
1099Coord(:,2)=T(2)+Coord(:,2);
1100Coord(:,3)=T(3)+Coord(:,3);
1101set(handles.ListCoord,'Data',Coord);
1102set(handles.APPLY,'BackgroundColor',[1 0 1])
1103
1104% --------------------------------------------------------------------
1105function MenuRotatePoints_Callback(hObject, eventdata, handles)
1106%hcalib=get(handles.calib_type,'parent');%handles of the GUI geometry_calib
1107CalibData=get(handles.geometry_calib,'UserData');
1108Tinput=[];%default
1109if isfield(CalibData,'rotate')
1110    Tinput=CalibData.rotate;
1111end
1112T=rotate_points(Tinput);%display rotate_points GUI to introduce rotation parameters
1113CalibData.rotate=T;
1114set(handles.geometry_calib,'UserData',CalibData)
1115%-----------------------------------------------------
1116%rotation
1117Phi=T(1);
1118O_x=0;%default
1119O_y=0;%default
1120if numel(T)>=2
1121    O_x=T(2);%default
1122end
1123if numel(T)>=3
1124    O_y=T(3);%default
1125end
1126Coord=get(handles.ListCoord,'Data');
1127r1=cos(pi*Phi/180);
1128r2=-sin(pi*Phi/180);
1129r3=sin(pi*Phi/180);
1130r4=cos(pi*Phi/180);
1131x=Coord(:,1)-O_x;
1132y=Coord(:,2)-O_y;
1133Coord(:,1)=r1*x+r2*y;
1134Coord(:,2)=r3*x+r4*y;
1135set(handles.ListCoord,'Data',Coord)
1136set(handles.APPLY,'BackgroundColor',[1 0 1])
1137
1138% --------------------------------------------------------------------
1139function MenuFlip_x_Callback(hObject, eventdata, handles)
1140Coord=get(handles.ListCoord,'Data');
1141Coord(:,1)=-Coord(:,1);
1142set(handles.ListCoord,'Data',Coord)
1143
1144% --------------------------------------------------------------------
1145function MenuFlip_y_Callback(hObject, eventdata, handles)
1146Coord=get(handles.ListCoord,'Data');
1147Coord(:,2)=-Coord(:,2);
1148set(handles.ListCoord,'Data',Coord)
1149
1150% --------------------------------------------------------------------
1151function MenuImportPoints_Callback(hObject, eventdata, handles)
1152fileinput=browse_xml(hObject, eventdata, handles);
1153if isempty(fileinput)
1154    return
1155end
1156[s,errormsg]=imadoc2struct(fileinput,'GeometryCalib');
1157if ~isfield(s,'GeometryCalib')
1158    msgbox_uvmat('ERROR','invalid input file: no geometry_calib data')
1159    return
1160end
1161GeometryCalib=s.GeometryCalib;
1162if ~(isfield(GeometryCalib,'SourceCalib')&&isfield(GeometryCalib.SourceCalib,'PointCoord'))
1163        msgbox_uvmat('ERROR','invalid input file: no calibration points')
1164    return
1165end
1166Coord=GeometryCalib.SourceCalib.PointCoord;
1167Coord=[Coord zeros(size(Coord,1),1)];
1168set(handles.ListCoord,'Data',Coord)
1169PLOT_Callback(handles.geometry_calib, [], handles)
1170set(handles.APPLY,'BackgroundColor',[1 0 1])
1171set(handles.CheckEnableMouse,'value',0); %desactivate mouse to avoid modifications by default
1172
1173% -----------------------------------------------------------------------
1174function MenuImportIntrinsic_Callback(hObject, eventdata, handles)
1175%------------------------------------------------------------------------
1176fileinput=browse_xml(hObject, eventdata, handles);
1177if isempty(fileinput)
1178    return
1179end
1180[s,errormsg]=imadoc2struct(fileinput,'GeometryCalib');
1181GeometryCalib=s.GeometryCalib;
1182display_intrinsic(GeometryCalib,handles)
1183
1184% -----------------------------------------------------------------------
1185function MenuImportAll_Callback(hObject, eventdata, handles)
1186%------------------------------------------------------------------------
1187fileinput=browse_xml(hObject, eventdata, handles);
1188if ~isempty(fileinput)
1189    loadfile(handles,fileinput)
1190end
1191set(handles.CheckEnableMouse,'value',0); %desactivate mouse to avoid modifications by default
1192
1193% -----------------------------------------------------------------------
1194% --- Executes on menubar option Import/Grid file: introduce previous grid files
1195function MenuGridFile_Callback(hObject, eventdata, handles)
1196% -----------------------------------------------------------------------
1197inputfile=browse_xml(hObject, eventdata, handles);
1198listfile=get(handles.ListCoordFiles,'String');
1199if isequal(listfile,{''})
1200    listfile={inputfile};
1201else
1202    listfile=[listfile;{inputfile}];%update the list of coord files
1203end
1204set(handles.ListCoordFiles,'String',listfile);
1205
1206
1207%------------------------------------------------------------------------
1208function fileinput=browse_xml(hObject, eventdata, handles)
1209%------------------------------------------------------------------------
1210fileinput=[];%default
1211oldfile=''; %default
1212UserData=get(handles.geometry_calib,'UserData');
1213if isfield(UserData,'XmlInputFile')
1214    oldfile=UserData.XmlInputFile;
1215end
1216[FileName, PathName, filterindex] = uigetfile( ...
1217       {'*.xml;*.mat', ' (*.xml,*.mat)';
1218       '*.xml',  '.xml files '; ...
1219        '*.mat',  '.mat matlab files '}, ...
1220        'Pick a file',oldfile);
1221fileinput=[PathName FileName];%complete file name
1222testblank=findstr(fileinput,' ');%look for blanks
1223if ~isempty(testblank)
1224    msgbox_uvmat('ERROR','forbidden input file name or path: no blank character allowed')
1225    return
1226end
1227sizf=size(fileinput);
1228if (~ischar(fileinput)||~isequal(sizf(1),1)),return;end
1229UserData.XmlInputFile=fileinput;
1230set(handles.geometry_calib,'UserData',UserData)%record current file foer further use of browser
1231
1232% -----------------------------------------------------------------------
1233function Heading=loadfile(handles,fileinput)
1234%------------------------------------------------------------------------
1235Heading=[];%default
1236[s,errormsg]=imadoc2struct(fileinput,'Heading','GeometryCalib');
1237if ~isempty(errormsg)
1238    msgbox_uvmat('ERROR',errormsg)
1239    return
1240end
1241if ~isempty(s.Heading)
1242    Heading=s.Heading;
1243end
1244
1245GeometryCalib=s.GeometryCalib;
1246fx=1;fy=1;Cx=0;Cy=0;kc=0; %default
1247CoordCell={};
1248Tabchar={};%default
1249val_cal=1;%default
1250if ~isempty(GeometryCalib)
1251    % choose the calibration option
1252    if isfield(GeometryCalib,'CalibrationType')
1253        calib_list=get(handles.calib_type,'String');
1254        for ilist=1:numel(calib_list)
1255            if strcmp(calib_list{ilist},GeometryCalib.CalibrationType)
1256                val_cal=ilist;
1257                break
1258            end
1259        end
1260    end
1261    display_intrinsic(GeometryCalib,handles)%intrinsic param
1262    %extrinsic param
1263    if isfield(GeometryCalib,'Tx_Ty_Tz')
1264        Tx_Ty_Tz=GeometryCalib.Tx_Ty_Tz;
1265        set(handles.Tx,'String',num2str(GeometryCalib.Tx_Ty_Tz(1),4))
1266        set(handles.Ty,'String',num2str(GeometryCalib.Tx_Ty_Tz(2),4))
1267        set(handles.Tz,'String',num2str(GeometryCalib.Tx_Ty_Tz(3),4))
1268    end
1269    if isfield(GeometryCalib,'omc')
1270        set(handles.Phi,'String',num2str(GeometryCalib.omc(1),4))
1271        set(handles.Theta,'String',num2str(GeometryCalib.omc(2),4))
1272        set(handles.Psi,'String',num2str(GeometryCalib.omc(3),4))
1273    end
1274    if isfield(GeometryCalib,'SourceCalib')&& isfield(GeometryCalib.SourceCalib,'PointCoord')
1275        calib=GeometryCalib.SourceCalib.PointCoord;
1276        Coord=[calib zeros(size(calib,1),1)];
1277        set(handles.ListCoord,'Data',Coord)
1278    end
1279    PLOT_Callback(handles.geometry_calib, [], handles)
1280    set(handles.APPLY,'BackgroundColor',[1 0 1])
1281end
1282set(handles.calib_type,'Value',val_cal)
1283
1284if isempty(CoordCell)% allow mouse action by default in the absence of input points
1285    set(handles.CheckEnableMouse,'Value',1)
1286    set(handles.CheckEnableMouse,'BackgroundColor',[1 1 0])
1287else % does not allow mouse action by default in the presence of input points
1288    set(handles.CheckEnableMouse,'Value',0)
1289    set(handles.CheckEnableMouse,'BackgroundColor',[0.7 0.7 0.7])
1290end
1291
1292%------------------------------------------------------------------------
1293%---display calibration intrinsic parameters
1294function display_intrinsic(GeometryCalib,handles)
1295%------------------------------------------------------------------------
1296fx=[];
1297fy=[];
1298if isfield(GeometryCalib,'fx_fy')
1299    fx=GeometryCalib.fx_fy(1);
1300    fy=GeometryCalib.fx_fy(2);
1301end
1302Cx_Cy=[0 0];%default
1303if isfield(GeometryCalib,'Cx_Cy')
1304    Cx_Cy=GeometryCalib.Cx_Cy;
1305end
1306kc=0;
1307if isfield(GeometryCalib,'kc')
1308    kc=GeometryCalib.kc; %* GeometryCalib.focal*GeometryCalib.focal;
1309end
1310set(handles.fx,'String',num2str(fx,5))
1311set(handles.fy,'String',num2str(fy,5))
1312set(handles.Cx,'String',num2str(Cx_Cy(1),'%1.1f'))
1313set(handles.Cy,'String',num2str(Cx_Cy(2),'%1.1f'))
1314set(handles.kc,'String',num2str(kc,'%1.4f'))
1315
1316%------------------------------------------------------------------------
1317% ---display calibration extrinsic parameters
1318function display_extrinsic(GeometryCalib,handles)
1319%------------------------------------------------------------------------
1320set(handles.Tx,'String',num2str(GeometryCalib.Tx_Ty_Tz(1),4))
1321set(handles.Ty,'String',num2str(GeometryCalib.Tx_Ty_Tz(2),4))
1322set(handles.Tz,'String',num2str(GeometryCalib.Tx_Ty_Tz(3),4))
1323set(handles.Phi,'String',num2str(GeometryCalib.omc(1),4))
1324set(handles.Theta,'String',num2str(GeometryCalib.omc(2),4))
1325set(handles.Psi,'String',num2str(GeometryCalib.omc(3),4))
1326
1327%------------------------------------------------------------------------
1328% --- executes when user attempts to close geometry_calib.
1329function geometry_calib_CloseRequestFcn(hObject, eventdata, handles)
1330%------------------------------------------------------------------------
1331delete(hObject); % closes the figure
1332
1333%------------------------------------------------------------------------
1334% --- executes on button press in PLOT.
1335%------------------------------------------------------------------------
1336function PLOT_Callback(hObject, eventdata, handles)
1337huvmat=findobj(allchild(0),'Name','uvmat');%find the current uvmat interface handle
1338hhuvmat=guidata(huvmat); %handles of GUI elements in uvmat
1339h_menu_coord=findobj(huvmat,'Tag','TransformName');
1340menu=get(h_menu_coord,'String');
1341choice=get(h_menu_coord,'Value');
1342option='';
1343if iscell(menu)
1344    option=menu{choice};
1345end
1346Coord=get(handles.ListCoord,'Data');
1347if ~isempty(Coord)
1348    if isequal(option,'phys')
1349        Coord_plot=Coord(:,1:3);
1350    elseif isempty(option);%optionoption,'px')||isequal(option,'')
1351        Coord_plot=Coord(:,4:5);
1352    else
1353        msgbox_uvmat('ERROR','the choice in menu_coord of uvmat must be blank or phys ')
1354    end
1355end
1356
1357set(0,'CurrentFigure',huvmat)
1358set(huvmat,'CurrentAxes',hhuvmat.PlotAxes)
1359hh=findobj('Tag','calib_points');
1360if  ~isempty(Coord) && isempty(hh)
1361    hh=line(Coord_plot(:,1),Coord_plot(:,2),'Color','m','Tag','calib_points','LineStyle','none','Marker','+','MarkerSize',10);
1362elseif isempty(Coord)%empty list of points, suppress the plot
1363    delete(hh)
1364else
1365    set(hh,'XData',Coord_plot(:,1))
1366    set(hh,'YData',Coord_plot(:,2))
1367end
1368pause(.1)
1369figure(handles.geometry_calib)
1370
1371%------------------------------------------------------------------------
1372% --- Executes on button press in Copy: display Coord on the Matlab work space
1373%------------------------------------------------------------------------
1374function Copy_Callback(hObject, eventdata, handles)
1375global Coord
1376evalin('base','global Coord')%make CurData global in the workspace
1377Coord=get(handles.ListCoord,'Data');
1378display('coordinates of calibration points (phys,px,marker) :')
1379evalin('base','Coord') %display CurData in the workspace
1380commandwindow; %brings the Matlab command window to the front
1381
1382%------------------------------------------------------------------------
1383% --- Executes when selected cell(s) is changed in ListCoord.
1384%------------------------------------------------------------------------
1385function ListCoord_CellSelectionCallback(hObject, eventdata, handles)
1386if ~isempty(eventdata.Indices)
1387    iline=eventdata.Indices(1);% selected line number
1388    set(handles.CoordLine,'String',num2str(iline))
1389     Data=get(handles.ListCoord,'Data');
1390     update_calib_marker(Data(iline,:))
1391end
1392
1393%------------------------------------------------------------------------
1394% --- Executes when entered data in editable cell(s) in ListCoord.
1395%------------------------------------------------------------------------
1396function ListCoord_CellEditCallback(hObject, eventdata, handles)
1397
1398Input=str2num(eventdata.EditData);%pasted input
1399Coord=get(handles.ListCoord,'Data');
1400iline=eventdata.Indices(1);% selected line number
1401if size(Coord,1)<iline+numel(Input)
1402    Coord=[Coord ; zeros(iline+numel(Input)-size(Coord,1),6)];% append zeros to fit the new column
1403end
1404Coord(iline:iline+numel(Input)-1,eventdata.Indices(2))=Input';
1405set(handles.ListCoord,'Data',Coord)
1406PLOT_Callback(hObject, eventdata, handles)
1407
1408%------------------------------------------------------------------------
1409% --- 'key_press_fcn:' function activated when a key is pressed on the keyboard
1410%------------------------------------------------------------------------
1411function ListCoord_KeyPressFcn(hObject, eventdata, handles)
1412iline=str2num(get(handles.CoordLine,'String'));
1413xx=double(get(handles.geometry_calib,'CurrentCharacter'));%get the keyboard character
1414if ismember(xx,[28 29 30 31])% directional arrow
1415    Coord=get(handles.ListCoord,'Data');
1416    switch xx
1417        case 30 % arrow upward
1418            iline=iline-1;
1419        case 31% arrow downward
1420            iline=iline+1;
1421    end
1422    if iline>=1 && iline<=size(Coord,1)
1423        set(handles.CoordLine,'String',num2str(iline))
1424        update_calib_marker(Coord(iline,1:5))% show the point corresponding to the selected line
1425    end
1426else
1427    set(handles.APPLY,'BackgroundColor',[1 0 1])% paint APPLY in magenta to indicate that the table content has be modified
1428    if ismember(xx,[127 31])% delete, or downward
1429        Coord=get(handles.ListCoord,'Data');
1430        iline=str2double(get(handles.CoordLine,'String'));
1431        if isequal(xx, 31)
1432            if isequal(iline,size(Coord,1))% arrow downward
1433                Coord=[Coord;zeros(1,size(Coord,2))];
1434            end
1435        else
1436            Coord(iline,:)=[];% suppress the current line
1437        end
1438        set(handles.ListCoord,'Data',Coord);
1439    end
1440end
1441
1442%------------------------------------------------------------------------
1443% --- update the plot of calibration points
1444%------------------------------------------------------------------------
1445% draw a circle around the point defined by the input coordinates Coord as given by line in the table Listcoord
1446function update_calib_marker(Coord)
1447
1448%% read config on uvmat
1449huvmat=findobj(allchild(0),'Name','uvmat');%find the current uvmat interface handle
1450hhuvmat=guidata(huvmat);
1451hhh=findobj(hhuvmat.PlotAxes,'Tag','calib_marker');
1452if numel(Coord)<5
1453    if ~isempty(hhh)
1454        delete(hhh)%delete the circle marker in case of no valid input
1455    end
1456    return
1457end
1458menu=get(hhuvmat.TransformName,'String');
1459choice=get(hhuvmat.TransformName,'Value');
1460option='';
1461if iscell(menu)
1462    option=menu{choice};
1463end
1464
1465%% read appropriate coordinates (px or phys) in the table ListCoord
1466if isequal(option,'phys') % use phys coord
1467    XCoord=Coord(1);
1468    YCoord=Coord(2);
1469elseif isempty(option)% use coord in pixels
1470    XCoord=Coord(4);
1471    YCoord=Coord(5);
1472else
1473    msgbox_uvmat('ERROR','the choice in menu_coord of uvmat must be blank or phys ')
1474    return
1475end
1476
1477%% adjust the plot limits if needed
1478xlim=get(hhuvmat.PlotAxes,'XLim');
1479ylim=get(hhuvmat.PlotAxes,'YLim');
1480ind_range=max(abs(xlim(2)-xlim(1)),abs(ylim(end)-ylim(1)))/25;%defines the size of the circle marker
1481check_xlim=0;
1482if XCoord>xlim(2)
1483    xlim=xlim+XCoord-xlim(2)+ind_range;% translate plot limit
1484    check_xlim=1;
1485elseif XCoord<xlim(1)
1486    xlim=xlim-XCoord+xlim(1)-ind_range;% translate plot limit
1487    check_xlim=1;
1488end
1489if check_xlim
1490    set(hhuvmat.PlotAxes,'XLim',xlim);
1491    set(hhuvmat.num_MaxX,'String',num2str(xlim(2)));
1492    set(hhuvmat.num_MinX,'String',num2str(xlim(1)));
1493end
1494check_ylim=0;
1495if YCoord>ylim(2)
1496    ylim=ylim+YCoord-ylim(2)+ind_range;% translate plot limit
1497    check_ylim=1;
1498elseif YCoord<ylim(1)
1499    ylim=ylim-YCoord+ylim(1)-ind_range;% translate plot limit
1500    check_ylim=1;
1501end
1502if check_ylim
1503    set(hhuvmat.PlotAxes,'YLim',ylim);
1504    set(hhuvmat.num_MaxY,'String',num2str(ylim(2)));
1505    set(hhuvmat.num_MinY,'String',num2str(ylim(1)));
1506end
1507
1508%% plot a circle around the selected point
1509if isempty(hhh)
1510    set(0,'CurrentFig',huvmat)
1511    set(huvmat,'CurrentAxes',hhuvmat.PlotAxes)
1512    rectangle('Curvature',[1 1],...
1513        'Position',[XCoord-ind_range/2 YCoord-ind_range/2 ind_range ind_range],'EdgeColor','m',...
1514        'LineStyle','-','Tag','calib_marker');
1515else
1516    set(hhh,'Position',[XCoord-ind_range/2 YCoord-ind_range/2 ind_range ind_range])
1517end
1518
1519%------------------------------------------------------------------------
1520% --- Executes on button press in ClearPoint: remove the selected line in the table Coord
1521%------------------------------------------------------------------------
1522function ClearPoint_Callback(hObject, eventdata, handles)
1523
1524Coord=get(handles.ListCoord,'Data');
1525iline=str2num(get(handles.CoordLine,'String'));
1526if isempty(iline)
1527    msgbox_uvmat('WARNING','no line suppressed, select a line in the table')
1528else
1529    answer=msgbox_uvmat('INPUT_Y-N',['suppress line ' num2str(iline) '?']);
1530    if isequal(answer,'Yes')
1531        Coord(iline,:)=[];
1532        set(handles.APPLY,'BackgroundColor',[1 0 1])
1533        set(handles.ListCoord,'Data',Coord);
1534        set(handles.CoordLine,'String','')
1535        PLOT_Callback(hObject,eventdata,handles)
1536        update_calib_marker([]);%remove circle marker
1537    end
1538end
1539
1540
1541
Note: See TracBrowser for help on using the repository browser.