source: trunk/src/geometry_calib.m @ 1150

Last change on this file since 1150 was 1150, checked in by sommeria, 4 months ago

browse_data improved

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