source: trunk/src/geometry_calib.m @ 1064

Last change on this file since 1064 was 1063, checked in by sommeria, 5 years ago

geometric calibration corrected

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