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

Last change on this file since 860 was 851, checked in by sommeria, 9 years ago

various

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