source: trunk/src/geometry_calib.m @ 1062

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

bugs repaired, still problems with geometry_calib

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