source: trunk/src/geometry_calib.m @ 1151

Last change on this file since 1151 was 1151, checked in by sommeria, 8 months ago

civ_3D updated

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