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

Last change on this file since 810 was 810, checked in by g7moreau, 7 years ago
  • Add license
File size: 20.5 KB
[457]1%'sub_background': substract a sliding background to an image series
[24]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:
[454]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)
[457]15% function GUI_config=sub_background(Param)
[451]17%%%%%%%%%%% GENERAL TO ALL SERIES ACTION FCTS %%%%%%%%%%%%%%%%%%%%%%%%%%%
[596]20% ParamOut: sets options in the GUI series.fig needed for the function
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
[596]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
[596]28% Param contains the elements:(use the menu bar command 'export/GUI config' in series to
29% see the current structure Param)
[451]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
[596]33%    .OutputDirExt: directory extension for data outputs
[451]34%    .Action: .ActionName: name of the current activated function
35%             .ActionPath:   path of the current activated function
[596]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
[451]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
[596]44%              .FieldName: name(s) of the field
[451]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
[596]48%              .Coord_y: name of y coordinate variable
49%              .Coord_x: name of x coordinate variable
[451]50%    .ProjObject: %sub structure describing a projection object (read from ancillary GUI set_object)
54% Copyright 2008-2014, LEGI UMR 5519 / CNRS UJF G-INP, Grenoble, France
56%   Joel.Sommeria - Joel.Sommeria (A)
58%     This file is part of the toolbox UVMAT.
60%     UVMAT is free software; you can redistribute it and/or modify
61%     it under the terms of the GNU General Public License as published
62%     by the Free Software Foundation; either version 2 of the license,
63%     or (at your option) any later version.
65%     UVMAT is distributed in the hope that it will be useful,
66%     but WITHOUT ANY WARRANTY; without even the implied warranty of
68%     GNU General Public License (see LICENSE.txt) for more details.
[459]71function ParamOut=sub_background (Param)
[676]73%%%%%%%%%%%%%%%%%    INPUT PREPARATION MODE (no RUN)    %%%%%%%%%%%%%%%%%
[592]74if isstruct(Param) && isequal(Param.Action.RUN,0)
[605]75    ParamOut.AllowInputSort='off';% allow alphabetic sorting of the list of input file SubDir (options 'off'/'on', 'off' by default)
76    ParamOut.WholeIndexRange='on';% prescribes the file index ranges from min to max (options 'off'/'on', 'off' by default)
77    ParamOut.NbSlice='on'; %nbre of slices ('off' by default)
78    ParamOut.VelType='off';% menu for selecting the velocity type (options 'off'/'one'/'two',  'off' by default)
79    ParamOut.FieldName='off';% menu for selecting the field (s) in the input file(options 'off'/'one'/'two', 'off' by default)
80    ParamOut.FieldTransform = 'off';%can use a transform function
81    ParamOut.ProjObject='off';%can use projection object(option 'off'/'on',
82    ParamOut.Mask='off';%can use mask option   (option 'off'/'on', 'off' by default)
[592]83    ParamOut.OutputDirExt='.sback';%set the output dir extension
[605]84    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
86    %% root input file(s) and type
[716]87    % check the existence of the first file in the series
88        first_j=[];
89    if isfield(Param.IndexRange,'first_j'); first_j=Param.IndexRange.first_j; end
90    last_j=[];
91    if isfield(Param.IndexRange,'last_j'); last_j=Param.IndexRange.last_j; end
92    PairString='';
93    if isfield(Param.IndexRange,'PairString'); PairString=Param.IndexRange.PairString; end
94    [i1,i2,j1,j2] = get_file_index(Param.IndexRange.first_i,first_j,PairString);
95    FirstFileName=fullfile_uvmat(Param.InputTable{1,1},Param.InputTable{1,2},Param.InputTable{1,3},...
96        Param.InputTable{1,5},Param.InputTable{1,4},i1,i2,j1,j2);
97    if ~exist(FirstFileName,'file')
98        msgbox_uvmat('WARNING',['the first input file ' FirstFileName ' does not exist'])
99    else
100        [i1,i2,j1,j2] = get_file_index(Param.IndexRange.last_i,last_j,PairString);
101        LastFileName=fullfile_uvmat(Param.InputTable{1,1},Param.InputTable{1,2},Param.InputTable{1,3},...
102        Param.InputTable{1,5},Param.InputTable{1,4},i1,i2,j1,j2);
103        if ~exist(FirstFileName,'file')
104             msgbox_uvmat('WARNING',['the last input file ' LastFileName ' does not exist'])
105        end
[605]106    end
[592]108    %% check the validity of  input file types
109    ImageTypeOptions={'image','multimage','mmreader','video'};%allowed input file types(images)
[784]110    FileInfo=get_file_info(FirstFileName);
[783]111    FileType=FileInfo.FileType;
[592]112    CheckImage=~isempty(find(strcmp(FileType,ImageTypeOptions), 1));% =1 for images
113    if ~CheckImage
[642]114        msgbox_uvmat('ERROR',['invalid file type input: ' FileType ' not an image'])
[451]115        return
[592]116    end
[676]118    %% numbers of fields
119    NbSlice=1;%default
120    if isfield(Param.IndexRange,'NbSlice')&&~isempty(Param.IndexRange.NbSlice)
121        NbSlice=Param.IndexRange.NbSlice;
[592]122    end
[774]123    incr_j=1;%default
124    if isfield(Param.IndexRange,'incr_j')&&~isempty(Param.IndexRange.incr_j)
125        incr_j=Param.IndexRange.incr_j;
126    end
127    if isempty(first_j)||isempty(last_j)
128        nbfield_j=1;
129    else
130        nbfield_j=numel(first_j:incr_j:last_j);%nb of fields for the j index (bursts or volume slices)
131    end
132    incr_i=1;%default
133    first_i=1;last_i=1;incr_i;%default
134    if isfield(Param.IndexRange,'first_i'); last_i=Param.IndexRange.first_i; end   
[802]135    if isfield(Param.IndexRange,'last_i'); last_i=Param.IndexRange.last_i; end
[774]136    if isfield(Param.IndexRange,'incr_i')&&~isempty(Param.IndexRange.incr_i)
137        incr_i=Param.IndexRange.incr_i;
138    end
139    nbfield_i=numel(first_i:incr_i:last_i);%nb of fields for the i index (bursts or volume slices)
[676]140    nbfield=nbfield_j*nbfield_i; %total number of fields
141    nbfield_i=floor(nbfield/NbSlice);%total number of  indexes in a slice (adjusted to an integer number of slices)
[676]143    %% setting of  parameters specific to sub_background
144    nbaver_init=23; %default number of images used for the sliding background: to be adjusted later to include an integer number of bursts 
[592]145    if nbfield_i~=1
146        nbaver=floor(nbaver_init/nbfield_j); % number of bursts used for the sliding background,
147        if isequal(floor(nbaver/2),nbaver)
148            nbaver=nbaver+1;%put the number of burst to an odd number (so the middle burst is defined)
149        end
150        nbaver_init=nbaver*nbfield_j;%propose by default an integer number of bursts
151    end
[676]153    prompt = {'volume scan mode (Yes/No)';'Number of images for the sliding background (MUST FIT IN COMPUTER MEMORY)';...
154        'the luminosity rank chosen to define the background (0.1=for dense particle seeding, 0.5 (median) for sparse particles'};
155    dlg_title = 'get (slice by slice) a sliding background and substract to each image';
156    num_lines= 3;
157    def     = { 'No';num2str(nbaver_init);'0.1'};
158    answer = inputdlg(prompt,dlg_title,num_lines,def);
160    %check input consistency
161    if strcmp(answer{1},'No') && ~isequal(NbSlice,1)
162        check=msgbox_uvmat('INPUT_Y-N',['confirm the multi-level splitting into ' num2str(NbSlice) ' slices']);
163        if ~strcmp(check,'Yes')
164            return
[592]165        end
166    end
[676]167    if strcmp(answer{1},'Yes')
168        step=1;
169    else
170        step=nbfield_j;%case of bursts: the sliding background is shifted by the length of one burst
171    end
172    nbaver_ima=str2num(answer{2});%number of images for the sliding background
173    nbaver=ceil(nbaver_ima/step);%number of bursts for the sliding background
174    if isequal(floor(nbaver/2),nbaver)
175        nbaver=nbaver+1;%set the number of bursts to an odd number (so the middle burst is defined)
176    end
177    nbaver_ima=nbaver*step;% correct the nbre of images corresponding to nbaver
[599]178    ParamOut.ActionInput.CheckVolume=strcmp(answer{1},'Yes');
179    ParamOut.ActionInput.SlidingSequenceLength=nbaver_ima;
180    ParamOut.ActionInput.BrightnessRankThreshold=str2num(answer{3});
182    % apply the image rescaling function 'level' (avoid the blinking effects of bright particles)
183    answer=msgbox_uvmat('INPUT_Y-N','apply image rescaling function levels.m after sub_background');
[599]184    ParamOut.ActionInput.CheckLevelTransform=strcmp(answer,'Yes');
[592]185    return
[676]187%%%%%%%%%%%%%%%%%    STOP HERE FOR PAMETER INPUT MODE   %%%%%%%%%%%%%%%%%
[592]189%% read input parameters from an xml file if input is a file name (batch mode)
[457]191if ischar(Param)
[592]192    Param=xml2struct(Param);% read Param as input file (batch case)
193    checkrun=0;
196RUNHandle=findobj(hseries,'Tag','RUN');%handle of RUN button in GUI series
197WaitbarHandle=findobj(hseries,'Tag','Waitbar');%handle of waitbar in GUI series
199%% input preparation
202if ~isequal(NbSlice,1)
203    display(['multi-level splitting into ' num2str(NbSlice) ' slices']);
[774]210hdisp=disp_uvmat('WAITING...','checking the file series',checkrun);
[774]212if ~isempty(hdisp),delete(hdisp),end;
214    % The cell array filecell is the list of input file names, while
215    % filecell{iview,fileindex}:
216    %        iview: line in the table corresponding to a given file series
217    %        fileindex: file index within  the file series,
218    % 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
219    % i1_series(iview,fileindex) expresses the same indices as a 1D array in file indices
[592]223    if ~isempty(j1_series{1})
224        frame_index{1}=j1_series{1};
225    else
226        frame_index{1}=i1_series{1};
227    end
[454]228nbfield_j=size(i1_series{1},1); %nb of fields for the j index (bursts or volume slices)
229nbfield_i=size(i1_series{1},2); %nb of fields for the i index
230nbfield=nbfield_j*nbfield_i; %total number of fields
[592]231nbfield_i=floor(nbfield/NbSlice);%total number of  indexes in a slice (adjusted to an integer number of slices)
[454]232nbfield=nbfield_i*NbSlice; %total number of fields after adjustement
[676]234%% output
[592]235FileExtOut='.png'; % write result as .png images for image inputs
236if strcmp(lower(NomType{1}(end)),'a')
237    NomTypeOut=NomType{1};%case of letter appendix
[802]238elseif isempty(j1_series{1})
[592]239    NomTypeOut='_1';
[592]241    NomTypeOut='_1_1';% caseof purely numerical indexing
[592]244OutputDir=[Param.OutputSubDir Param.OutputDirExt];
[599]246if isequal(Param.ActionInput.CheckVolume,1)
[592]247    step=1;
249    step=nbfield_j;%case of bursts: the sliding background is shifted by the length of one burst
[599]251nbaver_ima=Param.ActionInput.SlidingSequenceLength;%number of images for the sliding background
[592]252nbaver=ceil(nbaver_ima/step);%number of bursts for the sliding background
253if isequal(floor(nbaver/2),nbaver)
254    nbaver=nbaver+1;%set the number of bursts to an odd number (so the middle burst is defined)
257if nbaver_ima > nbfield
258    display('number of images in a slice smaller than the proposed number of images for the sliding average')
259    return
262% calculate absolute brightness rank
[24]264if rank==0
265    rank=1;%rank selected in the sorted image series
[239]268%% prealocate memory for the sliding background
[454]270    Afirst=read_image(filecell{1,1},FileType{1},MovieObject{1},frame_index{1}(1));
[700]271    [npy,npx,nbcolor]=size(Afirst);% the argument nbcolor is important to get npx right for color images
[454]272    if strcmp(class(Afirst),'uint8') % case of 8bit images
273        Ak=zeros(npy,npx,nbaver_ima,'uint8'); %prealocate memory
274        Asort=zeros(npy,npx,nbaver_ima,'uint8'); %prealocate memory
275    else
276        Ak=zeros(npy,npx,nbaver_ima,'uint16'); %prealocate memory
277        Asort=zeros(npy,npx,nbaver_ima,'uint16'); %prealocate memory
278    end
[239]279catch ME
[592]280    msgbox_uvmat('ERROR',['sub_background/read_image/' ME.message])
[239]281    return
[676]284%% summary of the parameters:
285% nbfield : total number of images treated (in case of multislices the function sub_background is repeated for each slice)
286% step: shift at each step of the sliding background (corresponding to the nbre of images in a burst)
287% nbaver_ima: length of the sequence used for the sliding background
[676]289% nbaver=nbaver_ima/step: nbaver_ima has been adjusted so that nbaver is an odd integer
290halfnbaver=floor(nbaver/2); % half width (in unit of bursts) of the sliding background
292%% select the series of image indices to process
[616]293indselect=1:step:nbfield;% select file indices of the slice
294for ifield=1:step-1
295    indselect=[indselect;indselect(end,:)+1];
298%% read the first series of nbaver_ima images and sort by luminosity at each pixel
299for ifield = 1:nbaver_ima
300    ifile=indselect(ifield);
301    filename=filecell{1,ifile};
302    Aread=read_image(filename,FileType{1},MovieObject{1},frame_index{1}(ifile));
303    if ndims(Aread)==3;%color images
304        Aread=sum(double(Aread),3);% take the sum of color components
[394]305    end
[616]306    Ak(:,:,ifield)=Aread;
308Asort=sort(Ak,3);%sort the luminosity of images at each point
309B=Asort(:,:,rank);%background image
311%% substract the first background image to the first images
[616]312display( 'first background image will be substracted')
[676]313for ifield=1:step*(halfnbaver+1);% nbre of images treated by the first background image
[616]314    Acor=double(Ak(:,:,ifield))-double(B);%substract background to the current image
315    Acor=(Acor>0).*Acor; % put to 0 the negative elements in Acor
316    ifile=indselect(ifield);
[802]317    j1=1;
[616]318    if ~isempty(j1_series{1})
319        j1=j1_series{1}(ifile);
320    end
321    newname=fullfile_uvmat(RootPath{1},OutputDir,RootFile{1},FileExtOut,NomTypeOut,i1_series{1}(ifile),[],j1);
[616]323    %write result file
324    if Param.ActionInput.CheckLevelTransform
325        C=levels(Acor);
326        imwrite(C,newname,'BitDepth',8); % save the new image
327    else
328        if isequal(FileInfo{1}.BitDepth,16)
329            C=uint16(Acor);
330            imwrite(C,newname,'BitDepth',16); % save the new image
331        else
332            C=uint8(Acor);
333            imwrite(C,newname,'BitDepth',8); % save the new image
[454]334        end
[24]335    end
[616]336    display([newname ' written'])
339%% repeat the operation on a sliding series of images
340display('sliding background image will be substracted')
341if nbfield_i > nbaver_ima
[676]342    for ifield = step*(halfnbaver+1):step:nbfield_i-step*(halfnbaver+1)% ifield +iburst=index of the current processed image
343        update_waitbar(WaitbarHandle,ifield/nbfield_i)
344        if ~isempty(RUNHandle) &&ishandle(RUNHandle) && ~strcmp(get(RUNHandle,'BusyAction'),'queue')
345            disp('program stopped by user')
346            return
347        end
348        Ak(:,:,1:nbaver_ima-step)=Ak(:,:,1+step:nbaver_ima);% shift the current image series by one burst (step)
349        %incorporate next burst in the current image series
350        for iburst=1:step
351            ifile=indselect(ifield+iburst+step*halfnbaver);
[802]352            j1=1;
353    if ~isempty(j1_series{1})
354        j1=j1_series{1}(ifile);
355    end
356            filename=fullfile_uvmat(RootPath{1},SubDir{1},RootFile{1},FileExt{1},NomType{1},i1_series{1}(ifile),[],j1);
[676]357            Aread=read_image(filename,FileType{1},MovieObject{1},i1_series{1}(ifile));
358            if ndims(Aread)==3;%color images
359                Aread=sum(double(Aread),3);% take the sum of color components
[442]360            end
[676]361            Ak(:,:,nbaver_ima-step+iburst)=Aread;% fill the last burst of the current image series by the new image
362        end
363        Asort=sort(Ak,3);%sort the new current image series by luminosity
364        B=Asort(:,:,rank);%current background image
365        %substract the background for the current burst
366        for iburst=1:step
367            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
368            Acor=(Acor>0).*Acor; % put to 0 the negative elements in Acor
369            ifile=indselect(ifield+iburst);
370            if ~isempty(j1_series{1})
371                j1=j1_series{1}(ifile);
372            end
373            newname=fullfile_uvmat(RootPath{1},OutputDir,RootFile{1},FileExtOut,NomTypeOut,i1_series{1}(ifile),[],j1);
374            %write result file
375            if Param.ActionInput.CheckLevelTransform
376                C=levels(Acor);
377                imwrite(C,newname,'BitDepth',8); % save the new image
378            else
379                if isequal(FileInfo{1}.BitDepth,16)
380                    C=uint16(Acor);
381                    imwrite(C,newname,'BitDepth',16); % save the new image
382                else
383                    C=uint8(Acor);
[616]384                    imwrite(C,newname,'BitDepth',8); % save the new image
[214]385                end
[24]386            end
[676]387            display([newname ' written'])       
388        end
[24]389    end
392%% substract the background from the last images
393display('last background image will be substracted')
[676]394for  ifield=nbfield_i-step*halfnbaver+1:nbfield_i
395    Acor=double(Ak(:,:,ifield-nbfield_i+step*(2*halfnbaver+1)))-double(B);
[616]396    Acor=(Acor>0).*Acor; % put to 0 the negative elements in Acor
397    ifile=indselect(ifield);
398    if ~isempty(j1_series{1})
399        j1=j1_series{1}(ifile);
400    end
[676]401    newname=fullfile_uvmat(RootPath{1},OutputDir,RootFile{1},FileExtOut,NomTypeOut,i1_series{1}(ifile),[],j1); 
[616]402    %write result file
403    if Param.ActionInput.CheckLevelTransform
404        C=levels(Acor);
405        imwrite(C,newname,'BitDepth',8); % save the new image
406    else
407        if isequal(FileInfo{1}.BitDepth,16)
408            C=uint16(Acor);
409            imwrite(C,newname,'BitDepth',16); % save the new image
410        else
411            C=uint8(Acor);
[394]412            imwrite(C,newname,'BitDepth',8); % save the new image
413        end
414    end
[616]415    display([newname ' written'])
[214]420function C=levels(A)
421%whos A;
441% figure;plot(c,n);
448i_select = find(cumsum(n)<0.95*sum(n));
449if isempty(i_select)
450    i_select = 1:length(c);
Note: See TracBrowser for help on using the repository browser.