source: trunk/src/series/extract_rdvision.m @ 843

Last change on this file since 843 was 843, checked in by sommeria, 9 years ago
File size: 32.7 KB
Line 
1%'extract_rdvision': relabel an image series with two indices, and correct errors from the RDvision transfer program
2%------------------------------------------------------------------------
3% function ParamOut=extract_rdvision(Param)
4%------------------------------------------------------------------------
5%
6%%%%%%%%%%% GENERAL TO ALL SERIES ACTION FCTS %%%%%%%%%%%%%%%%%%%%%%%%%%%
7%
8%OUTPUT
9% ParamOut: sets options in the GUI series.fig needed for the function
10%
11%INPUT:
12% In run mode, the input parameters are given as a Matlab structure Param copied from the GUI series.
13% In batch mode, Param is the name of the corresponding xml file containing the same information
14% when Param.Action.RUN=0 (as activated when the current Action is selected
15% in series), the function ouput paramOut set the activation of the needed GUI elements
16%
17% Param contains the elements:(use the menu bar command 'export/GUI config' in series to
18% see the current structure Param)
19%    .InputTable: cell of input file names, (several lines for multiple input)
20%                      each line decomposed as {RootPath,SubDir,Rootfile,NomType,Extension}
21%    .OutputSubDir: name of the subdirectory for data outputs
22%    .OutputDirExt: directory extension for data outputs
23%    .Action: .ActionName: name of the current activated function
24%             .ActionPath:   path of the current activated function
25%             .ActionExt: fct extension ('.m', Matlab fct, '.sh', compiled   Matlab fct
26%             .RUN =0 for GUI input, =1 for function activation
27%             .RunMode='local','background', 'cluster': type of function  use
28%             
29%    .IndexRange: set the file or frame indices on which the action must be performed
30%    .FieldTransform: .TransformName: name of the selected transform function
31%                     .TransformPath:   path  of the selected transform function
32%    .InputFields: sub structure describing the input fields withfields
33%              .FieldName: name(s) of the field
34%              .VelType: velocity type
35%              .FieldName_1: name of the second field in case of two input series
36%              .VelType_1: velocity type of the second field in case of two input series
37%              .Coord_y: name of y coordinate variable
38%              .Coord_x: name of x coordinate variable
39%    .ProjObject: %sub structure describing a projection object (read from ancillary GUI set_object)
40%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
41
42%=======================================================================
43% Copyright 2008-2014, LEGI UMR 5519 / CNRS UJF G-INP, Grenoble, France
44%   http://www.legi.grenoble-inp.fr
45%   Joel.Sommeria - Joel.Sommeria (A) legi.cnrs.fr
46%
47%     This file is part of the toolbox UVMAT.
48%
49%     UVMAT is free software; you can redistribute it and/or modify
50%     it under the terms of the GNU General Public License as published
51%     by the Free Software Foundation; either version 2 of the license,
52%     or (at your option) any later version.
53%
54%     UVMAT is distributed in the hope that it will be useful,
55%     but WITHOUT ANY WARRANTY; without even the implied warranty of
56%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
57%     GNU General Public License (see LICENSE.txt) for more details.
58%=======================================================================
59
60function ParamOut=extract_rdvision(Param) %default output=relabel_i_j(Param)
61
62%% set the input elements needed on the GUI series when the action is selected in the menu ActionName
63if isstruct(Param) && isequal(Param.Action.RUN,0)
64    ParamOut.AllowInputSort='off';...% allow alphabetic sorting of the list of input file SubDir (options 'off'/'on', 'off' by default)
65    ParamOut.WholeIndexRange='on';...% prescribes the file index ranges from min to max (options 'off'/'on', 'off' by default)
66    ParamOut.NbSlice='one'; ...%nbre of slices, 'one' prevents splitting in several processes, ('off' by default)
67    ParamOut.VelType='off';...% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
68    ParamOut.FieldName='off';...% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
69    ParamOut.FieldTransform = 'off';...%can use a transform function
70    ParamOut.ProjObject='off';...%can use projection object(option 'off'/'on',
71    ParamOut.Mask='off';...%can use mask option   (option 'off'/'on', 'off' by default)
72    ParamOut.OutputSubDirMode='custom'; %output folder given by the program, not by the GUI series
73     % detect the set of image folder
74    RootPath=Param.InputTable{1,1};
75    ListStruct=dir(RootPath);   
76    ListCells=struct2cell(ListStruct);% transform dir struct to a cell arrray
77    check_bad=strcmp('.',ListCells(1,:))|strcmp('..',ListCells(1,:));%detect the dir '.' to exclude it
78    check_dir=cell2mat(ListCells(4,:));% =1 for directories, =0 for files
79    ListDir=ListCells(1,find(check_dir & ~check_bad));
80%     InputTable=cell(numel(ListDir),5);
81%     InputTable(:,2)=ListDir';
82    isel=0;
83    for ilist=1:numel(ListDir)
84        ListStructSub=dir(fullfile(RootPath,ListDir{ilist}));
85        ListCellSub=struct2cell(ListStructSub);% transform dir struct to a cell arrray
86        detect_seq=regexp(ListCellSub(1,:),'.seq$');
87        seq_index=find(~cellfun('isempty',detect_seq),1);
88        if ~isempty(seq_index)
89%             msgbox_uvmat('ERROR',['not seq file in ' ListDir{ilist} ': please check the input folders'])
90%         else
91           isel=isel+1;
92           InputTable{isel,1}=RootPath;
93           InputTable{isel,2}=ListDir{ilist};
94            RootFile=regexprep(ListCellSub{1,seq_index},'.seq$','');
95            InputTable{isel,3}=RootFile;
96        InputTable{isel,4}='*';
97        InputTable{isel,5}='.seq';
98    end
99    end
100    hseries=findobj(allchild(0),'Tag','series');% find the parent GUI 'series'
101    hhseries=guidata(hseries); %handles of the elements in 'series'
102    set(hhseries.InputTable,'Data',InputTable)
103    ParamOut.ActionInput.LogPath=RootPath;% indicate the path for the output info: 0_LOG ....
104return
105end
106
107ParamOut=[];
108%%%%%%%%%%%% STANDARD PART  %%%%%%%%%%%%
109%% read input parameters from an xml file if input is a file name (batch mode)
110checkrun=1;
111if ischar(Param)
112    Param=xml2struct(Param);% read Param as input file (batch case)
113    checkrun=0;
114end
115hseries=findobj(allchild(0),'Tag','series');
116RUNHandle=findobj(hseries,'Tag','RUN');%handle of RUN button in GUI series
117WaitbarHandle=findobj(hseries,'Tag','Waitbar');%handle of waitbar in GUI series
118
119%% root input file(s) and type
120RootPath=Param.InputTable{1,1};
121if ~isempty(find(~strcmp(RootPath,Param.InputTable(:,1))))% if the Rootpath for each camera are not identical
122    disp_uvmat('ERROR','Rootpath for all cameras must be identical',checkrun)
123    return
124end
125
126% get the set of input file names (cell array filecell), and the lists of
127% input file or frame indices i1_series,i2_series,j1_series,j2_series
128[filecell,i1_series,i2_series,j1_series,j2_series]=get_file_series(Param);
129
130%OutputDir=[Param.OutputSubDir Param.OutputDirExt];
131 
132% numbers of slices and file indices
133nbfield_j=size(i1_series{1},1); %nb of fields for the j index (bursts or volume slices)
134nbfield_i=size(i1_series{1},2); %nb of fields for the i index
135nbfield=nbfield_j*nbfield_i; %total number of fields
136
137%determine the file type on each line from the first input file
138
139FileInfo=get_file_info(filecell{1,1});
140if strcmp(FileInfo.FileType,'rdvision')
141    if ~isequal(FileInfo.NumberOfFrames,nbfield)
142        msgbox_uvmat('ERROR',['the whole series of ' num2str(FileInfo.NumberOfFrames) ' images must be extracted at once'])
143        %rmfield(OutputDir)
144        return
145    end
146    %% interactive input of specific parameters (for RDvision system)
147    display('converting images from RDvision system...')
148else
149    msgbox_uvmat('ERROR','the input is not from rdvision: a .seq or .sqb file must be opened')
150    return
151end
152t=xmltree;
153save(t,fullfile(RootPath,'Running.xml'))%create an xml file to indicate that processing takes place
154
155%% calibration data and timing: read the ImaDoc files
156mode=''; %default
157timecell={};
158itime=0;
159NbSlice_calib={};
160
161%SubDirBase=regexprep(SubDir{1},'\..*','');%take the root part of SubDir, before the first dot '.'
162
163%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
164%%%  loop on the cameras ( #iview)
165%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
166for iview=1:size(Param.InputTable,1)
167    filexml=[fullfile(RootPath,Param.InputTable{iview,3}) '.xml'];%new convention: xml at the level of the image folder
168    if ~exist(filexml,'file')
169        disp_uvmat('ERROR',[filexml ' missing'],checkrun)
170        return
171    end
172    [XmlData,error]=imadoc2struct_special(filexml);
173    if isfield(XmlData,'Time')
174        itime=itime+1;
175        timecell{itime}=XmlData.Time;
176    end
177    if isfield(XmlData,'GeometryCalib') && isfield(XmlData.GeometryCalib,'SliceCoord')
178        NbSlice_calib{1}=size(XmlData.GeometryCalib.SliceCoord,1);%nbre of slices for Zindex in phys transform
179        if ~isequal(NbSlice_calib{1},NbSlice_calib{1})
180            msgbox_uvmat('WARNING','inconsistent number of Z indices for the two field series');
181        end
182    end
183   
184   
185    % correction to RDvision xml file
186    t=xmltree(filexml);
187   
188    % correct Dtj and Dtk
189    NomTypeNew='_1_1';% new file nomencalture by default
190    ImageName='img_1_1.png';% first image name
191    if isfield(XmlData,'NbDtj')
192        uid_NbDtj=find(t,'ImaDoc/Camera/BurstTiming/NbDtj');
193        uid_value=children(t,uid_NbDtj);
194        if ~isempty(uid_value)
195            t=set(t,uid_value(1),'value',num2str(XmlData.NbDtj));
196        end
197    end
198    if isfield(XmlData,'NbDtk')
199        uid_NbDtk=find(t,'ImaDoc/Camera/BurstTiming/NbDtk');
200        uid_value=children(t,uid_NbDtk);
201        if ~isempty(uid_value)
202            t=set(t,uid_value(1),'value',num2str(XmlData.NbDtk));
203        end
204    end
205    if isempty(j1_series{1}) && isfield(XmlData,'NbDti')
206        uid_Dti=find(t,'ImaDoc/Camera/BurstTiming/Dti');
207        t=add(t,uid_Dti,'chardata',num2str(XmlData.Dti));
208        uid_NbDti=find(t,'ImaDoc/Camera/BurstTiming/NbDti');
209        t=add(t,uid_NbDti,'chardata',num2str(XmlData.NbDti));
210        uid_NbDtj=find(t,'ImaDoc/Camera/BurstTiming/NbDtj');
211        uid_NbDtk=find(t,'ImaDoc/Camera/BurstTiming/NbDtk');
212        t=delete(t,uid_NbDtj);
213        t=delete(t,uid_NbDtk);
214        uid_Dtj=find(t,'ImaDoc/Camera/BurstTiming/Dtj');
215        uid_Dtk=find(t,'ImaDoc/Camera/BurstTiming/Dtk');
216        t=delete(t,uid_Dtj);
217        t=delete(t,uid_Dtk);
218        NomTypeNew='_1';
219        ImageName='img_1.png';
220    end
221   
222    %update information of 'Heading'
223    uid_Heading=find(t,'ImaDoc/Heading');
224    if isempty(uid_Heading)
225        [t,uid_Heading]=add(t,1,'element','Heading');
226    end
227    uid_SubCampaign=find(t,'ImaDoc/Heading/SubCampaign');
228    if ~isempty(uid_SubCampaign), t=delete(t,uid_SubCampaign); end
229    uid_Experiment=find(t,'ImaDoc/Heading/Experiment');
230    if ~isempty(uid_Experiment), t=delete(t,uid_Experiment); end
231    uid_Device=find(t,'ImaDoc/Heading/Device');
232    if ~isempty(uid_Device), t=delete(t,uid_Device); end
233    uid_Record=find(t,'ImaDoc/Heading/Record');
234    if ~isempty(uid_Record), t=delete(t,uid_Record); end
235    uid_DateExp=find(t,'ImaDoc/Heading/DateExp');
236    if ~isempty(uid_DateExp), t=delete(t,uid_DateExp); end
237   
238    %indicate the name of the first image (as a check that the xml file is not moved)
239    uid_ImageName=find(t,'ImaDoc/Heading/ImageName');
240    if isempty(uid_ImageName)
241        [t,uid_ImageName]=add(t,uid_Heading,'element','ImageName');
242    end
243    uid_value=children(t,uid_ImageName);
244    if isempty(uid_value)
245        t=add(t,uid_ImageName,'chardata',ImageName);%indicate  name of the first image, with ;png extension
246    else
247        t=set(t,uid_value(1),'value',ImageName);%indicate  name of the first image, with ;png extension
248    end
249   
250    %indicate the date and time of the image acquisition start
251    % if isfield(FileInfo,'binrepertoire') && isfield(FileInfo,'starttime')
252    %     sep_pos=regexp(FileInfo.binrepertoire,'T');
253    %     DateTime=FileInfo.starttime;
254    %     if ~isempty(sep_pos)
255    %         DateTime=[FileInfo.binrepertoire(1:sep_pos-1) ' ' DateTime];
256    %     end
257    %     uid_DateTime=find(t,'ImaDoc/Heading/DateTime');
258    %     if isempty(uid_DateTime)
259    %         [t,uid_DateTime]=add(t,uid_Heading,'element','DateTime');
260    %     end
261    %     uid_value=children(t,uid_DateTime);
262    %     if isempty(uid_value)
263    %         t=add(t,uid_DateTime,'chardata',DateTime);%indicate  name of the first image, with ;png extension
264    %     else
265    %         t=set(t,uid_value(1),'value',DateTime);%indicate  name of the first image, with ;png extension
266    %     end
267    % end
268   
269    %% backup the previous xml file and save the corrected one
270%    [success,message]=copyfile(filexml,[filexml '~']);%make backup
271%     if success~=1
272%         disp(['errror in xml file backup: ' message]);
273%         return
274%     end
275    save(t,filexml)
276    nbfield2=1;
277    if isfield(XmlData,'Time')
278        nbfield2=size(XmlData.Time,2);
279    end
280   
281    %% get the names of .seq and .sqb files
282    switch Param.InputTable{iview,5}
283        case {'.seq','.sqb'}
284            filename_seq=fullfile(RootPath,Param.InputTable{iview,2},[Param.InputTable{iview,3} '.seq']);
285            filename_sqb=fullfile(RootPath,Param.InputTable{iview,2},[Param.InputTable{iview,3} '.sqb']);
286        otherwise
287            errormsg='input file extension must be .seq or .sqb';
288    end
289    if ~exist(filename_seq,'file')
290        errormsg=[filename_seq ' does not exist'];
291        return
292    end
293   
294    %% get data from .seq file
295    s=ini2struct(filename_seq);
296    SeqData=s.sequenceSettings;
297    SeqData.width=str2double(SeqData.width);
298    SeqData.height=str2double(SeqData.height);
299    SeqData.bytesperpixel=str2double(SeqData.bytesperpixel);
300    SeqData.nb_frames=str2double(s.sequenceSettings.numberoffiles);
301    if isempty(SeqData.binrepertoire)%used when binrepertoire empty, strange feature of rdvision
302        SeqData.binrepertoire=regexprep(s.sequenceSettings.bindirectory,'\\$','');%tranform Windows notation to Linux
303        SeqData.binrepertoire=regexprep(SeqData.binrepertoire,'\','/');
304        [tild,binrepertoire,DirExt]=fileparts(SeqData.binrepertoire);
305        SeqData.binrepertoire=[SeqData.binrepertoire DirExt];
306    end
307%     PathDir=fileparts(PathDir);
308   
309    %% reading the .sqb file
310    m = memmapfile(filename_sqb,'Format', { 'uint32' [1 1] 'offset'; ...
311        'uint32' [1 1] 'garbage1';...
312        'double' [1 1] 'timestamp';...
313        'uint32' [1 1] 'file_idx';...
314        'uint32' [1 1] 'garbage2' },'Repeat',SeqData.nb_frames);
315    %%%%%%%BRICOLAGE in case of unreadable .sqb file
316    %     ind=[60 63:152];%indices of bin files
317    %     lengthimage=w*h*bpp;% lengthof an image record on the binary file
318    %     for ii=1:32*numel(ind)
319    %         data(ii).offset=mod(ii-1,32)*2*lengthimage+lengthimage;%Dalsa_2
320    %         %data(ii).offset=mod(ii-1,32)*2*lengthimage;%Dalsa_1
321    %         data(ii).file_idx=ind(ceil(ii/32));
322    %         data(ii).timestamp=0.2*(ii-1);
323    %     end
324    %%%%%%%
325    for ii=1: numel(m.Data)
326        timestamp(ii)=m.Data(ii).timestamp;
327    end
328    timestamp %todo: check withDt from the xml file
329    [BinSize,errormsg]=binread_rdv_series(RootPath,SeqData,m.Data,nbfield2,NomTypeNew)
330    if ~isempty(errormsg)
331        disp_uvmat('ERROR',errormsg,checkrun)
332        return
333    end
334end
335delete(fullfile(RootPath,'Running.xml'))%delete the  xml file to indicate that processing is finished
336
337%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
338%--------- reads a series of bin files
339%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
340function [BinSize,errormsg]=binread_rdv_series(PathDir,SeqData,SqbData,nbfield2,NomTypeNew)
341% BINREAD_RDV Permet de lire les fichiers bin gᅵnᅵrᅵs par Hiris ᅵ partir du
342% fichier seq associᅵ.
343%   [IMGS,TIMESTAMPS,NB_FRAMES] = BINREAD_RDV(FILENAME,FRAME_IDX) lit
344%   l'image d'indice FRAME_IDX de la sï¿œquence FILENAME.
345%
346%   Entrï¿œes
347%   -------
348%   FILENAME  : Nom du fichier sï¿œquence (.seq).
349%   FRAME_IDX : Indice de l'image ï¿œ lire. Si FRAME_IDX vaut -1 alors la
350%   sï¿œquence est entiï¿œrement lue. Si FRAME_IDX est un tableau d'indices
351%   alors toutes les images d'incides correspondant sont lues. Si FRAME_IDX
352%   est un tableau vide alors aucune image n'est lue mais le nombre
353%   d'images et tous les timestamps sont renvoyï¿œs. Les indices commencent ï¿œ
354%   1 et se termines ï¿œ NB_FRAMES.
355%
356%   Sorties
357%   -------
358%   IMGS        : Images de sortie.
359%   TIMESTAMPS  : Timestaps des images lues.
360%   NB_FRAMES   : Nombres d'images dans la sï¿œquence.
361NbBinFile=0;
362BinSize=0;
363errormsg='';
364classname=sprintf('uint%d',SeqData.bytesperpixel*8);
365
366classname=['*' classname];
367BitDepth=8*SeqData.bytesperpixel;%needed to write images (8 or 16 bits)
368binrepertoire=fullfile(PathDir,SeqData.binrepertoire);
369OutputDir=fullfile(PathDir,SeqData.sequencename);
370if ~exist(OutputDir,'dir')
371    %     errormsg=[OutputDir ' already exist, delete it first'];
372    %     return
373    % end
374    [s,errormsg]=mkdir(OutputDir);
375   
376    if s==0
377        disp(errormsg)
378        return%not able to create new image dir
379    end
380end
381for ii=1:SeqData.nb_frames
382    j1=[];
383    if ~isequal(nbfield2,1)
384        j1=mod(ii-1,nbfield2)+1;
385    end
386    i1=floor((ii-1)/nbfield2)+1;
387    OutputFile=fullfile_uvmat(PathDir,SeqData.sequencename,'img','.png',NomTypeNew,i1,[],j1);% TODO: set NomTypeNew from SeqData.mode
388    fname=fullfile(binrepertoire,sprintf('%s%.5d.bin',SeqData.binfile,SqbData(ii).file_idx));
389    if exist(OutputFile,'file')
390        fid=0;
391    else
392        if fid==0 || ~strcmp(fname,fname_prev) % open the bin file if not in use
393            if fid~=0
394                fclose(fid);%close the previous bin file if relevant
395            end
396            [fid,msg]=fopen(fname,'rb');
397            if isequal(fid,-1)
398                disp(['error in opening ' fname ': ' msg])
399            else
400                disp([fname ' opened for reading'])
401            end
402            fseek(fid,SqbData(ii).offset,-1);%look at the right starting place in the bin file
403            NbBinFile=NbBinFile+1;%counter of binary files (for checking purpose)
404            BinSize(NbBinFile)=0;% strat counter for new bin file
405        else
406            %             fclose(fid);%close the previous bin file
407            %             fid=fopen(fname,'rb');% open the new bin file
408            fseek(fid,SqbData(ii).offset,-1);%look at the right starting place in the bin file
409        end
410        fname_prev=fname;
411        A=reshape(fread(fid,SeqData.width*SeqData.height,classname),SeqData.width,SeqData.height);%read the current image
412        A=A';
413        BinSize(NbBinFile)=BinSize(NbBinFile)+SeqData.width*SeqData.height*SeqData.bytesperpixel*8; %record bits read
414        try
415            imwrite(A,OutputFile,'BitDepth',BitDepth) % case of 16 bit images
416            disp([OutputFile ' written']);
417            % [s,errormsg] = fileattrib(OutputFile,'-w','a'); %set images to read only '-w' for all users ('a')
418            %         if ~s
419            % %             disp_uvmat('ERROR',errormsg,checkrun);
420            %             return
421            %         end
422        catch ME
423            errormsg=ME.message;
424            return
425        end
426    end
427end
428if fid~=0
429fclose(fid)
430end
431
432
433
434
435% for ifile=1:nbfield
436%             update_waitbar(WaitbarHandle,ifile/nbfield)
437%     if ~isempty(RUNHandle) && ~strcmp(get(RUNHandle,'BusyAction'),'queue')
438%         disp('program stopped by user')
439%         break
440%     end
441%     [A,FileInfo,timestamps]=read_rdvision(filename,ifile);
442%     if ifile==1
443%         classA=class(A);
444%         if strcmp(classA,'uint8')
445%             BitDepth=8;
446%         else
447%         BitDepth=16;
448%         end
449%     end
450%     j1=[];
451%     if ~isequal(nbfield2,1)
452%     j1=mod(ifile-1+first_label,nbfield2)+1;
453%     end
454%     i1=floor((ifile-1+first_label)/nbfield2)+1;
455%     OutputFile=fullfile_uvmat(RootPath{1},OutputDir,'img','.png',NomTypeNew,i1,[],j1);
456%     try
457%         imwrite(A,OutputFile,'BitDepth',BitDepth) % case of 16 bit images
458%     disp([OutputFile ' written']);
459%         [s,errormsg] = fileattrib(OutputFile,'-w','a'); %set images to read only '-w' for all users ('a')
460%         if ~s
461%             disp_uvmat('ERROR',errormsg,checkrun);
462%             return
463%         end
464%     catch ME
465%         disp_uvmat('ERROR',ME.message,checkrun);
466%         return
467%     end
468%
469% end
470
471%'imadoc2struct_special': reads the xml file for image documentation
472%------------------------------------------------------------------------
473% function [s,errormsg]=imadoc2struct_special(ImaDoc,option)
474%
475% OUTPUT:
476% s: structure representing ImaDoc
477%   s.Heading: information about the data hierarchical structure
478%   s.Time: matrix of times
479%   s.TimeUnit
480%  s.GeometryCalib: substructure containing the parameters for geometric calibration
481% errormsg: error message
482%
483% INPUT:
484% ImaDoc: full name of the xml input file with head key ImaDoc
485% option: ='GeometryCalib': read  the data of GeometryCalib, including source point coordinates
486
487function [s,errormsg]=imadoc2struct_special(ImaDoc,option)
488
489%% default input and output
490if ~exist('option','var')
491    option='*';
492end
493errormsg=[];%default
494s.Heading=[];%default
495s.Time=[]; %default
496s.TimeUnit=[]; %default
497s.GeometryCalib=[];
498tsai=[];%default
499
500%% opening the xml file
501if exist(ImaDoc,'file')~=2, errormsg=[ ImaDoc ' does not exist']; return;end;%input file does not exist
502try
503    t=xmltree(ImaDoc);
504catch
505    errormsg={[ImaDoc ' is not a valid xml file']; lasterr};
506    display(errormsg);
507    return
508end
509uid_root=find(t,'/ImaDoc');
510if isempty(uid_root), errormsg=[ImaDoc ' is not an image documentation file ImaDoc']; return; end;%not an ImaDoc .xml file
511
512
513%% Heading
514uid_Heading=find(t,'/ImaDoc/Heading');
515if ~isempty(uid_Heading),
516    uid_Campaign=find(t,'/ImaDoc/Heading/Campaign');
517    uid_Exp=find(t,'/ImaDoc/Heading/Experiment');
518    uid_Device=find(t,'/ImaDoc/Heading/Device');
519    uid_Record=find(t,'/ImaDoc/Heading/Record');
520    uid_FirstImage=find(t,'/ImaDoc/Heading/ImageName');
521    s.Heading.Campaign=get(t,children(t,uid_Campaign),'value');
522    s.Heading.Experiment=get(t,children(t,uid_Exp),'value');
523    s.Heading.Device=get(t,children(t,uid_Device),'value');
524    if ~isempty(uid_Record)
525        s.Heading.Record=get(t,children(t,uid_Record),'value');
526    end
527    s.Heading.ImageName=get(t,children(t,uid_FirstImage),'value');
528end
529
530%% Camera  and timing
531if strcmp(option,'*') || strcmp(option,'Camera')
532    uid_Camera=find(t,'/ImaDoc/Camera');
533    if ~isempty(uid_Camera)
534        uid_ImageSize=find(t,'/ImaDoc/Camera/ImageSize');
535        if ~isempty(uid_ImageSize);
536            ImageSize=get(t,children(t,uid_ImageSize),'value');
537            xindex=findstr(ImageSize,'x');
538            if length(xindex)>=2
539                s.Npx=str2double(ImageSize(1:xindex(1)-1));
540                s.Npy=str2double(ImageSize(xindex(1)+1:xindex(2)-1));
541            end
542        end
543        uid_TimeUnit=find(t,'/ImaDoc/Camera/TimeUnit');
544        if ~isempty(uid_TimeUnit)
545            s.TimeUnit=get(t,children(t,uid_TimeUnit),'value');
546        end
547        uid_BurstTiming=find(t,'/ImaDoc/Camera/BurstTiming');
548        if ~isempty(uid_BurstTiming)
549            for k=1:length(uid_BurstTiming)
550                subt=branch(t,uid_BurstTiming(k));%subtree under BurstTiming
551                % reading Dtk
552                Frequency=get_value(subt,'/BurstTiming/FrameFrequency',1);
553                Dtj=get_value(subt,'/BurstTiming/Dtj',[]);
554                Dtj=Dtj/Frequency;%Dtj converted from frame unit to TimeUnit (e.g. 's')
555                NbDtj=get_value(subt,'/BurstTiming/NbDtj',[]);
556                %%%% correction RDvision %%%%
557%                 NbDtj=NbDtj/numel(Dtj);
558%                 s.NbDtj=NbDtj;
559%                 %%%%
560                Dti=get_value(subt,'/BurstTiming/Dti',[]);
561                NbDti=get_value(subt,'/BurstTiming/NbDti',1);
562                 %%%% correction RDvision %%%%
563                if isempty(Dti)% series
564                     Dti=Dtj;
565                      NbDti=NbDtj;
566                     Dtj=[];
567                     s.Dti=Dti;
568                     s.NbDti=NbDti;
569                else
570                    % NbDtj=NbDtj/numel(Dtj);%bursts
571                    if ~isempty(NbDtj)
572                    s.NbDtj=NbDtj/numel(Dtj);%bursts;
573                    else
574                        s.NbDtj=1;
575                    end
576                end
577                %%%% %%%%
578                Dti=Dti/Frequency;%Dtj converted from frame unit to TimeUnit (e.g. 's')
579
580                Time_val=get_value(subt,'/BurstTiming/Time',0);%time in TimeUnit
581                if ~isempty(Dti)
582                    Dti=reshape(Dti'*ones(1,NbDti),NbDti*numel(Dti),1); %concatene Dti vector NbDti times
583                    Time_val=[Time_val;Time_val(end)+cumsum(Dti)];%append the times defined by the intervals  Dti
584                end
585                if ~isempty(Dtj)
586                    Dtj=reshape(Dtj'*ones(1,s.NbDtj),1,s.NbDtj*numel(Dtj)); %concatene Dtj vector NbDtj times
587                    Dtj=[0 Dtj];
588                    Time_val=Time_val*ones(1,numel(Dtj))+ones(numel(Time_val),1)*cumsum(Dtj);% produce a time matrix with Dtj
589                end
590                % reading Dtk
591                Dtk=get_value(subt,'/BurstTiming/Dtk',[]);
592                NbDtk=get_value(subt,'/BurstTiming/NbDtk',1);
593                %%%% correction RDvision %%%%
594                if ~isequal(NbDtk,1)
595                    NbDtk=-1+(NbDtk+1)/(NbDti+1);
596                end
597                s.NbDtk=NbDtk;
598                %%%%%
599                if isempty(Dtk)
600                    s.Time=[s.Time;Time_val];
601                else
602                    for kblock=1:NbDtk+1
603                        Time_val_k=Time_val+(kblock-1)*Dtk;
604                        s.Time=[s.Time;Time_val_k];
605                    end
606                end
607            end
608        end
609    end
610end
611
612%% motor
613if strcmp(option,'*') || strcmp(option,'GeometryCalib')
614    uid_subtree=find(t,'/ImaDoc/TranslationMotor');
615    if length(uid_subtree)==1
616        subt=branch(t,uid_subtree);%subtree under GeometryCalib
617       [s.TranslationMotor,errormsg]=read_subtree(subt,{'Nbslice','ZStart','ZEnd'},[1 1 1],[1 1 1]);
618    end
619end
620%%  geometric calibration
621if strcmp(option,'*') || strcmp(option,'GeometryCalib')
622    uid_GeometryCalib=find(t,'/ImaDoc/GeometryCalib');
623    if ~isempty(uid_GeometryCalib)
624        if length(uid_GeometryCalib)>1
625            errormsg=['More than one GeometryCalib in ' filecivxml];
626            return
627        end
628        subt=branch(t,uid_GeometryCalib);%subtree under GeometryCalib
629        cont=get(subt,1,'contents');
630        if ~isempty(cont)
631            uid_CalibrationType=find(subt,'/GeometryCalib/CalibrationType');
632            if isequal(length(uid_CalibrationType),1)
633                tsai.CalibrationType=get(subt,children(subt,uid_CalibrationType),'value');
634            end
635            uid_CoordUnit=find(subt,'/GeometryCalib/CoordUnit');
636            if isequal(length(uid_CoordUnit),1)
637                tsai.CoordUnit=get(subt,children(subt,uid_CoordUnit),'value');
638            end
639            uid_fx_fy=find(subt,'/GeometryCalib/fx_fy');
640            focal=[];%default fro old convention (Reg Wilson)
641            if isequal(length(uid_fx_fy),1)
642                tsai.fx_fy=str2num(get(subt,children(subt,uid_fx_fy),'value'));
643            else %old convention (Reg Wilson)
644                uid_focal=find(subt,'/GeometryCalib/focal');
645                uid_dpx_dpy=find(subt,'/GeometryCalib/dpx_dpy');
646                uid_sx=find(subt,'/GeometryCalib/sx');
647                if ~isempty(uid_focal) && ~isempty(uid_dpx_dpy) && ~isempty(uid_sx)
648                    dpx_dpy=str2num(get(subt,children(subt,uid_dpx_dpy),'value'));
649                    sx=str2num(get(subt,children(subt,uid_sx),'value'));
650                    focal=str2num(get(subt,children(subt,uid_focal),'value'));
651                    tsai.fx_fy(1)=sx*focal/dpx_dpy(1);
652                    tsai.fx_fy(2)=focal/dpx_dpy(2);
653                end
654            end
655            uid_Cx_Cy=find(subt,'/GeometryCalib/Cx_Cy');
656            if ~isempty(uid_Cx_Cy)
657                tsai.Cx_Cy=str2num(get(subt,children(subt,uid_Cx_Cy),'value'));
658            end
659            uid_kc=find(subt,'/GeometryCalib/kc');
660            if ~isempty(uid_kc)
661                tsai.kc=str2double(get(subt,children(subt,uid_kc),'value'));
662            else %old convention (Reg Wilson)
663                uid_kappa1=find(subt,'/GeometryCalib/kappa1');
664                if ~isempty(uid_kappa1)&& ~isempty(focal)
665                    kappa1=str2double(get(subt,children(subt,uid_kappa1),'value'));
666                    tsai.kc=-kappa1*focal*focal;
667                end
668            end
669            uid_Tx_Ty_Tz=find(subt,'/GeometryCalib/Tx_Ty_Tz');
670            if ~isempty(uid_Tx_Ty_Tz)
671                tsai.Tx_Ty_Tz=str2num(get(subt,children(subt,uid_Tx_Ty_Tz),'value'));
672            end
673            uid_R=find(subt,'/GeometryCalib/R');
674            if ~isempty(uid_R)
675                RR=get(subt,children(subt,uid_R),'value');
676                if length(RR)==3
677                    tsai.R=[str2num(RR{1});str2num(RR{2});str2num(RR{3})];
678                end
679            end
680           
681            %look for laser plane definitions
682            uid_Angle=find(subt,'/GeometryCalib/PlaneAngle');
683            uid_Pos=find(subt,'/GeometryCalib/SliceCoord');
684            if isempty(uid_Pos)
685                uid_Pos=find(subt,'/GeometryCalib/PlanePos');%old convention
686            end
687            if ~isempty(uid_Angle)
688                tsai.PlaneAngle=str2num(get(subt,children(subt,uid_Angle),'value'));
689            end
690            if ~isempty(uid_Pos)
691                for j=1:length(uid_Pos)
692                    tsai.SliceCoord(j,:)=str2num(get(subt,children(subt,uid_Pos(j)),'value'));
693                end
694                uid_DZ=find(subt,'/GeometryCalib/SliceDZ');
695                uid_NbSlice=find(subt,'/GeometryCalib/NbSlice');
696                if ~isempty(uid_DZ) && ~isempty(uid_NbSlice)
697                    DZ=str2double(get(subt,children(subt,uid_DZ),'value'));
698                    NbSlice=get(subt,children(subt,uid_NbSlice),'value');
699                    if isequal(NbSlice,'volume')
700                        tsai.NbSlice='volume';
701                        NbSlice=NbDtj+1;
702                    else
703                        tsai.NbSlice=str2double(NbSlice);
704                    end
705                    tsai.SliceCoord=ones(NbSlice,1)*tsai.SliceCoord+DZ*(0:NbSlice-1)'*[0 0 1];
706                end
707            end   
708            tsai.SliceAngle=get_value(subt,'/GeometryCalib/SliceAngle',[0 0 0]);
709            tsai.VolumeScan=get_value(subt,'/GeometryCalib/VolumeScan','n');
710            tsai.InterfaceCoord=get_value(subt,'/GeometryCalib/InterfaceCoord',[0 0 0]);
711            tsai.RefractionIndex=get_value(subt,'/GeometryCalib/RefractionIndex',1);
712           
713            if strcmp(option,'GeometryCalib')
714                tsai.PointCoord=get_value(subt,'/GeometryCalib/SourceCalib/PointCoord',[0 0 0 0 0]);
715            end
716            s.GeometryCalib=tsai;
717        end
718    end
719end
720
721%--------------------------------------------------
722%  read a subtree
723% INPUT:
724% t: xltree
725% head_element: head elelemnt of the subtree
726% Data, structure containing
727%    .Key: element name
728%    .Type: type of element ('charg', 'float'....)
729%    .NbOccur: nbre of occurrence, NaN for un specified number
730function [s,errormsg]=read_subtree(subt,Data,NbOccur,NumTest)
731%--------------------------------------------------
732s=[];%default
733errormsg='';
734head_element=get(subt,1,'name');
735    cont=get(subt,1,'contents');
736    if ~isempty(cont)
737        for ilist=1:length(Data)
738            uid_key=find(subt,[head_element '/' Data{ilist}]);
739            if ~isequal(length(uid_key),NbOccur(ilist))
740                errormsg=['wrong number of occurence for ' Data{ilist}];
741                return
742            end
743            for ival=1:length(uid_key)
744                val=get(subt,children(subt,uid_key(ival)),'value');
745                if ~NumTest(ilist)
746                    eval(['s.' Data{ilist} '=val;']);
747                else
748                    eval(['s.' Data{ilist} '=str2double(val);'])
749                end
750            end
751        end
752    end
753
754
755%--------------------------------------------------
756%  read an xml element
757function val=get_value(t,label,default)
758%--------------------------------------------------
759val=default;
760uid=find(t,label);%find the element iud(s)
761if ~isempty(uid) %if the element named label exists
762   uid_child=children(t,uid);%find the children
763   if ~isempty(uid_child)
764       data=get(t,uid_child,'type');%get the type of child
765       if iscell(data)% case of multiple element
766           for icell=1:numel(data)
767               val_read=str2num(get(t,uid_child(icell),'value'));
768               if ~isempty(val_read)
769                   val(icell,:)=val_read;
770               end
771           end
772%           val=val';
773       else % case of unique element value
774           val_read=str2num(get(t,uid_child,'value'));
775           if ~isempty(val_read)
776               val=val_read;
777           else
778              val=get(t,uid_child,'value');%char string data
779           end
780       end
781   end
782end
783
784
785
786
Note: See TracBrowser for help on using the repository browser.