source: trunk/src/series/usr_fct/merge_proj_images.m @ 984

Last change on this file since 984 was 984, checked in by sommeria, 4 years ago

introduce .cine in various functions, improve stero PIV

File size: 18.6 KB
Line 
1%'merge_proj': concatene several images from series, adjust their luminosity, can project them on a regular grid in phys coordinates
2%------------------------------------------------------------------------
3% function ParamOut=merge_proj(Param)
4%------------------------------------------------------------------------
5%%%%%%%%%%% GENERAL TO ALL SERIES ACTION FCTS %%%%%%%%%%%%%%%%%%%%%%%%%%%
6%
7%OUTPUT
8% ParamOut: sets options in the GUI series.fig needed for the function
9%
10%INPUT:
11% In run mode, the input parameters are given as a Matlab structure Param copied from the GUI series.
12% In batch mode, Param is the name of the corresponding xml file containing the same information
13% when Param.Action.RUN=0 (as activated when the current Action is selected
14% in series), the function ouput paramOut set the activation of the needed GUI elements
15%
16% Param contains the elements:(use the menu bar command 'export/GUI config' in series to
17% see the current structure Param)
18%    .InputTable: cell of input file names, (several lines for multiple input)
19%                      each line decomposed as {RootPath,SubDir,Rootfile,NomType,Extension}
20%    .OutputSubDir: name of the subdirectory for data outputs
21%    .OutputDirExt: directory extension for data outputs
22%    .Action: .ActionName: name of the current activated function
23%             .ActionPath:   path of the current activated function
24%             .ActionExt: fct extension ('.m', Matlab fct, '.sh', compiled   Matlab fct
25%             .RUN =0 for GUI input, =1 for function activation
26%             .RunMode='local','background', 'cluster': type of function  use
27%             
28%    .IndexRange: set the file or frame indices on which the action must be performed
29%    .FieldTransform: .TransformName: name of the selected transform function
30%                     .TransformPath:   path  of the selected transform function
31%    .InputFields: sub structure describing the input fields withfields
32%              .FieldName: name(s) of the field
33%              .VelType: velocity type
34%              .FieldName_1: name of the second field in case of two input series
35%              .VelType_1: velocity type of the second field in case of two input series
36%              .Coord_y: name of y coordinate variable
37%              .Coord_x: name of x coordinate variable
38%    .ProjObject: %sub structure describing a projection object (read from ancillary GUI set_object)
39%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
40
41%=======================================================================
42% Copyright 2008-2017, LEGI UMR 5519 / CNRS UGA G-INP, Grenoble, France
43%   http://www.legi.grenoble-inp.fr
44%   Joel.Sommeria - Joel.Sommeria (A) legi.cnrs.fr
45%
46%     This file is part of the toolbox UVMAT.
47%
48%     UVMAT is free software; you can redistribute it and/or modify
49%     it under the terms of the GNU General Public License as published
50%     by the Free Software Foundation; either version 2 of the license,
51%     or (at your option) any later version.
52%
53%     UVMAT is distributed in the hope that it will be useful,
54%     but WITHOUT ANY WARRANTY; without even the implied warranty of
55%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
56%     GNU General Public License (see LICENSE.txt) for more details.
57%=======================================================================
58
59function ParamOut=merge_proj(Param)
60
61%% set the input elements needed on the GUI series when the function is selected in the menu ActionName or InputTable refreshed
62ImageTypeOptions={'image','multimage','mmreader','video','cine_phantom'};
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='off';% prescribes the file index ranges from min to max (options 'off'/'on', 'off' by default)
66    ParamOut.NbSlice='off'; %nbre of slices ('off' by default)
67    ParamOut.VelType='one';% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
68    ParamOut.FieldName='one';% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
69    ParamOut.FieldTransform = 'on';%can use a transform function
70    ParamOut.TransformPath=fullfile(fileparts(which('uvmat')),'transform_field');% path to transform functions (needed for compilation only)
71    ParamOut.ProjObject='on';%can use projection object(option 'off'/'on',
72    ParamOut.Mask='on';%can use mask option   (option 'off'/'on', 'off' by default)
73    ParamOut.OutputDirExt='.mproj';%set the output dir extension
74    ParamOut.OutputFileMode='NbInput';% '=NbInput': 1 output file per input file index, '=NbInput_i': 1 file per input file index i, '=NbSlice': 1 file per slice
75    first_j=[];
76    if isequal(size(Param.InputTable,1),1) && ~isfield(Param,'ProjObject')
77        msgbox_uvmat('WARNING','You need a projection object of type plane for merge_proj')
78    end
79    if isfield(Param.IndexRange,'first_j'); first_j=Param.IndexRange.first_j; end
80    PairString='';
81    if isfield(Param.IndexRange,'PairString'); PairString=Param.IndexRange.PairString; end
82    [i1,i2,j1,j2] = get_file_index(Param.IndexRange.first_i,first_j,PairString);
83   
84    for iview=1:size(Param.InputTable,1)
85        FirstFileName=fullfile_uvmat(Param.InputTable{iview,1},Param.InputTable{iview,2},Param.InputTable{iview,3},...
86            Param.InputTable{iview,5},Param.InputTable{iview,4},i1,i2,j1,j2);
87        if ~exist(FirstFileName,'file')
88            msgbox_uvmat('WARNING',['the first input file ' FirstFileName ' does not exist'])
89        end
90        FileInfo=get_file_info(FirstFileName);
91        CheckImage=~isempty(find(strcmp(FileInfo.FileType,ImageTypeOptions)));% =1 for images
92        if ~CheckImage
93            msgbox_uvmat('WARNING',['the input file ' FirstFileName ' is not an image'])
94        end
95    end
96    return
97end
98
99%%%%%%%%%%%% STANDARD PART (DO NOT EDIT) %%%%%%%%%%%%
100ParamOut=[]; %default output
101%% read input parameters from an xml file if input is a file name (batch mode)
102checkrun=1;
103if ischar(Param)
104    Param=xml2struct(Param);% read Param as input file (batch case)
105    checkrun=0;
106end
107hseries=findobj(allchild(0),'Tag','series');
108RUNHandle=findobj(hseries,'Tag','RUN');%handle of RUN button in GUI series
109WaitbarHandle=findobj(hseries,'Tag','Waitbar');%handle of waitbar in GUI series
110
111%% define the directory for result file (with path=RootPath{1})
112OutputDir=[Param.OutputSubDir Param.OutputDirExt];% subdirectory for output files
113
114if ~isfield(Param,'InputFields')
115    Param.InputFields.FieldName='';
116end
117
118%% root input file type
119RootPath=Param.InputTable(:,1);
120RootFile=Param.InputTable(:,3);
121SubDir=Param.InputTable(:,2);
122NomType=Param.InputTable(:,4);
123FileExt=Param.InputTable(:,5);
124[filecell,i1_series,i2_series,j1_series,j2_series]=get_file_series(Param);
125%%%%%%%%%%%%
126% The cell array filecell is the list of input file names, while
127% filecell{iview,fileindex}:
128%        iview: line in the table corresponding to a given file series
129%        fileindex: file index within  the file series,
130% i1_series(iview,ref_j,ref_i)... are the corresponding arrays of indices i1,i2,j1,j2, depending on the input line iview and the two reference indices ref_i,ref_j
131% i1_series(iview,fileindex) expresses the same indices as a 1D array in file indices
132%%%%%%%%%%%%
133% NbSlice=1;%default
134% if isfield(Param.IndexRange,'NbSlice')&&~isempty(Param.IndexRange.NbSlice)
135%     NbSlice=Param.IndexRange.NbSlice;
136% end
137NbView=numel(i1_series);%number of input file series (lines in InputTable)
138NbField_j=size(i1_series{1},1); %nb of fields for the j index (bursts or volume slices)
139NbField_i=size(i1_series{1},2); %nb of fields for the i index
140NbField=NbField_j*NbField_i; %total number of fields
141
142%% determine the file type on each line from the first input file
143ImageTypeOptions={'image','multimage','mmreader','video','cine_phantom'};
144NcTypeOptions={'netcdf','civx','civdata'};
145for iview=1:NbView
146    if ~exist(filecell{iview,1}','file')
147        disp_uvmat('ERROR',['the first input file ' filecell{iview,1} ' does not exist'],checkrun)
148        return
149    end
150    [FileInfo{iview},MovieObject{iview}]=get_file_info(filecell{iview,1});
151    FileType{iview}=FileInfo{iview}.FileType;
152    CheckImage{iview}=~isempty(find(strcmp(FileType{iview},ImageTypeOptions)));% =1 for images
153   
154    if ~isempty(j1_series{iview})
155        frame_index{iview}=j1_series{iview};
156    else
157        frame_index{iview}=i1_series{iview};
158    end
159end
160
161%% calibration data and timing: read the ImaDoc files
162[XmlData,NbSlice_calib,time,errormsg]=read_multimadoc(RootPath,SubDir,RootFile,FileExt,i1_series,i2_series,j1_series,j2_series);
163if size(time,1)>1
164    diff_time=max(max(diff(time)));
165    if diff_time>0
166        disp_uvmat('WARNING',['times of series differ by (max) ' num2str(diff_time) ': the mean time is chosen in result'],checkrun)
167    end
168end
169if ~isempty(errormsg)
170    disp_uvmat('WARNING',errormsg,checkrun)
171end
172time=mean(time,1); %averaged time taken for the merged field
173
174%% coordinate transform or other user defined transform
175transform_fct='';%default fct handle
176if isfield(Param,'FieldTransform')&&~isempty(Param.FieldTransform.TransformName)
177    currentdir=pwd;
178    cd(Param.FieldTransform.TransformPath)
179    transform_fct=str2func(Param.FieldTransform.TransformName);
180    cd (currentdir)
181end
182
183%% output file type (8 bits)
184
185FileExtOut='.png'; %image output (input and proj result = image)
186% for iview=1:NbView
187%     BitDepth(iview)=FileInfo{iview}.BitDepth;
188% end
189% BitDepth=max(BitDepth);
190BitDepth=8;
191
192NomTypeOut=NomType;% output file index will indicate the first and last ref index in the series
193RootFileOut=RootFile{1};
194for iview=2:NbView
195    if ~strcmp(RootFile{iview},RootFile{1})
196        RootFileOut='mproj';
197        break
198    end
199end
200
201%% mask
202MaskData=cell(NbView,1);
203if Param.CheckMask
204    if ischar(Param.MaskTable)% case of a single mask (char chain)
205        Param.MaskTable={Param.MaskTable};
206    end
207    for iview=1:numel(Param.MaskTable)
208        if exist(Param.MaskTable{iview},'file')
209            [MaskData{iview},tild,errormsg] = read_field(Param.MaskTable{iview},'image');
210            if ~isempty(transform_fct) && nargin(transform_fct)>=2
211                MaskData{iview}=transform_fct(MaskData{iview},XmlData{iview});
212            end
213        end
214    end
215end
216
217%% Set field names and velocity types
218%use Param.InputFields for all views
219
220%% MAIN LOOP ON FIELDS
221%%%%%%%%%%%%% STANDARD PART (DO NOT EDIT) %%%%%%%%%%%%
222% for i_slice=1:NbSlice
223%     index_slice=i_slice:NbSlice:NbField;% select file indices of the slice
224%     NbFiles=0;
225%     nbmissing=0;
226
227%%%%%%%%%%%%%%%% loop on field indices %%%%%%%%%%%%%%%%
228for index=1:NbField
229    update_waitbar(WaitbarHandle,index/NbField)
230    if ~isempty(RUNHandle) && ~strcmp(get(RUNHandle,'BusyAction'),'queue')
231        disp('program stopped by user')
232        return
233    end
234   
235    %%%%%%%%%%%%%%%% loop on views (input lines) %%%%%%%%%%%%%%%%
236    Data=cell(1,NbView);%initiate the set Data
237    timeread=zeros(1,NbView);
238    for iview=1:NbView
239        %% reading input file(s)
240        [Data{iview},tild,errormsg] = read_field(filecell{iview,index},FileType{iview},Param.InputFields,frame_index{iview}(index));
241        if ~isempty(errormsg)
242            disp(['ERROR in merge_proj/read_field/' errormsg])
243            return
244        end
245        % get the time defined in the current file if not already defined from the xml file
246        if ~isempty(time) && isfield(Data{iview},'Time')
247            timeread(iview)=Data{iview}.Time;
248        end
249        if ~isempty(NbSlice_calib)
250            Data{iview}.ZIndex=mod(i1_series{iview}(index)-1,NbSlice_calib{iview})+1;%Zindex for phys transform
251        end
252       
253        %% transform the input field (e.g; phys) if requested (no transform involving two input fields)
254        if ~isempty(transform_fct)
255            if nargin(transform_fct)>=2
256                Data{iview}=transform_fct(Data{iview},XmlData{iview});
257            else
258                Data{iview}=transform_fct(Data{iview});
259            end
260        end
261       
262        %% CUSTOM ADJUSTMENT OF LUMINOSITY ANDCONTRAST%%%%%%%%%%%
263        if iview==1
264        Data{iview}.A=Data{iview}.A-100; %remove offset on Dalsa1
265        else
266        Data{iview}.A=Data{iview}.A-60; %remove offset on Dalsa2
267        Data{iview}.A=Data{iview}.A*3;%adjust luminosity of Dalsa2
268        Data{iview}.A=filter2(ones(2,2)/4,Data{iview}.A); %filter image Dalsa2 to fit with the projection grid resolution
269        end
270       
271        %% projection on object (gridded plane)
272        if Param.CheckObject
273            [Data{iview},errormsg]=proj_field(Data{iview},Param.ProjObject);
274            if ~isempty(errormsg)
275                disp(['ERROR in merge_proge/proj_field: ' errormsg])
276                return
277            end
278        end
279       
280        %% mask
281        if Param.CheckMask && ~isempty(MaskData{iview})
282            [Data{iview},errormsg]=mask_proj(Data{iview},MaskData{iview});
283        end
284    end
285    %%%%%%%%%%%%%%%% END LOOP ON VIEWS %%%%%%%%%%%%%%%%
286   
287    %% merge the NbView fields
288    MergeData=merge_field(Data);
289    if isfield(MergeData,'Txt')
290        disp(MergeData.Txt);
291        return
292    end
293   
294    %% time of the merged field: take the average of the different views
295    if ~isempty(time)
296        timeread=time(index);
297    elseif ~isempty(find(timeread))% time defined from ImaDoc
298        timeread=mean(timeread(timeread~=0));% take average over times form the files (when defined)
299    else
300        timeread=index;% take time=file index
301    end
302   
303    %% generating the name of the merged field
304    i1=i1_series{1}(index);
305    if ~isempty(i2_series{end})
306        i2=i2_series{end}(index);
307    else
308        i2=i1;
309    end
310    j1=1;
311    j2=1;
312    if ~isempty(j1_series{1})
313        j1=j1_series{1}(index);
314        if ~isempty(j2_series{end})
315            j2=j2_series{end}(index);
316        else
317            j2=j1;
318        end
319    end
320    OutputFile=fullfile_uvmat(RootPath{1},OutputDir,RootFileOut,FileExtOut,NomType{1},i1,i2,j1,j2);
321   
322    %% recording the merged field
323   
324    if BitDepth==8
325        imwrite(uint8(MergeData.A),OutputFile,'BitDepth',8)
326    else
327        imwrite(uint16(MergeData.A),OutputFile,'BitDepth',16)
328    end
329    if index==1
330        %write xml calibration file, using the first file
331        siz=size(MergeData.A);
332        npy=siz(1);
333        npx=siz(2);
334        if isfield(MergeData,'coord_x') && isfield(MergeData,'coord_y')
335            Rangx=MergeData.coord_x;
336            Rangy=MergeData.coord_y;
337        elseif isfield(MergeData,'AX')&& isfield(MergeData,'AY')
338            Rangx=[MergeData.AX(1) MergeData.AX(end)];
339            Rangy=[MergeData.AY(1) MergeData.AY(end)];
340        else
341            Rangx=[0.5 npx-0.5];
342            Rangy=[npy-0.5 0.5];%default
343        end
344        pxcmx=(npx-1)/(Rangx(2)-Rangx(1));
345        pxcmy=(npy-1)/(Rangy(1)-Rangy(2));
346        T_x=-pxcmx*Rangx(1)+0.5;
347        T_y=-pxcmy*Rangy(2)+0.5;
348        GeometryCal.CalibrationType='rescale';
349        GeometryCal.CoordUnit=MergeData.CoordUnit;
350        GeometryCal.focal=1;
351        GeometryCal.R=[pxcmx,0,0;0,pxcmy,0;0,0,1];
352        GeometryCal.Tx_Ty_Tz=[T_x T_y 1];
353        ImaDoc.GeometryCalib=GeometryCal;
354        t=struct2xml(ImaDoc);
355        t=set(t,1,'name','ImaDoc');
356        save(t,[fileparts(OutputFile) '.xml'])
357    end
358end   
359
360
361
362%'merge_field': concatene fields
363%------------------------------------------------------------------------
364function [MergeData,errormsg]=merge_field(Data)
365%% default output
366if isempty(Data)||~iscell(Data)
367    MergeData=[];
368    return
369end
370errormsg='';
371MergeData=Data{1};% merged field= first field by default, reproduces the glabal attributes of the first field
372NbView=length(Data);
373if NbView==1
374    return
375end
376
377%% group the variables (fields of 'Data') in cells of variables with the same dimensions
378[CellInfo,NbDim,errormsg]=find_field_cells(Data{1});
379if ~isempty(errormsg)
380    return
381end
382
383%LOOP ON GROUPS OF VARIABLES SHARING THE SAME DIMENSIONS
384for icell=1:length(CellInfo)
385    if NbDim(icell)~=1 % skip field cells which are of dim 1
386        switch CellInfo{icell}.CoordType
387            case 'scattered'  %case of input fields with unstructured coordinates: just concacene data
388                for ivar=CellInfo{icell}.VarIndex %  indices of the selected variables in the list FieldData.ListVarName
389                    VarName=Data{1}.ListVarName{ivar};
390                    %MergeData=Data{1};% merged field= first field by default, reproduces the glabal attributes of the first field
391                    for iview=2:NbView
392                        MergeData.(VarName)=[MergeData.(VarName); Data{iview}.(VarName)];
393                    end
394                end
395            case 'grid'        %case of fields defined on a structured  grid
396                FFName='';
397                if isfield(CellInfo{icell},'VarIndex_errorflag') && ~isempty(CellInfo{icell}.VarIndex_errorflag)
398                    FFName=Data{1}.ListVarName{CellInfo{icell}.VarIndex_errorflag};% name of errorflag variable
399                end
400                % select good data on each view
401                for ivar=CellInfo{icell}.VarIndex  %  indices of the selected variables in the list FieldData.ListVarName
402                    VarName=Data{1}.ListVarName{ivar};
403                    for iview=1:NbView
404                        if isempty(FFName)
405                            check_bad=isnan(Data{iview}.(VarName));%=0 for NaN data values, 1 else
406                        else
407                            check_bad=isnan(Data{iview}.(VarName)) | Data{iview}.(FFName)~=0;%=0 for NaN or error flagged data values, 1 else
408                        end
409                        Data{iview}.(VarName)(check_bad)=0; %set to zero NaN or masked data
410                        if iview==1
411                            MergeData.(VarName)=Data{1}.(VarName);% correct the field of MergeData
412                            NbAver=~check_bad;% initiate NbAver: the nbre of good data for each point
413                        elseif size(Data{iview}.(VarName))~=size(MergeData.(VarName))
414                            errormsg='sizes of the input matrices do not agree, need to interpolate on a common grid using a projection object';
415                            return
416                        else                     
417                            MergeData.(VarName)=MergeData.(VarName) + Data{iview}.(VarName);%add data
418                            NbAver=NbAver + ~check_bad;% add 1 for good data, 0 else
419                        end
420                    end
421                    MergeData.(VarName)(NbAver~=0)=MergeData.(VarName)(NbAver~=0)./NbAver(NbAver~=0);% take average of defined data at each point
422                end
423        end
424        if isempty(FFName)
425            FFName='FF';
426        end
427        MergeData.(FFName)(NbAver~=0)=0;% flag to 1 undefined summed data
428        MergeData.(FFName)(NbAver==0)=1;% flag to 1 undefined summed data
429    end
430end
431
432
433
434   
Note: See TracBrowser for help on using the repository browser.