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

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

bug corrected in sub_background. test_patch1 introduced in civ_series

File size: 19.5 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    % In the mode 'volume', nbfield2=1 (1 image at each level)and NbSlice (=nbfield_j)
13    % Else nbfield2=nbfield_j =nbre of images in a burst (j index)
14   
15% function GUI_config=sub_background(Param)
16%
17%%%%%%%%%%% GENERAL TO ALL SERIES ACTION FCTS %%%%%%%%%%%%%%%%%%%%%%%%%%%
18%
19%OUTPUT
20% ParamOut: sets 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% when Param.Action.RUN=0 (as activated when the current Action is selected
26% in series), the function ouput paramOut 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
29% see the current structure Param)
30%    .InputTable: cell of input file names, (several lines for multiple input)
31%                      each line decomposed as {RootPath,SubDir,Rootfile,NomType,Extension}
32%    .OutputSubDir: name of the subdirectory for data outputs
33%    .OutputDirExt: directory extension for data outputs
34%    .Action: .ActionName: name of the current activated function
35%             .ActionPath:   path of the current activated function
36%             .ActionExt: fct extension ('.m', Matlab fct, '.sh', compiled   Matlab fct
37%             .RUN =0 for GUI input, =1 for function activation
38%             .RunMode='local','background', 'cluster': type of function  use
39%             
40%    .IndexRange: set the file or frame indices on which the action must be performed
41%    .FieldTransform: .TransformName: name of the selected transform function
42%                     .TransformPath:   path  of the selected transform function
43%    .InputFields: sub structure describing the input fields withfields
44%              .FieldName: name(s) of the field
45%              .VelType: velocity type
46%              .FieldName_1: name of the second field in case of two input series
47%              .VelType_1: velocity type of the second field in case of two input series
48%              .Coord_y: name of y coordinate variable
49%              .Coord_x: name of x coordinate variable
50%    .ProjObject: %sub structure describing a projection object (read from ancillary GUI set_object)
51%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
52   
53function ParamOut=sub_background (Param)
54
55%%%%%%%%%%%%%%%%%    INPUT PREPARATION MODE (no RUN)    %%%%%%%%%%%%%%%%%
56if isstruct(Param) && isequal(Param.Action.RUN,0)
57    ParamOut.AllowInputSort='off';% allow alphabetic sorting of the list of input file SubDir (options 'off'/'on', 'off' by default)
58    ParamOut.WholeIndexRange='on';% prescribes the file index ranges from min to max (options 'off'/'on', 'off' by default)
59    ParamOut.NbSlice='on'; %nbre of slices ('off' by default)
60    ParamOut.VelType='off';% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
61    ParamOut.FieldName='off';% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
62    ParamOut.FieldTransform = 'off';%can use a transform function
63    ParamOut.ProjObject='off';%can use projection object(option 'off'/'on',
64    ParamOut.Mask='off';%can use mask option   (option 'off'/'on', 'off' by default)
65    ParamOut.OutputDirExt='.sback';%set the output dir extension
66    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
67   
68    %% root input file(s) and type
69    % check the existence of the first file in the series
70        first_j=[];
71    if isfield(Param.IndexRange,'first_j'); first_j=Param.IndexRange.first_j; end
72    last_j=[];
73    if isfield(Param.IndexRange,'last_j'); last_j=Param.IndexRange.last_j; end
74    PairString='';
75    if isfield(Param.IndexRange,'PairString'); PairString=Param.IndexRange.PairString; end
76    [i1,i2,j1,j2] = get_file_index(Param.IndexRange.first_i,first_j,PairString);
77    FirstFileName=fullfile_uvmat(Param.InputTable{1,1},Param.InputTable{1,2},Param.InputTable{1,3},...
78        Param.InputTable{1,5},Param.InputTable{1,4},i1,i2,j1,j2);
79    if ~exist(FirstFileName,'file')
80        msgbox_uvmat('WARNING',['the first input file ' FirstFileName ' does not exist'])
81    else
82        [i1,i2,j1,j2] = get_file_index(Param.IndexRange.last_i,last_j,PairString);
83        LastFileName=fullfile_uvmat(Param.InputTable{1,1},Param.InputTable{1,2},Param.InputTable{1,3},...
84        Param.InputTable{1,5},Param.InputTable{1,4},i1,i2,j1,j2);
85        if ~exist(FirstFileName,'file')
86             msgbox_uvmat('WARNING',['the last input file ' LastFileName ' does not exist'])
87        end
88    end
89
90    %% check the validity of  input file types
91    ImageTypeOptions={'image','multimage','mmreader','video'};%allowed input file types(images)
92    FileType=get_file_type(FirstFileName);
93    CheckImage=~isempty(find(strcmp(FileType,ImageTypeOptions), 1));% =1 for images
94    if ~CheckImage
95        msgbox_uvmat('ERROR',['invalid file type input: ' FileType ' not an image'])
96        return
97    end
98   
99    %% numbers of fields
100    NbSlice=1;%default
101    if isfield(Param.IndexRange,'NbSlice')&&~isempty(Param.IndexRange.NbSlice)
102        NbSlice=Param.IndexRange.NbSlice;
103    end
104    incr_j=1;%default
105    if isfield(Param.IndexRange,'incr_j')&&~isempty(Param.IndexRange.incr_j)
106        incr_j=Param.IndexRange.incr_j;
107    end
108    if isempty(first_j)||isempty(last_j)
109        nbfield_j=1;
110    else
111        nbfield_j=numel(first_j:incr_j:last_j);%nb of fields for the j index (bursts or volume slices)
112    end
113    incr_i=1;%default
114    first_i=1;last_i=1;incr_i;%default
115    if isfield(Param.IndexRange,'first_i'); last_i=Param.IndexRange.first_i; end   
116    if isfield(Param.IndexRange,'last_i'); last_i=Param.IndexRange.last_j; end
117    if isfield(Param.IndexRange,'incr_i')&&~isempty(Param.IndexRange.incr_i)
118        incr_i=Param.IndexRange.incr_i;
119    end
120    nbfield_i=numel(first_i:incr_i:last_i);%nb of fields for the i index (bursts or volume slices)
121    nbfield=nbfield_j*nbfield_i; %total number of fields
122    nbfield_i=floor(nbfield/NbSlice);%total number of  indexes in a slice (adjusted to an integer number of slices)
123   
124    %% setting of  parameters specific to sub_background
125    nbaver_init=23; %default number of images used for the sliding background: to be adjusted later to include an integer number of bursts 
126    if nbfield_i~=1
127        nbaver=floor(nbaver_init/nbfield_j); % number of bursts used for the sliding background,
128        if isequal(floor(nbaver/2),nbaver)
129            nbaver=nbaver+1;%put the number of burst to an odd number (so the middle burst is defined)
130        end
131        nbaver_init=nbaver*nbfield_j;%propose by default an integer number of bursts
132    end
133   
134    prompt = {'volume scan mode (Yes/No)';'Number of images for the sliding background (MUST FIT IN COMPUTER MEMORY)';...
135        'the luminosity rank chosen to define the background (0.1=for dense particle seeding, 0.5 (median) for sparse particles'};
136    dlg_title = 'get (slice by slice) a sliding background and substract to each image';
137    num_lines= 3;
138    def     = { 'No';num2str(nbaver_init);'0.1'};
139    answer = inputdlg(prompt,dlg_title,num_lines,def);
140   
141    %check input consistency
142    if strcmp(answer{1},'No') && ~isequal(NbSlice,1)
143        check=msgbox_uvmat('INPUT_Y-N',['confirm the multi-level splitting into ' num2str(NbSlice) ' slices']);
144        if ~strcmp(check,'Yes')
145            return
146        end
147    end
148    if strcmp(answer{1},'Yes')
149        step=1;
150    else
151        step=nbfield_j;%case of bursts: the sliding background is shifted by the length of one burst
152    end
153    nbaver_ima=str2num(answer{2});%number of images for the sliding background
154    nbaver=ceil(nbaver_ima/step);%number of bursts for the sliding background
155    if isequal(floor(nbaver/2),nbaver)
156        nbaver=nbaver+1;%set the number of bursts to an odd number (so the middle burst is defined)
157    end
158    nbaver_ima=nbaver*step;% correct the nbre of images corresponding to nbaver
159    ParamOut.ActionInput.CheckVolume=strcmp(answer{1},'Yes');
160    ParamOut.ActionInput.SlidingSequenceLength=nbaver_ima;
161    ParamOut.ActionInput.BrightnessRankThreshold=str2num(answer{3});
162   
163    % apply the image rescaling function 'level' (avoid the blinking effects of bright particles)
164    answer=msgbox_uvmat('INPUT_Y-N','apply image rescaling function levels.m after sub_background');
165    ParamOut.ActionInput.CheckLevelTransform=strcmp(answer,'Yes');
166    return
167end
168%%%%%%%%%%%%%%%%%    STOP HERE FOR PAMETER INPUT MODE   %%%%%%%%%%%%%%%%%
169
170%% read input parameters from an xml file if input is a file name (batch mode)
171checkrun=1;
172if ischar(Param)
173    Param=xml2struct(Param);% read Param as input file (batch case)
174    checkrun=0;
175end
176hseries=findobj(allchild(0),'Tag','series');
177RUNHandle=findobj(hseries,'Tag','RUN');%handle of RUN button in GUI series
178WaitbarHandle=findobj(hseries,'Tag','Waitbar');%handle of waitbar in GUI series
179
180%% input preparation
181nbaver_ima=Param.ActionInput.SlidingSequenceLength;
182NbSlice=Param.IndexRange.NbSlice;
183if ~isequal(NbSlice,1)
184    display(['multi-level splitting into ' num2str(NbSlice) ' slices']);
185end
186RootPath=Param.InputTable(:,1);
187RootFile=Param.InputTable(:,3);
188SubDir=Param.InputTable(:,2);
189NomType=Param.InputTable(:,4);
190FileExt=Param.InputTable(:,5);
191hdisp=disp_uvmat('WAITING...','checking the file series',checkrun);
192[filecell,i1_series,i2_series,j1_series,j2_series]=get_file_series(Param);
193if ~isempty(hdisp),delete(hdisp),end;
194%%%%%%%%%%%%
195    % The cell array filecell is the list of input file names, while
196    % filecell{iview,fileindex}:
197    %        iview: line in the table corresponding to a given file series
198    %        fileindex: file index within  the file series,
199    % 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
200    % i1_series(iview,fileindex) expresses the same indices as a 1D array in file indices
201%%%%%%%%%%%%
202[FileType{1},FileInfo{1},MovieObject{1}]=get_file_type(filecell{1,1});
203    if ~isempty(j1_series{1})
204        frame_index{1}=j1_series{1};
205    else
206        frame_index{1}=i1_series{1};
207    end
208nbfield_j=size(i1_series{1},1); %nb of fields for the j index (bursts or volume slices)
209nbfield_i=size(i1_series{1},2); %nb of fields for the i index
210nbfield=nbfield_j*nbfield_i; %total number of fields
211nbfield_i=floor(nbfield/NbSlice);%total number of  indexes in a slice (adjusted to an integer number of slices)
212nbfield=nbfield_i*NbSlice; %total number of fields after adjustement
213
214%% output
215FileExtOut='.png'; % write result as .png images for image inputs
216if strcmp(lower(NomType{1}(end)),'a')
217    NomTypeOut=NomType{1};%case of letter appendix
218elseif isempty(j1_series)
219    NomTypeOut='_1';
220else
221    NomTypeOut='_1_1';% caseof purely numerical indexing
222end
223
224OutputDir=[Param.OutputSubDir Param.OutputDirExt];
225
226if isequal(Param.ActionInput.CheckVolume,1)
227    step=1;
228else
229    step=nbfield_j;%case of bursts: the sliding background is shifted by the length of one burst
230end
231nbaver_ima=Param.ActionInput.SlidingSequenceLength;%number of images for the sliding background
232nbaver=ceil(nbaver_ima/step);%number of bursts for the sliding background
233if isequal(floor(nbaver/2),nbaver)
234    nbaver=nbaver+1;%set the number of bursts to an odd number (so the middle burst is defined)
235end
236nbaver_ima=nbaver*step;
237if nbaver_ima > nbfield
238    display('number of images in a slice smaller than the proposed number of images for the sliding average')
239    return
240end
241
242% calculate absolute brightness rank
243rank=floor(Param.ActionInput.BrightnessRankThreshold*nbaver_ima);
244if rank==0
245    rank=1;%rank selected in the sorted image series
246end
247
248%% prealocate memory for the sliding background
249try
250    Afirst=read_image(filecell{1,1},FileType{1},MovieObject{1},frame_index{1}(1));
251    [npy,npx,nbcolor]=size(Afirst);% the argument nbcolor is important to get npx right for color images
252    if strcmp(class(Afirst),'uint8') % case of 8bit images
253        Ak=zeros(npy,npx,nbaver_ima,'uint8'); %prealocate memory
254        Asort=zeros(npy,npx,nbaver_ima,'uint8'); %prealocate memory
255    else
256        Ak=zeros(npy,npx,nbaver_ima,'uint16'); %prealocate memory
257        Asort=zeros(npy,npx,nbaver_ima,'uint16'); %prealocate memory
258    end
259catch ME
260    msgbox_uvmat('ERROR',['sub_background/read_image/' ME.message])
261    return
262end
263
264%% summary of the parameters:
265% nbfield : total number of images treated (in case of multislices the function sub_background is repeated for each slice)
266% step: shift at each step of the sliding background (corresponding to the nbre of images in a burst)
267% nbaver_ima: length of the sequence used for the sliding background
268
269% nbaver=nbaver_ima/step: nbaver_ima has been adjusted so that nbaver is an odd integer
270halfnbaver=floor(nbaver/2); % half width (in unit of bursts) of the sliding background
271
272%% select the series of image indices to process
273indselect=1:step:nbfield;% select file indices of the slice
274for ifield=1:step-1
275    indselect=[indselect;indselect(end,:)+1];
276end
277
278%% read the first series of nbaver_ima images and sort by luminosity at each pixel
279for ifield = 1:nbaver_ima
280    ifile=indselect(ifield);
281    filename=filecell{1,ifile};
282    Aread=read_image(filename,FileType{1},MovieObject{1},frame_index{1}(ifile));
283    if ndims(Aread)==3;%color images
284        Aread=sum(double(Aread),3);% take the sum of color components
285    end
286    Ak(:,:,ifield)=Aread;
287end
288Asort=sort(Ak,3);%sort the luminosity of images at each point
289B=Asort(:,:,rank);%background image
290
291%% substract the first background image to the first images
292display( 'first background image will be substracted')
293for ifield=1:step*(halfnbaver+1);% nbre of images treated by the first background image
294    Acor=double(Ak(:,:,ifield))-double(B);%substract background to the current image
295    Acor=(Acor>0).*Acor; % put to 0 the negative elements in Acor
296    ifile=indselect(ifield);
297    if ~isempty(j1_series{1})
298        j1=j1_series{1}(ifile);
299    end
300    newname=fullfile_uvmat(RootPath{1},OutputDir,RootFile{1},FileExtOut,NomTypeOut,i1_series{1}(ifile),[],j1);
301   
302    %write result file
303    if Param.ActionInput.CheckLevelTransform
304        C=levels(Acor);
305        imwrite(C,newname,'BitDepth',8); % save the new image
306    else
307        if isequal(FileInfo{1}.BitDepth,16)
308            C=uint16(Acor);
309            imwrite(C,newname,'BitDepth',16); % save the new image
310        else
311            C=uint8(Acor);
312            imwrite(C,newname,'BitDepth',8); % save the new image
313        end
314    end
315    display([newname ' written'])
316end
317
318%% repeat the operation on a sliding series of images
319display('sliding background image will be substracted')
320if nbfield_i > nbaver_ima
321    for ifield = step*(halfnbaver+1):step:nbfield_i-step*(halfnbaver+1)% ifield +iburst=index of the current processed image
322        update_waitbar(WaitbarHandle,ifield/nbfield_i)
323        if ~isempty(RUNHandle) &&ishandle(RUNHandle) && ~strcmp(get(RUNHandle,'BusyAction'),'queue')
324            disp('program stopped by user')
325            return
326        end
327        Ak(:,:,1:nbaver_ima-step)=Ak(:,:,1+step:nbaver_ima);% shift the current image series by one burst (step)
328        %incorporate next burst in the current image series
329        for iburst=1:step
330            ifile=indselect(ifield+iburst+step*halfnbaver);
331            filename=fullfile_uvmat(RootPath{1},SubDir{1},RootFile{1},FileExt{1},NomType{1},i1_series{1}(ifile),[],j1_series{1}(ifile));
332            Aread=read_image(filename,FileType{1},MovieObject{1},i1_series{1}(ifile));
333            if ndims(Aread)==3;%color images
334                Aread=sum(double(Aread),3);% take the sum of color components
335            end
336            Ak(:,:,nbaver_ima-step+iburst)=Aread;% fill the last burst of the current image series by the new image
337        end
338        Asort=sort(Ak,3);%sort the new current image series by luminosity
339        B=Asort(:,:,rank);%current background image
340        %substract the background for the current burst
341        for iburst=1:step
342            Acor=double(Ak(:,:,step*halfnbaver+iburst))-double(B); %the current image has been already read ans stored as index step*halfnbaver+iburst in the current series
343            Acor=(Acor>0).*Acor; % put to 0 the negative elements in Acor
344            ifile=indselect(ifield+iburst);
345            if ~isempty(j1_series{1})
346                j1=j1_series{1}(ifile);
347            end
348            newname=fullfile_uvmat(RootPath{1},OutputDir,RootFile{1},FileExtOut,NomTypeOut,i1_series{1}(ifile),[],j1);
349            %write result file
350            if Param.ActionInput.CheckLevelTransform
351                C=levels(Acor);
352                imwrite(C,newname,'BitDepth',8); % save the new image
353            else
354                if isequal(FileInfo{1}.BitDepth,16)
355                    C=uint16(Acor);
356                    imwrite(C,newname,'BitDepth',16); % save the new image
357                else
358                    C=uint8(Acor);
359                    imwrite(C,newname,'BitDepth',8); % save the new image
360                end
361            end
362            display([newname ' written'])       
363        end
364    end
365end
366
367%% substract the background from the last images
368display('last background image will be substracted')
369for  ifield=nbfield_i-step*halfnbaver+1:nbfield_i
370    Acor=double(Ak(:,:,ifield-nbfield_i+step*(2*halfnbaver+1)))-double(B);
371    Acor=(Acor>0).*Acor; % put to 0 the negative elements in Acor
372    ifile=indselect(ifield);
373    if ~isempty(j1_series{1})
374        j1=j1_series{1}(ifile);
375    end
376    newname=fullfile_uvmat(RootPath{1},OutputDir,RootFile{1},FileExtOut,NomTypeOut,i1_series{1}(ifile),[],j1); 
377    %write result file
378    if Param.ActionInput.CheckLevelTransform
379        C=levels(Acor);
380        imwrite(C,newname,'BitDepth',8); % save the new image
381    else
382        if isequal(FileInfo{1}.BitDepth,16)
383            C=uint16(Acor);
384            imwrite(C,newname,'BitDepth',16); % save the new image
385        else
386            C=uint8(Acor);
387            imwrite(C,newname,'BitDepth',8); % save the new image
388        end
389    end
390    display([newname ' written'])
391end
392
393
394
395function C=levels(A)
396%whos A;
397B=double(A(:,:,1));
398windowsize=round(min(size(B,1),size(B,2))/20);
399windowsize=floor(windowsize/2)*2+1;
400ix=1/2-windowsize/2:-1/2+windowsize/2;%
401%del=np/3;
402%fct=exp(-(ix/del).^2);
403fct2=cos(ix/(windowsize-1)/2*pi/2);
404%Mfiltre=(ones(5,5)/5^2);
405%Mfiltre=fct2';
406Mfiltre=fct2'*fct2;
407Mfiltre=Mfiltre/(sum(sum(Mfiltre)));
408
409C=filter2(Mfiltre,B);
410C(:,1:windowsize)=C(:,windowsize)*ones(1,windowsize);
411C(:,end-windowsize+1:end)=C(:,end-windowsize+1)*ones(1,windowsize);
412C(1:windowsize,:)=ones(windowsize,1)*C(windowsize,:);
413C(end-windowsize+1:end,:)=ones(windowsize,1)*C(end-windowsize,:);
414C=tanh(B./(2*C));
415[n,c]=hist(reshape(C,1,[]),100);
416% figure;plot(c,n);
417
418[m,i]=max(n);
419c_max=c(i);
420[dummy,index]=sort(abs(c-c(i)));
421n=n(index);
422c=c(index);
423i_select = find(cumsum(n)<0.95*sum(n));
424if isempty(i_select)
425    i_select = 1:length(c);
426end
427c_select=c(i_select);
428n_select=n(i_select);
429cmin=min(c_select);
430cmax=max(c_select);
431C=(C-cmin)/(cmax-cmin)*256;
432C=uint8(C);
Note: See TracBrowser for help on using the repository browser.