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

Last change on this file since 903 was 887, checked in by sommeria, 10 years ago

comments on extract_rdvision suppressed

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