source: trunk/src/geometry_calib.m @ 1111

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

3D calibration corrected

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