source: trunk/src/geometry_calib.m @ 1112

Last change on this file since 1112 was 1112, checked in by sommeria, 2 years ago

set_slice separated from geometrey_calib

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