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

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

bugs corrected in series fct taking into account new conventions

File size: 17.8 KB
Line 
1%'sub_background': substract background to an image series, used with series.fig
2%------------------------------------------------------------------------
3% function GUI_input=sub_background(Param)
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 (Param)
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('Param','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%% input parameters
60% read the xml file for batch case
61if ischar(Param) && ~isempty(find(regexp('Param','.xml$')))
62    Param=xml2struct(Param);
63else %  RUN case: parameters introduced as the input structure Param
64    hseries=guidata(Param.hseries);%handles of the GUI series
65    WaitbarPos=get(hseries.waitbar_frame,'Position');
66end
67filebase=fullfile(Param.InputTable{1,1},Param.InputTable{1,3});
68dir_images=Param.InputTable{1,1};
69NomType=Param.InputTable{1,4};
70FileExt=Param.InputTable{1,5};
71[filecell,i1_series,i2_series,j1_series,j2_series]=get_file_series(Param);
72if size(filecell,1)>1
73    msgbox_uvmat('WARNING','This function uses only the first input image series')
74    return
75end
76
77%%% TODO: update with the new conventions%%%%%%%%%%%%%%%%%
78%% determine input image type
79FileType=[];%default
80MovieObject=[];
81%FileExt=Series.FileExt;
82
83if isequal(lower(FileExt),'.avi')
84    hhh=which('mmreader');
85    if ~isequal(hhh,'')&& mmreader.isPlatformSupported()
86        MovieObject=mmreader(fullfile(RootPath,[RootFile FileExt]));
87        FileType='movie';
88    else
89        FileType='avi';
90    end
91elseif isequal(lower(FileExt),'.vol')
92    FileType='vol';
93else
94    form=imformats(FileExt(2:end));
95    if ~isempty(form)% if the extension corresponds to an image format recognized by Matlab
96        if isequal(NomType,'*');
97            FileType='multimage';
98        else
99            FileType='image';
100        end
101    end
102end
103if isempty(FileType)
104    msgbox_uvmat('ERROR',['invalid file extension ' FileExt ': this function only accepts image or movie input'])
105    return
106end
107
108nbslice_i=Param.NbSlice; %number of slices
109siz=size(i1_series{1});
110nbaver_init=23;%approximate number of images used for the sliding background: to be adjusted later to include an integer number of bursts
111j1=[];%default
112
113%% apply the image rescaling function 'level' (avoid the blinking effects of bright particles)
114answer=msgbox_uvmat('INPUT_Y-N','apply image rescaling function levels.m after sub_background');
115test_level=isequal(answer,'Yes');
116
117%% adjust the proposed number of images in the sliding average to include an integer number of bursts
118if siz(2)~=1
119    nbaver=floor(nbaver_init/siz(1)); % number of bursts used for the sliding background,
120    if isequal(floor(nbaver/2),nbaver)
121        nbaver=nbaver+1;%put the number of burst to an odd number (so the middle burst is defined)
122    end
123    nbaver_init=nbaver*siz(1);%propose by default an integer number of bursts
124end
125
126%% create dir of the new images
127% [dir_images,namebase]=fileparts(filebase);
128if test_level
129    term='_b_levels';
130else
131    term='_b';
132end
133[pp,subdir_ima]=fileparts(Param.InputTable{1,1});
134try
135    mkdir([dir_images term]);
136catch ME
137    msgbox_uvmat('ERROR',ME.message);
138    return
139end
140[xx,msg2] = fileattrib([dir_images term],'+w','g'); %yield writing access (+w) to user group (g)
141if ~strcmp(msg2,'')
142    msgbox_uvmat('ERROR',['pb of permission for ' subdir_ima term ': ' msg2])%error message for directory creation
143    return
144end
145filebase_b=fullfile([dir_images term],Param.InputTable{1,3});
146
147%% set processing parameters
148prompt = {'Number of images for the sliding background (MUST FIT IN COMPUETER MEMORY)';'The number of positions (laser slices)';'volume scan mode (Yes/No)';...
149    'the luminosity rank chosen to define the background (0.1=for dense particle seeding, 0.5 (median) for sparse particles'};
150dlg_title = ['get (slice by slice) a sliding background and substract to each image, result in subdir ' subdir_ima term];
151num_lines= 3;
152def     = { num2str(nbaver_init);num2str(nbslice_i);'No';'0.1'};
153answer = inputdlg(prompt,dlg_title,num_lines,def);
154set(hseries.ParamVal,'String',answer([1 [3:4]]))
155set(hseries.ParamVal,'Visible','on')
156
157nbaver_ima=str2num(answer{1});%number of images for the sliding background
158nbaver=ceil(nbaver_ima/siz(1));%number of bursts for the sliding background
159if isequal(floor(nbaver/2),nbaver)
160    nbaver=nbaver+1;%put the number of burst to an odd number (so the middle burst is defined)
161end
162step=siz(1);%case of bursts: the sliding background is shifted by one burst
163vol_test=answer{3};
164if isequal(vol_test,'Yes')
165    nbfield2=1;%case of volume: no consecutive series at a given level
166    nbslice_i=siz(1);%number of slices
167else
168    nbfield2=siz(1); %nb of consecutive images at each level(burst)
169    if siz(2)>1
170        % nbslice_i=str2num(answer{2})/(num_i1(1,2)-num_i1(1,1));% number of slices
171        nbslice_i=str2num(answer{2})/(i1_series{1}(1,2)-i1_series{1}(1,1));% number of slices
172    else
173        nbslice_i=1;
174    end
175    if ~isequal(floor(nbslice_i),nbslice_i)
176        msgbox_uvmat('ERROR','the number of slices must be a multiple of the i increment')
177        return
178    end
179end
180rank=floor(str2num(answer{4})*nbaver_ima);
181if rank==0
182    rank=1;%rank selected in the sorted image series
183end
184lengthtot=siz(1)*siz(2);
185nbfield=floor(lengthtot/(nbfield2*nbslice_i));%total number of i indexes (adjusted to an integer number of slices)
186nbfield_slice=nbfield*nbfield2;% number of fields per slice
187if nbaver_ima > nbfield*nbfield2
188    msgbox_uvmat('ERROR','number of images in a slice smaller than the proposed number of images for the sliding average')
189    return
190end
191nbfirst=(ceil(nbaver/2))*step;
192if nbfirst>nbaver_ima
193    nbfirst=ceil(nbaver_ima/2);
194    step=1;
195    nbaver=nbaver_ima;
196end
197
198%% prealocate memory for the sliding background
199% first_image=name_generator(filebase,num_i1(1),num_j1(1),FileExt,NomType);
200% Afirst=read_image(first_image,FileType,num_i1(1),MovieObject);
201Afirst=read_image(filecell{1,1},FileType,i1_series{1}(1),MovieObject);
202[npy,npx]=size(Afirst);
203try
204    Ak=zeros(npy,npx,nbaver_ima,'uint16'); %prealocate memory
205    Asort=zeros(npy,npx,nbaver_ima,'uint16'); %prealocate memory
206catch ME
207    msgbox_uvmat('ERROR',ME.message)
208    return
209end
210
211%% copy the xml file
212if exist([filebase '.xml'],'file')
213    copyfile([filebase '.xml'],[filebase_b '.xml']);% copy the .civ file
214    t=xmltree([filebase_b '.xml']);
215   
216    %update information on the first image name in the series
217    uid_Heading=find(t,'ImaDoc/Heading');
218    if isempty(uid_Heading)
219        [t,uid_Heading]=add(t,1,'element','Heading');
220    end
221    uid_ImageName=find(t,'ImaDoc/Heading/ImageName');
222    if ~isempty(j1_series{1})
223        j1=j1_series{1}(1);
224    end
225    ImageName=fullfile_uvmat([dir_images term],'',Param.InputTable{1,3},'.png',NomType,i1_series{1}(1),[],j1);
226    %     ImageName=name_generator(filebase_b,num_i1(1),num_j1(1),'.png',NomType);
227    [pth,ImageName]=fileparts(ImageName);
228    ImageName=[ImageName '.png'];
229    if isempty(uid_ImageName)
230        [t,uid_ImageName]=add(t,uid_Heading,'element','ImageName');
231    end
232    uid_value=children(t,uid_ImageName);
233    if isempty(uid_value)
234        t=add(t,uid_ImageName,'chardata',ImageName);%indicate  name of the first image, with ;png extension
235    else
236        t=set(t,uid_value(1),'value',ImageName);%indicate  name of the first image, with ;png extension
237    end
238   
239    %add information about image transform
240    [t,new_uid]=add(t,1,'element','ImageTransform');
241    [t,NameFunction_uid]=add(t,new_uid,'element','NameFunction');
242    [t]=add(t,NameFunction_uid,'chardata','sub_background');
243    if test_level
244        [t,NameFunction_uid]=add(t,new_uid,'element','NameFunction');
245        [t]=add(t,NameFunction_uid,'chardata','levels');
246    end
247    [t,NbSlice_uid]=add(t,new_uid,'element','NbSlice');
248    [t]=add(t,new_uid,'chardata',num2str(nbslice_i));
249    [t,NbSlidingImages_uid]=add(t,new_uid,'element','NbSlidingImages');
250    [t]=add(t,NbSlidingImages_uid,'chardata',num2str(nbaver));
251    [t,LuminosityRank_uid]=add(t,new_uid,'element','RankBackground');
252    [t]=add(t,LuminosityRank_uid,'chardata',num2str(rank));% luminosity rank almong the nbaver sliding images
253    save(t,[filebase_b '.xml'])
254elseif exist([filebase '.civ'],'file')
255    copyfile([filebase '.civ'],[filebase_b '.civ']);% copy the .civ file
256end
257%copy the mask
258if exist([filebase '_1mask_1'],'file')
259    copyfile([filebase '_1mask_1'],[filebase_b '_1mask_1']);% copy the mask file
260end
261
262%MAIN LOOP ON SLICES
263
264for islice=1:nbslice_i
265    %% select the series of image indices at the level islice
266    for ifield=1:nbfield
267        for iburst=1:nbfield2
268            indselect(iburst,ifield)=((ifield-1)*nbslice_i+(islice-1))*nbfield2+iburst;
269        end
270    end
271   
272    %% read the first series of nbaver_ima images and sort by luminosity at each pixel
273    for ifield = 1:nbaver_ima
274        ifile=indselect(ifield);
275        filename=filecell{1,ifile};
276        % filename=name_generator(filebase,num_i1(ifile),num_j1(ifile),FileExt,NomType);
277        Aread=read_image(filename,FileType,i1_series{1}(ifile),MovieObject);
278        Ak(:,:,ifield)=Aread;
279    end
280    Asort=sort(Ak,3);%sort the luminosity of images at each point
281    B=Asort(:,:,rank);%background image
282    display( 'first background image will be substracted')
283    for ifield=1:nbfirst
284        Acor=double(Ak(:,:,ifield))-double(B);%substract background to the current image
285        Acor=(Acor>0).*Acor; % put to 0 the negative elements in Acor
286        C=uint16(Acor);% set to integer 16 bits
287        ifile=indselect(ifield);
288        %             newname=name_generator(filebase_b,num_i1(ifile),num_j1(ifile),'.png',NomType)% makes the new file name
289        if ~isempty(j1_series{1})
290            j1=j1_series{1}(ifile);
291        end
292        newname=fullfile_uvmat([dir_images term],'',Param.InputTable{1,3},'.png',NomType,i1_series{1}(ifile),[],j1);
293        %newname=name_generator(filebase_b,i1_series{1}(ifile),j1_series{1}(ifile),'.png',NomType);% makes the new file name
294        if test_level
295            C=levels(C);
296            imwrite(C,newname,'BitDepth',8); % save the new image
297        else
298            imwrite(C,newname,'BitDepth',16); % save the new image
299        end
300    end
301   
302    %% repeat the operation on a sliding series of nbaver*nbfield2 images
303    display('sliding background image will be substracted')
304    if nbfield_slice > nbaver_ima
305        for ifield = step*ceil(nbaver/2)+1:step:nbfield_slice-step*floor(nbaver/2)
306            stopstate=get(hseries.RUN,'BusyAction');
307            if isequal(stopstate,'queue')% enable STOP command
308                update_waitbar(hseries.waitbar,WaitbarPos,(ifield+(islice-1)*nbfield_slice)/(nbfield_slice*nbslice_i))
309                display((ifield+(islice-1)*nbfield_slice)/(nbfield_slice*nbslice_i))
310                Ak(:,:,1:nbaver_ima-step)=Ak(:,:,1+step:nbaver_ima);% shift the current image series by one burst (step)
311                %incorporate next burst in the current image series
312                for iburst=1:step
313                    ifile=indselect(ifield+step*floor(nbaver/2)+iburst-1);
314                    filename=name_generator(filebase,num_i1(ifile),num_j1(ifile),FileExt,NomType);
315                    Aread=read_image(filename,FileType,num_i1(ifile),MovieObject);
316                    Ak(:,:,nbaver_ima-step+iburst)=Aread;
317                end
318                Asort=sort(Ak,3);%sort the new current image series by luminosity
319                B=Asort(:,:,rank);%current background image
320                for iburst=1:step
321                    index=step*floor(nbaver/2)+iburst;
322                    Acor=double(Ak(:,:,index))-double(B);
323                    Acor=(Acor>0).*Acor; % put to 0 the negative elements in Acor
324                    C=uint16(Acor);
325                    ifile=indselect(ifield+iburst-1);
326                    if ~isempty(j1_series{1})
327                        j1=j1_series{1}(ifile);
328                    end
329                    newname=fullfile_uvmat([dir_images term],'',Param.InputTable{1,3},'.png',NomType,i1_series{1}(ifile),[],j1);
330                    %[newname]=name_generator(filebase_b,num_i1(ifile),num_j1(ifile),'.png',NomType) % makes the new file name
331                    if test_level
332                        C=levels(C);
333                        imwrite(C,newname,'BitDepth',8); % save the new image
334                    else
335                        imwrite(C,newname,'BitDepth',16); % save the new image
336                    end
337                end
338            else
339                return
340            end
341        end
342    end
343   
344    %% substract the background from the last images
345    display('last background image will be substracted')
346    ifield=nbfield_slice-(step*ceil(nbaver/2))+1:nbfield_slice;
347    for ifield=nbfield_slice-(step*floor(nbaver/2))+1:nbfield_slice
348        index=ifield-nbfield_slice+step*(2*floor(nbaver/2)+1);
349        Acor=double(Ak(:,:,index))-double(B);
350        Acor=(Acor>0).*Acor; % put to 0 the negative elements in Acor
351        C=uint16(Acor);
352        ifile=indselect(ifield);
353        if ~isempty(j1_series{1})
354            j1=j1_series{1}(ifile);
355        end
356        newname=fullfile_uvmat([dir_images term],'',Param.InputTable{1,3},'.png',NomType,i1_series{1}(ifile),[],j1);
357        %newname=name_generator(filebase_b,num_i1(ifile),num_j1(ifile),'.png',NomType);% makes the new file name
358        if test_level
359            C=levels(C);
360            imwrite(C,newname,'BitDepth',8); % save the new image
361        else
362            imwrite(C,newname,'BitDepth',16); % save the new image
363        end
364    end
365end
366
367%finish the waitbar
368update_waitbar(hseries.waitbar,WaitbarPos,1)
369
370
371%------------------------------------------------------------------------
372%--read images and convert them to the uint16 format used for PIV
373function A=read_image(filename,type_ima,num,MovieObject)
374%------------------------------------------------------------------------
375%num is the view number needed for an avi movie
376switch type_ima
377    case 'movie'
378        A=read(MovieObject,num);
379    case 'avi'
380        mov=aviread(filename,num);
381        A=frame2im(mov(1));
382    case 'multimage'
383        A=imread(filename,num);
384    case 'image'   
385        A=imread(filename);
386end
387siz=size(A);
388if length(siz)==3;%color images
389    A=sum(double(A),3);
390end
391   
392
393function C=levels(A)
394%whos A;
395B=double(A(:,:,1));
396windowsize=round(min(size(B,1),size(B,2))/20);
397windowsize=floor(windowsize/2)*2+1;
398ix=1/2-windowsize/2:-1/2+windowsize/2;%
399%del=np/3;
400%fct=exp(-(ix/del).^2);
401fct2=cos(ix/(windowsize-1)/2*pi/2);
402%Mfiltre=(ones(5,5)/5^2);
403%Mfiltre=fct2';
404Mfiltre=fct2'*fct2;
405Mfiltre=Mfiltre/(sum(sum(Mfiltre)));
406
407C=filter2(Mfiltre,B);
408C(:,1:windowsize)=C(:,windowsize)*ones(1,windowsize);
409C(:,end-windowsize+1:end)=C(:,end-windowsize+1)*ones(1,windowsize);
410C(1:windowsize,:)=ones(windowsize,1)*C(windowsize,:);
411C(end-windowsize+1:end,:)=ones(windowsize,1)*C(end-windowsize,:);
412C=tanh(B./(2*C));
413[n,c]=hist(reshape(C,1,[]),100);
414% figure;plot(c,n);
415
416[m,i]=max(n);
417c_max=c(i);
418[dummy,index]=sort(abs(c-c(i)));
419n=n(index);
420c=c(index);
421i_select = find(cumsum(n)<0.95*sum(n));
422if isempty(i_select)
423    i_select = 1:length(c);
424end
425c_select=c(i_select);
426n_select=n(i_select);
427cmin=min(c_select);
428cmax=max(c_select);
429C=(C-cmin)/(cmax-cmin)*256;
430C=uint8(C);
Note: See TracBrowser for help on using the repository browser.