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

Last change on this file since 214 was 214, checked in by sommeria, 13 years ago

relabel_i_j and sub_background improved. Possibility of using levels

File size: 16.2 KB
Line 
1%'sub_background': substract background to an image series, used with series.fig
2%------------------------------------------------------------------------
3% function GUI_input=aver_stat(num_i1,num_i2,num_j1,num_j2,Series)
4%
5%OUTPUT
6% GUI_input=list of options in the GUI series.fig needed for the function
7%
8%INPUT:
9%num_i1: series of first indices i (given from the series interface as first_i:incr_i:last_i, mode and list_pair_civ)
10%num_i2: series of second indices i (given from the series interface as first_i:incr_i:last_i, mode and list_pair_civ)
11%num_j1: series of first indices j (given from the series interface as first_j:incr_j:last_j, mode and list_pair_civ )
12%num_j2: series of second indices j (given from the series interface as first_j:incr_j:last_j, mode and list_pair_civ)
13%Series: Matlab structure containing information set by the series interface
14%       .RootPath: path to the image series
15%       .RootFile: root file name
16%       .FileExt: image file extension
17%       .NomType: nomenclature type for file indexing
18%       .NbSlice: %number of slices defined on the interface
19%----------------------------------------------------------------------
20% Method:
21    %calculate the background image by sorting the luminosity of each point
22    % over a sliding sub-sequence of 'nbaver_ima' images.
23    % The luminosity value of rank 'rank' is selected as the
24    % 'background'. rank=nbimages/2 gives the median value.  Smaller values are appropriate
25    % for a dense set of particles. The extrem value rank=1 gives the true minimum
26    % luminosity, but it can be polluted by noise.
27% Organization of image indices:
28    % The program is working on a series of images, labelled by two indices i and j, given
29    % by the input matlab vectors num_i1 and num_j1 respectively. In the list, j is the fastest increasing index.
30    % The processing can be done in slices (number nbslice), with bursts of
31    % nbfield2 successive images for a given slice (mode 'multilevel')
32    % In the mode 'volume', nbfield2=1 (1 image at each level)
33%
34function GUI_input=sub_background (num_i1,num_i2,num_j1,num_j2,Series)
35
36%------------------------------------------------------------------------
37%requests for the visibility of input windows in the GUI series  (activated directly by the selection in the menu ACTION)
38if ~exist('num_i1','var')
39    GUI_input={'RootPath';'on';...
40        'SubDir';'off';... % subdirectory of derived files (PIV fields), ('on' by default)
41        'RootFile';'on';... %root input file name ('on' by default)
42        'FileExt';'on';... %inputf file extension ('on' by default)
43        'NomType';'on';...%type of file indexing ('on' by default)
44        'NbSlice';'on'; ...%nbre of slices ('off' by default)
45        %'VelTypeMenu';'on';...% menu for selecting the velocity type (civ1,..)('off' by default)
46        %'FieldMenu';'on';...% menu for selecting the velocity field (s) in the input file ('off' by default)
47        %'VelTypeMenu_1';'on';...% menu for selecting the velocity type (civ1,..)('off' by default)
48        %'FieldMenu_1';'on';...% menu for selecting the velocity field (s) in the input file ('off' by default)
49        %'CoordType';...%can use a transform function
50        %'GetObject';...;%can use projection object
51        %'GetMask';...;%can use mask option 
52        %'PARAMETER';'NbSliding';...
53        %'PARAMETER';'VolumeScan';...
54        %'PARAMETER';'RankBrightness';...
55               ''};
56    return %exit the function
57end
58
59%----------------------------------------------------------------
60%% initiate the waitbar
61hseries=guidata(Series.hseries);%handles of the GUI series
62WaitbarPos=get(hseries.waitbar_frame,'Position');
63%-----------------------------------------------------------------
64if iscell(Series.RootPath)
65    msgbox_uvmat('ERROR','This function use only one input image series')
66    return
67end
68
69%% determine input image type
70FileType=[];%default
71MovieObject=[];
72FileExt=Series.FileExt;
73
74if isequal(lower(FileExt),'.avi')
75    hhh=which('mmreader');
76    if ~isequal(hhh,'')&& mmreader.isPlatformSupported()
77        MovieObject=mmreader(fullfile(RootPath,[RootFile FileExt]));
78        FileType='movie';
79    else
80        FileType='avi';
81    end
82elseif isequal(lower(FileExt),'.vol')
83    FileType='vol';
84else
85   form=imformats(FileExt(2:end));
86   if ~isempty(form)% if the extension corresponds to an image format recognized by Matlab
87       if isequal(Series.NomType,'*');
88           FileType='multimage';
89       else
90           FileType='image';
91       end
92   end
93end
94if isempty(FileType)
95    msgbox_uvmat('ERROR',['invalid file extension ' FileExt ': this function only accepts image or movie input'])
96    return
97end
98
99nbslice_i=Series.NbSlice; %number of slices
100siz=size(num_i1);
101nbaver_init=23;%approximate number of images used for the sliding background: to be adjusted later to include an integer number of bursts
102
103
104%% apply the image rescaling function 'level' (avoid the blinking effects of bright particles)
105answer=msgbox_uvmat('INPUT_Y-N','apply image rescaling function levels.m after sub_background');
106test_level=isequal(answer,'Yes');
107
108%% adjust the proposed number of images in the sliding average to include an integer number of bursts
109if siz(2)~=1
110    nbaver=floor(nbaver_init/siz(1)); % number of bursts used for the sliding background,
111    if isequal(floor(nbaver/2),nbaver)
112        nbaver=nbaver+1;%put the number of burst to an odd number (so the middle burst is defined)
113    end
114    nbaver_init=nbaver*siz(1);%propose by default an integer number of bursts
115end
116
117filebase=fullfile(Series.RootPath,Series.RootFile);
118dir_images=Series.RootPath;
119nom_type=Series.NomType;
120
121%% create dir of the new images
122% [dir_images,namebase]=fileparts(filebase);
123if test_level
124    term='_b_levels';
125else
126    term='_b';
127end
128[pp,subdir_ima]=fileparts(Series.RootPath);
129try
130    mkdir([dir_images term]);
131catch
132    errormsg=lasterr
133            msgbox_uvmat('ERROR',errormsg);
134            return
135end
136[xx,msg2] = fileattrib([dir_images term],'+w','g'); %yield writing access (+w) to user group (g)
137if ~strcmp(msg2,'')
138    msgbox_uvmat('ERROR',['pb of permission for ' subdir_ima term ': ' msg2])%error message for directory creation
139    return
140end
141filebase_b=fullfile([dir_images term],Series.RootFile);
142
143%% set processing parameters
144prompt = {'Number of images for the sliding background';'The number of positions (laser slices)';'volume scan mode (Yes/No)';...
145        'the luminosity rank chosen to define the background (0.1=for dense particle seeding, 0.5 (median) for sparse particles'};
146dlg_title = ['get (slice by slice) a sliding background and substract to each image, result in subdir ' subdir_ima term];
147num_lines= 3;
148def     = { num2str(nbaver_init);num2str(nbslice_i);'No';'0.1'};
149answer = inputdlg(prompt,dlg_title,num_lines,def);
150set(hseries.ParamVal,'String',answer([1 [3:4]]))
151set(hseries.ParamVal,'Visible','on')
152
153nbaver_ima=str2num(answer{1});%number of images for the sliding background
154nbaver=ceil(nbaver_ima/siz(1));%number of bursts for the sliding background
155if isequal(floor(nbaver/2),nbaver)
156   nbaver=nbaver+1%put the number of burst to an odd number (so the middle burst is defined)
157end
158step=siz(1);%case of bursts: the sliding background is shifted by one burst
159vol_test=answer{3};
160if isequal(vol_test,'Yes')
161    nbfield2=1;%case of volume: no consecutive series at a given level
162    nbslice_i=siz(1);%number of slices
163else
164    nbfield2=siz(1); %nb of consecutive images at each level(burst)
165    if siz(2)>1
166       nbslice_i=str2num(answer{2})/(num_i1(1,2)-num_i1(1,1));% number of slices
167    else
168        nbslice_i=1;
169    end
170    if ~isequal(floor(nbslice_i),nbslice_i)
171        msgbox_uvmat('ERROR','the number of slices must be a multiple of the i increment')
172        return
173    end
174end
175rank=floor(str2num(answer{4})*nbaver_ima);
176if rank==0
177    rank=1;%rank selected in the sorted image series
178end
179lengthtot=siz(1)*siz(2);
180nbfield=floor(lengthtot/(nbfield2*nbslice_i));%total number of i indexes (adjusted to an integer number of slices)
181nbfield_slice=nbfield*nbfield2;% number of fields per slice
182if nbaver_ima > nbfield*nbfield2
183    errordlg('number of images in a slice smaller than the proposed number of images for the sliding average')
184    return
185end
186nbfirst=(ceil(nbaver/2))*step;
187if nbfirst>nbaver_ima
188    nbfirst=ceil(nbaver_ima/2);
189    step=1;
190    nbaver=nbaver_ima;
191end
192
193%% copy the xml file
194if exist([filebase '.xml'],'file')
195    copyfile([filebase '.xml'],[filebase_b '.xml']);% copy the .civ file
196    t=xmltree([filebase_b '.xml']);
197   
198    %update information on the first image name in the series
199    uid_Heading=find(t,'ImaDoc/Heading');
200    if isempty(uid_Heading)
201        [t,uid_Heading]=add(t,1,'element','Heading');
202    end   
203    uid_ImageName=find(t,'ImaDoc/Heading/ImageName');
204    ImageName=name_generator(filebase_b,num_i1(1),num_j1(1),'.png',Series.NomType);
205    [pth,ImageName]=fileparts(ImageName);
206    ImageName=[ImageName '.png']
207    if isempty(uid_ImageName)
208       [t,uid_ImageName]=add(t,uid_Heading,'element','ImageName');
209    end
210    uid_value=children(t,uid_ImageName);
211    if isempty(uid_value)
212        t=add(t,uid_ImageName,'chardata',ImageName)%indicate  name of the first image, with ;png extension
213    else
214        t=set(t,uid_value(1),'value',ImageName)%indicate  name of the first image, with ;png extension
215    end 
216
217    %add information about image transform
218    [t,new_uid]=add(t,1,'element','ImageTransform');
219    [t,NameFunction_uid]=add(t,new_uid,'element','NameFunction');
220    [t]=add(t,NameFunction_uid,'chardata','sub_background');     
221    if test_levels
222            [t,NameFunction_uid]=add(t,new_uid,'element','NameFunction');
223            [t]=add(t,NameFunction_uid,'chardata','levels');
224    end
225    [t,NbSlice_uid]=add(t,new_uid,'element','NbSlice');
226    [t]=add(t,new_uid,'chardata',num2str(nbslice_i));
227    [t,NbSlidingImages_uid]=add(t,new_uid,'element','NbSlidingImages');
228    [t]=add(t,NbSlidingImages_uid,'chardata',num2str(nbaver));
229    [t,LuminosityRank_uid]=add(t,new_uid,'element','RankBackground');
230    [t]=add(t,LuminosityRank_uid,'chardata',num2str(rank));% luminosity rank almong the nbaver sliding images
231    save(t,[filebase_b '.xml'])
232elseif exist([filebase '.civ'],'file')
233    copyfile([filebase '.civ'],[filebase_b '.civ']);% copy the .civ file
234end
235%copy the mask
236if exist([filebase '_1mask_1'],'file')
237     copyfile([filebase '_1mask_1'],[filebase_b '_1mask_1']);% copy the mask file
238end
239
240%MAIN LOOP ON SLICES
241for islice=1:nbslice_i
242    %% select the series of image indices at the level islice
243    for ifield=1:nbfield
244        for iburst=1:nbfield2
245            indselect(iburst,ifield)=((ifield-1)*nbslice_i+(islice-1))*nbfield2+iburst;
246        end
247    end 
248   
249    %% read the first series of nbaver_ima images and sort by luminosity at each pixel
250    for ifield = 1:nbaver_ima
251        ifile=indselect(ifield);
252        filename=name_generator(filebase,num_i1(ifile),num_j1(ifile),Series.FileExt,Series.NomType);
253        Aread=read_image(filename,FileType,num_i1(ifile),MovieObject);
254        Ak(:,:,ifield)=Aread;           
255    end
256    Asort=sort(Ak,3);%sort the luminosity of images at each point
257    B=Asort(:,:,rank);%background image
258   display( 'first background image will be substracted')
259    for ifield=1:nbfirst
260            Acor=double(Ak(:,:,ifield))-double(B);%substract background to the current image
261            Acor=(Acor>0).*Acor; % put to 0 the negative elements in Acor
262            C=uint16(Acor);% set to integer 16 bits
263            ifile=indselect(ifield);
264            newname=name_generator(filebase_b,num_i1(ifile),num_j1(ifile),'.png',nom_type)% makes the new file name
265            if test_level
266                C=levels(C);
267                 imwrite(C,newname,'BitDepth',8); % save the new image
268            else
269                 imwrite(C,newname,'BitDepth',16); % save the new image
270            end
271    end
272   
273    %% repeat the operation on a sliding series of nbaver*nbfield2 images
274    display('sliding background image will be substracted')
275    if nbfield_slice > nbaver_ima
276        for ifield = step*ceil(nbaver/2)+1:step:nbfield_slice-step*floor(nbaver/2)
277            stopstate=get(hseries.RUN,'BusyAction');
278            if isequal(stopstate,'queue')% enable STOP command
279                update_waitbar(hseries.waitbar,WaitbarPos,(ifield+(islice-1)*nbfield_slice)/(nbfield_slice*nbslice_i))
280                (ifield+(islice-1)*nbfield_slice)/(nbfield_slice*nbslice_i)
281                Ak(:,:,[1:nbaver_ima-step])=Ak(:,:,[1+step:nbaver_ima]);% shift the current image series by one burst (step)
282                %incorporate next burst in the current image series
283                for iburst=1:step
284                    ifile=indselect(ifield+step*floor(nbaver/2)+iburst-1);
285                    filename=name_generator(filebase,num_i1(ifile),num_j1(ifile),Series.FileExt,Series.NomType);
286                    Aread=read_image(filename,FileType,num_i1(ifile),MovieObject);
287                    Ak(:,:,nbaver_ima-step+iburst)=Aread;
288                end
289                Asort=sort(Ak,3);%sort the new current image series by luminosity
290                B=Asort(:,:,rank);%current background image
291                for iburst=1:step
292                    index=step*floor(nbaver/2)+iburst;
293                    Acor=double(Ak(:,:,index))-double(B);
294                    Acor=(Acor>0).*Acor; % put to 0 the negative elements in Acor
295                    C=uint16(Acor);
296                    ifile=indselect(ifield+iburst-1);
297                    [newname]=...
298                        name_generator(filebase_b,num_i1(ifile),num_j1(ifile),'.png',Series.NomType) % makes the new file name
299                    if test_level
300                        C=levels(C);
301                        imwrite(C,newname,'BitDepth',8); % save the new image
302                    else
303                        imwrite(C,newname,'BitDepth',16); % save the new image
304                    end
305                end
306            else
307                return
308            end
309        end
310    end
311
312%% substract the background from the last images
313    display('last background image will be substracted')
314     ifield=nbfield_slice-(step*ceil(nbaver/2))+1:nbfield_slice;
315     for ifield=nbfield_slice-(step*floor(nbaver/2))+1:nbfield_slice
316         index=ifield-nbfield_slice+step*(2*floor(nbaver/2)+1);
317         Acor=double(Ak(:,:,index))-double(B);
318         Acor=(Acor>0).*Acor; % put to 0 the negative elements in Acor
319         C=uint16(Acor);
320         ifile=indselect(ifield);
321         newname=name_generator(filebase_b,num_i1(ifile),num_j1(ifile),'.png',nom_type)% makes the new file name
322         if test_level
323             C=levels(C);
324             imwrite(C,newname,'BitDepth',8); % save the new image
325         else
326             imwrite(C,newname,'BitDepth',16); % save the new image
327         end
328     end
329end
330
331%finish the waitbar
332update_waitbar(hseries.waitbar,WaitbarPos,1)
333
334
335%------------------------------------------------------------------------
336%--read images and convert them to the uint16 format used for PIV
337function A=read_image(filename,type_ima,num,MovieObject)
338%------------------------------------------------------------------------
339%num is the view number needed for an avi movie
340switch type_ima
341    case 'movie'
342        A=read(MovieObject,num);
343    case 'avi'
344        mov=aviread(filename,num);
345        A=frame2im(mov(1));
346    case 'multimage'
347        A=imread(filename,num);
348    case 'image'   
349        A=imread(filename);
350end
351siz=size(A);
352if length(siz)==3;%color images
353    A=sum(double(A),3);
354end
355   
356
357function C=levels(A)
358%whos A;
359B=double(A(:,:,1));
360windowsize=round(min(size(B,1),size(B,2))/20);
361windowsize=floor(windowsize/2)*2+1;
362ix=[1/2-windowsize/2:-1/2+windowsize/2];%
363%del=np/3;
364%fct=exp(-(ix/del).^2);
365fct2=cos(ix/(windowsize-1)/2*pi/2);
366%Mfiltre=(ones(5,5)/5^2);
367%Mfiltre=fct2';
368Mfiltre=fct2'*fct2;
369Mfiltre=Mfiltre/(sum(sum(Mfiltre)));
370
371C=filter2(Mfiltre,B);
372C(:,1:windowsize)=C(:,windowsize)*ones(1,windowsize);
373C(:,end-windowsize+1:end)=C(:,end-windowsize+1)*ones(1,windowsize);
374C(1:windowsize,:)=ones(windowsize,1)*C(windowsize,:);
375C(end-windowsize+1:end,:)=ones(windowsize,1)*C(end-windowsize,:);
376C=tanh(B./(2*C));
377[n,c]=hist(reshape(C,1,[]),100);
378% figure;plot(c,n);
379
380[m,i]=max(n);
381c_max=c(i);
382[dummy,index]=sort(abs(c-c(i)));
383n=n(index);
384c=c(index);
385i_select = find(cumsum(n)<0.95*sum(n));
386if isempty(i_select)
387    i_select = 1:length(c);
388end
389c_select=c(i_select);
390n_select=n(i_select);
391cmin=min(c_select);
392cmax=max(c_select);
393C=(C-cmin)/(cmax-cmin)*256;
394C=uint8(C);
Note: See TracBrowser for help on using the repository browser.