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

Last change on this file since 455 was 455, checked in by sommeria, 12 years ago

a few bug corrected

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