source: trunk/src/series/sub_background.m @ 573

Last change on this file since 573 was 573, checked in by sommeria, 11 years ago

clean the head of the series fcts

File size: 20.8 KB
Line 
1%'sub_background': substract a sliding background to an image series
2%------------------------------------------------------------------------
3% Method:
4    %calculate the background image by sorting the luminosity of each point
5    % over a sliding sub-sequence of 'nbaver_ima' images.
6    % The luminosity value of rank 'rank' is selected as the
7    % 'background'. rank=nbimages/2 gives the median value.  Smaller values are appropriate
8    % for a dense set of particles. The extrem value rank=1 gives the true minimum
9    % luminosity, but it can be polluted by noise.
10% Organization of image indices:
11    % The program is working on a series of images,
12    % The processing can be done over groups of nbfield2 consecutive files in slices (parameter NbSlice)
13    % In the mode 'volume', nbfield2=1 (1 image at each level)and NbSlice (=nbfield_j)
14    % Else nbfield2=nbfield_j =nbre of images in a burst (j index)
15   
16% function GUI_config=sub_background(Param)
17%
18%%%%%%%%%%% GENERAL TO ALL SERIES ACTION FCTS %%%%%%%%%%%%%%%%%%%%%%%%%%%
19%
20% This function is used in four modes by the GUI series:
21%           1) config GUI: with no input argument, the function determine the suitable GUI configuration
22%           2) interactive input: the function is used to interactively introduce input parameters, and then stops
23%           3) RUN: the function itself runs, when an appropriate input  structure Param has been introduced.
24%           4) BATCH: the function itself proceeds in BATCH mode, using an xml file 'Param' as input.
25%
26%OUTPUT
27% GUI_series_config=list of options in the GUI series.fig needed for the function
28%
29%INPUT:
30% In run mode, the input parameters are given as a Matlab structure Param copied from the GUI series.
31% In batch mode, Param is the name of the corresponding xml file containing the same information
32% In the absence of input (as activated when the current Action is selected
33% in series), the function ouput GUI_series_config set the activation of the needed GUI elements
34%
35% Param contains the elements:(use the menu bar command 'export/GUI config' in series to see the current structure Param)
36%    .InputTable: cell of input file names, (several lines for multiple input)
37%                      each line decomposed as {RootPath,SubDir,Rootfile,NomType,Extension}
38%    .OutputSubDir: name of the subdirectory for data outputs
39%    .OutputDirExt: extension for the directory for data outputs
40%    .Action: .ActionName: name of the current activated function
41%             .ActionPath:   path of the current activated function
42%    .IndexRange: set the file or frame indices on which the action must be performed
43%    .FieldTransform: .TransformName: name of the selected transform function
44%                     .TransformPath:   path  of the selected transform function
45%                     .TransformHandle: corresponding function handle
46%    .InputFields: sub structure describing the input fields withfields
47%              .FieldName: name of the field
48%              .VelType: velocity type
49%              .FieldName_1: name of the second field in case of two input series
50%              .VelType_1: velocity type of the second field in case of two input series
51%    .ProjObject: %sub structure describing a projection object (read from ancillary GUI set_object)
52%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
53
54   
55function ParamOut=sub_background (Param)
56
57%% set the input elements needed on the GUI series when the action is selected in the menu ActionName
58if ~exist('Param','var') % case with no input parameter
59    ParamOut={'AllowInputSort';'off';...% allow alphabetic sorting of the list of input files (options 'off'/'on', 'off' by default)
60        'WholeIndexRange';'on';...% prescribes the file index ranges from min to max (options 'off'/'on', 'off' by default)
61        'NbSlice';'on'; ...%nbre of slices ('off' by default)
62        'VelType';'off';...% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
63        'FieldName';'off';...% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
64        'FieldTransform'; 'off';...%can use a transform function
65        'ProjObject';'off';...%can use projection object(option 'off'/'on',
66        'Mask';'off';...%can use mask option   (option 'off'/'on', 'off' by default)
67        'OutputDirExt';'.sback';...%set the output dir extension
68               ''};
69        return
70end
71
72%%%%%%%%%%%% STANDARD PART (DO NOT EDIT) %%%%%%%%%%%%
73%% select different modes,  RUN, parameter input, BATCH
74% BATCH  case: read the xml file for batch case
75if ischar(Param)
76        Param=xml2struct(Param);
77        checkrun=0;
78% RUN case: parameters introduced as the input structure Param
79else
80    hseries=guidata(Param.hseries);%handles of the GUI series
81    if isfield(Param,'Specific')&& strcmp(Param.Specific,'?')
82        checkrun=1;% will search input parameters (preparation of BATCH mode)
83    else
84        checkrun=2; % indicate the RUN option is used
85    end
86end
87ParamOut=Param; %default output
88OutputDir=[Param.OutputSubDir Param.OutputDirExt];
89
90%% root input file(s) and type
91RootPath=Param.InputTable(:,1);
92RootFile=Param.InputTable(:,3);
93SubDir=Param.InputTable(:,2);
94NomType=Param.InputTable(:,4);
95FileExt=Param.InputTable(:,5);
96[filecell,i1_series,i2_series,j1_series,j2_series]=get_file_series(Param);
97%%%%%%%%%%%%
98% The cell array filecell is the list of input file names, while
99% filecell{iview,fileindex}:
100%        iview: line in the table corresponding to a given file series
101%        fileindex: file index within  the file series,
102% 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
103% i1_series(iview,fileindex) expresses the same indices as a 1D array in file indices
104%%%%%%%%%%%%
105NbSlice=1;%default
106if isfield(Param.IndexRange,'NbSlice')&&~isempty(Param.IndexRange.NbSlice)
107    NbSlice=Param.IndexRange.NbSlice;
108end
109nbview=numel(i1_series);%number of input file series (lines in InputTable)
110nbfield_j=size(i1_series{1},1); %nb of fields for the j index (bursts or volume slices)
111nbfield_i=size(i1_series{1},2); %nb of fields for the i index
112nbfield=nbfield_j*nbfield_i; %total number of fields
113nbfield_i=floor(nbfield/NbSlice);%total number of  indexes in a slice (adjusted to an integer number of slices)
114nbfield=nbfield_i*NbSlice; %total number of fields after adjustement
115
116%determine the file type on each line from the first input file
117ImageTypeOptions={'image','multimage','mmreader','video'};%allowed input file types(images)
118
119[FileType{1},FileInfo{1},MovieObject{1}]=get_file_type(filecell{1,1});
120CheckImage{1}=~isempty(find(strcmp(FileType,ImageTypeOptions)));% =1 for images
121if ~isempty(j1_series{1})
122    frame_index{1}=j1_series{1};
123else
124    frame_index{1}=i1_series{1};
125end
126
127%% calibration data and timing: read the ImaDoc files
128%not relevant here
129
130%% check coincidence in time for several input file series
131%not relevant here
132
133%% coordinate transform or other user defined transform
134%not relevant here
135
136%%%%%%%%%%%% END STANDARD PART  %%%%%%%%%%%%
137 % EDIT FROM HERE
138
139 %% check the validity of  input file types
140if CheckImage{1}
141    FileExtOut='.png'; % write result as .png images for image inputs
142    if strcmp(lower(NomType{1}(end)),'a')
143        NomTypeOut=NomType{1};%case of letter appendix
144    elseif isempty(j1_series)
145        NomTypeOut='_1';
146    else
147        NomTypeOut='_1_1';% caseof purely numerical indexing
148    end
149else
150    msgbox_uvmat('ERROR',['invalid file type input: ' FileType{1} ' not an image'])
151    return
152end
153
154%% Set field names and velocity types
155%not relevant here
156
157%% Initiate output fields
158%not relevant here
159 
160%%% SPECIFIC PART BEGINS HERE
161NbSlice=Param.IndexRange.NbSlice; %number of slices
162%siz=size(i1_series);
163nbaver_init=23;%approximate number of images used for the sliding background: to be adjusted later to include an integer number of bursts
164j1=[];%default
165
166%% adjust the proposed number of images in the sliding average to include an integer number of bursts
167if nbfield_i~=1
168    nbaver=floor(nbaver_init/nbfield_j); % number of bursts used for the sliding background,
169    if isequal(floor(nbaver/2),nbaver)
170        nbaver=nbaver+1;%put the number of burst to an odd number (so the middle burst is defined)
171    end
172    nbaver_init=nbaver*nbfield_j;%propose by default an integer number of bursts
173end
174
175%% input of specific parameters
176if checkrun %get specific parameters interactively
177    prompt = {'volume scan mode (Yes/No)';'Number of images for the sliding background (MUST FIT IN COMPUTER MEMORY)';...
178        'the luminosity rank chosen to define the background (0.1=for dense particle seeding, 0.5 (median) for sparse particles'};
179    dlg_title = ['get (slice by slice) a sliding background and substract to each image, result in subdir ' OutputDir];
180    num_lines= 3;
181    def     = { 'No';num2str(nbaver_init);'0.1'};
182    answer = inputdlg(prompt,dlg_title,num_lines,def);
183   
184    %check input consistency
185    if strcmp(answer{1},'No') && ~isequal(NbSlice,1)
186        check=msgbox_uvmat('INPUT_Y-N',['confirm the multi-level splitting into ' num2str(NbSlice) ' slices']);
187        if ~strcmp(check,'Yes')
188            return
189        end
190    end
191    if strcmp(answer{1},'Yes')
192        step=1;
193    else
194        step=nbfield_j;%case of bursts: the sliding background is shifted by the length of one burst
195    end
196    nbaver_ima=str2num(answer{2});%number of images for the sliding background
197    nbaver=ceil(nbaver_ima/step);%number of bursts for the sliding background
198    if isequal(floor(nbaver/2),nbaver)
199        nbaver=nbaver+1;%set the number of bursts to an odd number (so the middle burst is defined)
200    end
201    nbaver_ima=nbaver*step;
202    if nbaver_ima > nbfield
203        msgbox_uvmat('ERROR','number of images in a slice smaller than the proposed number of images for the sliding average')
204        return
205    end
206    ParamOut.Specific.CheckVolume=strcmp(answer{1},'Yes');
207    ParamOut.Specific.SlidingSequenceSize=nbaver_ima;
208    ParamOut.Specific.BrightnessRankThreshold=str2num(answer{3});
209   
210    % apply the image rescaling function 'level' (avoid the blinking effects of bright particles)
211    answer=msgbox_uvmat('INPUT_Y-N','apply image rescaling function levels.m after sub_background');
212    ParamOut.Specific.CheckLevelTransform=strcmp(answer,'Yes');
213    if checkrun==1
214         return
215    end
216    %%%%%%%%%%%%%%%%%%%%%%  STOP HERE FOR PAMETER INPUT MODE  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
217else
218    if isequal(Param.Specific.CheckVolume,1)
219        step=1;
220    else
221        step=nbfield_j;%case of bursts: the sliding background is shifted by the length of one burst
222    end
223    nbaver_ima=Param.Specific.SlidingSequenceSize;%number of images for the sliding background
224    nbaver=ceil(nbaver_ima/step);%number of bursts for the sliding background
225    if isequal(floor(nbaver/2),nbaver)
226        nbaver=nbaver+1;%set the number of bursts to an odd number (so the middle burst is defined)
227    end
228    nbaver_ima=nbaver*step;
229    if nbaver_ima > nbfield
230        msgbox_uvmat('ERROR','number of images in a slice smaller than the proposed number of images for the sliding average')
231        return
232    end
233end
234
235% calculate absolute brightness rank
236rank=floor(ParamOut.Specific.BrightnessRankThreshold*nbaver_ima);
237if rank==0
238    rank=1;%rank selected in the sorted image series
239end
240
241%% prealocate memory for the sliding background
242try
243    Afirst=read_image(filecell{1,1},FileType{1},MovieObject{1},frame_index{1}(1));
244    [npy,npx]=size(Afirst);
245    if strcmp(class(Afirst),'uint8') % case of 8bit images
246        Ak=zeros(npy,npx,nbaver_ima,'uint8'); %prealocate memory
247        Asort=zeros(npy,npx,nbaver_ima,'uint8'); %prealocate memory
248    else
249        Ak=zeros(npy,npx,nbaver_ima,'uint16'); %prealocate memory
250        Asort=zeros(npy,npx,nbaver_ima,'uint16'); %prealocate memory
251    end
252catch ME
253    msgbox_uvmat('ERROR',ME.message)
254    return
255end
256
257%% update the xml file
258% SubDirBase=regexprep(Param.InputTable{1,2},'\..*','');%take the root part of SubDir, before the first dot '.'
259% filexml=fullfile(RootPath{1},[SubDirBase '.xml']);
260% if ~exist(filexml,'file') && exist([fullfile(RootPath{1},SubDir{1},RootFile{1}) '.xml'],'file')% xml inside the image directory
261%     copyfile([filebase '.xml'],filexml);% copy the .xml file
262% end
263% if exist(filexml,'file')
264%     t=xmltree(filexml); 
265%     %update information on the first image name in the series
266%     uid_Heading=find(t,'ImaDoc/Heading');
267%     if isempty(uid_Heading)
268%         [t,uid_Heading]=add(t,1,'element','Heading');
269%     end
270%     uid_ImageName=find(t,'ImaDoc/Heading/ImageName');
271%     if ~isempty(j1_series{1})
272%         j1=j1_series{1}(1);
273%     end
274%     ImageName=fullfile_uvmat([dir_images term],'',RootFile{1},'.png',NomType,i1_series(1,1),[],j1);
275%     [pth,ImageName]=fileparts(ImageName);
276%     ImageName=[ImageName '.png'];
277%     if isempty(uid_ImageName)
278%         [t,uid_ImageName]=add(t,uid_Heading,'element','ImageName');
279%     end
280%     uid_value=children(t,uid_ImageName);
281%     if isempty(uid_value)
282%         t=add(t,uid_ImageName,'chardata',ImageName);%indicate  name of the first image, with ;png extension
283%     else
284%         t=set(t,uid_value(1),'value',ImageName);%indicate  name of the first image, with ;png extension
285%     end
286%     
287%     %add information about image transform
288%     [t,new_uid]=add(t,1,'element','ImageTransform');
289%     [t,NameFunction_uid]=add(t,new_uid,'element','NameFunction');
290%     [t]=add(t,NameFunction_uid,'chardata','sub_background');
291%     if GUI_config.CheckLevel
292%         [t,NameFunction_uid]=add(t,new_uid,'element','NameFunction');
293%         [t]=add(t,NameFunction_uid,'chardata','levels');
294%     end
295%     [t,NbSlice_uid]=add(t,new_uid,'element','NbSlice');
296%     [t]=add(t,new_uid,'chardata',num2str(NbSlice));
297%     [t,NbSlidingImages_uid]=add(t,new_uid,'element','NbSlidingImages');
298%     [t]=add(t,NbSlidingImages_uid,'chardata',num2str(nbaver));
299%     [t,LuminosityRank_uid]=add(t,new_uid,'element','RankBackground');
300%     [t]=add(t,LuminosityRank_uid,'chardata',num2str(rank));% luminosity rank almong the nbaver sliding images
301%     save(t,filexml)
302% end
303%copy the mask
304% if exist([filebase '_1mask_1'],'file')
305%     copyfile([filebase '_1mask_1'],[filebase_b '_1mask_1']);% copy the mask file
306% end
307
308%MAIN LOOP ON SLICES
309for islice=1:NbSlice
310    %% select the series of image indices at the level islice
311    indselect=islice:NbSlice*step:nbfield;% select file indices of the slice
312    for ifield=1:step-1
313        indselect=[indselect;indselect(end,:)+1];
314    end
315   
316    %% read the first series of nbaver_ima images and sort by luminosity at each pixel
317    for ifield = 1:nbaver_ima
318        ifile=indselect(ifield);
319        filename=filecell{1,ifile};
320        Aread=read_image(filename,FileType{1},MovieObject{1},frame_index{1}(ifile));
321        if ndims(Aread)==3;%color images
322            Aread=sum(double(Aread),3);% take the sum of color components
323        end
324        Ak(:,:,ifield)=Aread;
325    end
326    Asort=sort(Ak,3);%sort the luminosity of images at each point
327    B=Asort(:,:,rank);%background image
328    display( 'first background image will be substracted')
329    nbfirst=(ceil(nbaver/2))*step;
330    for ifield=1:nbfirst
331        Acor=double(Ak(:,:,ifield))-double(B);%substract background to the current image
332        Acor=(Acor>0).*Acor; % put to 0 the negative elements in Acor
333        ifile=indselect(ifield);
334        if ~isempty(j1_series{1})
335            j1=j1_series{1}(ifile);
336        end
337        newname=fullfile_uvmat(RootPath{1},OutputDir,RootFile{1},FileExtOut,NomTypeOut,i1_series{1}(ifile),[],j1);
338       
339        %write result file
340        if ParamOut.Specific.CheckLevelTransform
341            C=levels(Acor);
342            imwrite(C,newname,'BitDepth',8); % save the new image
343        else
344            if isequal(FileInfo{1}.BitDepth,16)
345                C=uint16(Acor);
346                imwrite(C,newname,'BitDepth',16); % save the new image
347            else
348                C=uint8(Acor);
349                imwrite(C,newname,'BitDepth',8); % save the new image
350            end
351        end
352        display([newname ' written'])
353    end
354   
355    %% repeat the operation on a sliding series of images
356    display('sliding background image will be substracted')
357    if nbfield_i > nbaver_ima
358        for ifield = step*ceil(nbaver/2)+1:step:nbfield_i-step*floor(nbaver/2)
359            if checkrun
360                stopstate=get(hseries.RUN,'BusyAction');
361                update_waitbar(hseries.Waitbar,(ifield+(islice-1)*nbfield_i)/(nbfield_i*NbSlice))
362            else
363                stopstate='queue';
364            end
365            if isequal(stopstate,'queue')% enable STOP command
366                Ak(:,:,1:nbaver_ima-step)=Ak(:,:,1+step:nbaver_ima);% shift the current image series by one burst (step)
367                %incorporate next burst in the current image series
368                for iburst=1:step
369                    ifile=indselect(ifield+step*floor(nbaver/2)+iburst-1);
370                    filename=fullfile_uvmat(RootPath{1},SubDir{1},RootFile{1},FileExt{1},NomType{1},i1_series{1}(ifile),[],j1_series{1}(ifile));
371                    Aread=read_image(filename,FileType{1},MovieObject{1},i1_series{1}(ifile));
372                    if ndims(Aread)==3;%color images
373                        Aread=sum(double(Aread),3);% take the sum of color components
374                    end
375                    Ak(:,:,nbaver_ima-step+iburst)=Aread;
376                end
377                Asort=sort(Ak,3);%sort the new current image series by luminosity
378                B=Asort(:,:,rank);%current background image
379                for iburst=1:step
380                    index=step*floor(nbaver/2)+iburst;
381                    Acor=double(Ak(:,:,index))-double(B);
382                    Acor=(Acor>0).*Acor; % put to 0 the negative elements in Acor
383                    ifile=indselect(ifield+iburst-1);
384                    if ~isempty(j1_series{1})
385                        j1=j1_series{1}(ifile);
386                    end
387                    newname=fullfile_uvmat(RootPath{1},OutputDir,RootFile{1},FileExtOut,NomTypeOut,i1_series{1}(ifile),[],j1);
388                    %write result file
389                    if ParamOut.Specific.CheckLevelTransform
390                        C=levels(Acor);
391                        imwrite(C,newname,'BitDepth',8); % save the new image
392                    else
393                        if isequal(FileInfo{1}.BitDepth,16)
394                            C=uint16(Acor);
395                            imwrite(C,newname,'BitDepth',16); % save the new image
396                        else
397                            C=uint8(Acor);
398                            imwrite(C,newname,'BitDepth',8); % save the new image
399                        end
400                    end
401                    display([newname ' written'])
402                   
403                end
404            else
405                return
406            end
407        end
408    end
409   
410    %% substract the background from the last images
411    display('last background image will be substracted')
412    ifield=nbfield_i-(step*ceil(nbaver/2))+1:nbfield_i;
413    for ifield=nbfield_i-(step*floor(nbaver/2))+1:nbfield_i
414        index=ifield-nbfield_i+step*(2*floor(nbaver/2)+1);
415        Acor=double(Ak(:,:,index))-double(B);
416        Acor=(Acor>0).*Acor; % put to 0 the negative elements in Acor
417        ifile=indselect(ifield);
418        if ~isempty(j1_series{1})
419            j1=j1_series{1}(ifile);
420        end
421        newname=fullfile_uvmat(RootPath{1},OutputDir,RootFile{1},FileExtOut,NomTypeOut,i1_series{1}(ifile),[],j1);
422       
423        %write result file
424        if ParamOut.Specific.CheckLevelTransform
425            C=levels(Acor);
426            imwrite(C,newname,'BitDepth',8); % save the new image
427        else
428            if isequal(FileInfo{1}.BitDepth,16)
429                C=uint16(Acor);
430                imwrite(C,newname,'BitDepth',16); % save the new image
431            else
432                C=uint8(Acor);
433                imwrite(C,newname,'BitDepth',8); % save the new image
434            end
435        end
436        display([newname ' written'])
437    end
438end
439
440
441function C=levels(A)
442%whos A;
443B=double(A(:,:,1));
444windowsize=round(min(size(B,1),size(B,2))/20);
445windowsize=floor(windowsize/2)*2+1;
446ix=1/2-windowsize/2:-1/2+windowsize/2;%
447%del=np/3;
448%fct=exp(-(ix/del).^2);
449fct2=cos(ix/(windowsize-1)/2*pi/2);
450%Mfiltre=(ones(5,5)/5^2);
451%Mfiltre=fct2';
452Mfiltre=fct2'*fct2;
453Mfiltre=Mfiltre/(sum(sum(Mfiltre)));
454
455C=filter2(Mfiltre,B);
456C(:,1:windowsize)=C(:,windowsize)*ones(1,windowsize);
457C(:,end-windowsize+1:end)=C(:,end-windowsize+1)*ones(1,windowsize);
458C(1:windowsize,:)=ones(windowsize,1)*C(windowsize,:);
459C(end-windowsize+1:end,:)=ones(windowsize,1)*C(end-windowsize,:);
460C=tanh(B./(2*C));
461[n,c]=hist(reshape(C,1,[]),100);
462% figure;plot(c,n);
463
464[m,i]=max(n);
465c_max=c(i);
466[dummy,index]=sort(abs(c-c(i)));
467n=n(index);
468c=c(index);
469i_select = find(cumsum(n)<0.95*sum(n));
470if isempty(i_select)
471    i_select = 1:length(c);
472end
473c_select=c(i_select);
474n_select=n(i_select);
475cmin=min(c_select);
476cmax=max(c_select);
477C=(C-cmin)/(cmax-cmin)*256;
478C=uint8(C);
Note: See TracBrowser for help on using the repository browser.