Filter löschen
Filter löschen

Looping, or running the LSPIV.m code (from github) on all the files in a folder

4 Ansichten (letzte 30 Tage)
Hi all,
So I am having troubling running my LSPIV.m code on all the ".tif" files in my folder. Line 39-46 (%% Import the data from a multi-frame tif and make into a single array) is written so it selects one file and runs the remaining lines of on code that one file; however, I am swarmed with data and I was hoping I can loop the code to run on all files within a folder.
Is there a way to do this so that it can run this without problems?
Code:
% LSPIV with no parallel processing enabled.
%
% This file is to illustrate how the technique works, showing the gaussian
% peak fitting in real time during calculation. The speed of the technique
% is limited by this non-linear fitting step. The speed of the technique can
% be sped up through parallelization (our approach -- see LSPIV_parallel.m)
% or a more efficient algorithm.
%
% For additional information, please see corresponding paper:
%
% 'Line-Scanning Particle Image Velocimetry: an Optical Approach for
% Quantifying a Wide Range of Blood Flow Speeds in Live Animals'
% by Tyson N. Kim, Patrick W. Goodwill, Yeni Chen, Steven M. Conolly, Chris
% B. Schaffer, Dorian Liepmann, Rong A. Wang
%
% PWG 3/28/2012
close all
% Parameters to improve fits
maxGaussWidth = 100; % maximum width of peak during peak fitting
% Judge correctness of fit
numstd = 3; %num of stdard deviation from the mean before flagging
windowsize = 2600; %in # scans, this will be converted to velocity points
%if one scan is 1/2600 s, then windowsize=2600 means
%a 1 second moving window. Choose the window size
%according to experiment.
%% settings
% Ask user for setting
speedSetting = 3; % USER SETTING
disp('settings are hard coded in the script, see script!');
numavgs = 100; %up to 100 (or more) for noisy or slow data
skipamt = 25; %if it is 2, it skips every other point. 3 = skips 2/3rds of points, etc.
shiftamt = 2;
%% Import the data from a multi-frame tif and make into a single array
% The goal is a file format that is one single array,
% so modify this section to accomodate your raw data format.
%
% This particular file format assumes
disp('import raw data');
[fname,pathname]=uigetfile('*.TIF','pick a linescan file');%loads file
if fname == 0; beep; disp('Cancelled'); end
imageLines = imimportTif([pathname fname])';
%% choose where in the image to process
imagesc(imageLines(1:size(imageLines,2),:))
colormap('gray')
startColumn = round(min(X1, X2)); % Defines what part of the image we perform LSPIV on.
endColumn = round(max(X1, X2));
%% minus out background signal (PWG 6/4/2009)
tic
disp('DC correction')
DCoffset = sum(imageLines,1) / size(imageLines,1);
imageLinesDC = imageLines - repmat(DCoffset,size(imageLines,1),1);
%% do LSPIV correlation
disp('LSPIV begin');
scene_fft = fft(imageLinesDC(1:end-shiftamt,:),[],2);
test_img = zeros(size(scene_fft));
test_img(:,startColumn:endColumn) = imageLinesDC(shiftamt+1:end, startColumn:endColumn);
test_fft = fft(test_img,[],2);
W = 1./sqrt(abs(scene_fft)) ./ sqrt(abs(test_fft)); % phase only
LSPIVresultFFT = scene_fft .* conj(test_fft) .* W;
LSPIVresult = ifft(LSPIVresultFFT,[],2);
disp('LSPIV complete');
%% find shift amounts
disp('Find the peaks');
velocity = [];
maxpxlshift = round(size(imageLines,2)/2)-1;
index_vals = skipamt:skipamt:(size(LSPIVresult,1) - numavgs);
numpixels = size(LSPIVresult,2);
velocity = nan(size(index_vals));
amps = nan(size(index_vals));
sigmas = nan(size(index_vals));
goodness = nan(size(index_vals));
%% iterate through
close all
for index = 1:length(index_vals)
if mod(index_vals(index),100) == 0
fprintf('line: %d\n',index_vals(index))
end
LSPIVresultAVG = fftshift(sum(LSPIVresult(index_vals(index):index_vals(index)+numavgs,:),1)) ...
/ max(sum(LSPIVresult(index_vals(index):index_vals(index)+numavgs,:),1));
% find a good guess for the center
c = zeros(1, numpixels);
c(numpixels/2-maxpxlshift:numpixels/2+maxpxlshift) = ...
LSPIVresultAVG(numpixels/2-maxpxlshift:numpixels/2+maxpxlshift);
[maxval, maxindex] = max(c);
% fit a guassian to the xcorrelation to get a subpixel shift
options = fitoptions('gauss1');
options.Lower = [0 numpixels/2-maxpxlshift 0 0];
options.Upper = [1e9 numpixels/2+maxpxlshift maxGaussWidth 1];
options.StartPoint = [1 maxindex 10 .1];
[q,good] = fit((1:length(LSPIVresultAVG))',LSPIVresultAVG','a1*exp(-((x-b1)/c1)^2) + d1',options);
%save the data
velocity(index) = (q.b1 - size(LSPIVresult,2)/2 - 1)/shiftamt;
amps(index) = q.a1;
sigmas(index) = q.c1;
goodness(index) = good.rsquare;
% plot the data out
figure(1)
subplot(1,2,1)
hold off
plot(LSPIVresultAVG);
hold all
plot(q);
xlim([1 numpixels]);
ylim([0 1]);
subplot(1,2,2)
plot(index_vals,velocity)
title('displacement [pixels/scan]');
ylabel('pixel shift');
xlabel('scan number');
pause(.01);
end
%% find possible bad fits
toc
% Find bad velocity points using a moving window
pixel_windowsize = round(windowsize / skipamt);
badpixels = zeros(size(velocity));
for index = 1:1:length(velocity)-pixel_windowsize
pmean = mean(velocity(index:index+pixel_windowsize-1)); %partial window mean
pstd = std(velocity(index:index+pixel_windowsize-1)); %partial std
pbadpts = find((velocity(index:index+pixel_windowsize-1) > pmean + pstd*numstd) | ...
(velocity(index:index+pixel_windowsize-1) < pmean - pstd*numstd));
badpixels(index+pbadpts-1) = badpixels(index+pbadpts-1) + 1; %running sum of bad pts
end
badvals = find(badpixels > 0); % turn pixels into indicies
goodvals = find(badpixels == 0);
meanvel = mean(velocity(goodvals)); %overall mean
stdvel = std(velocity(goodvals)); %overall std
% show results
figure(2)
subplot(3,1,1)
imgtmp = zeros([size(imageLines(:,startColumn:endColumn),2) size(imageLines(:,startColumn:endColumn),1) 3]); % to enable BW and color simultaneously
imgtmp(:,:,1) = imageLines(:,startColumn:endColumn)'; imgtmp(:,:,2) = imageLines(:,startColumn:endColumn)'; imgtmp(:,:,3) = imageLines(:,startColumn:endColumn)';
imagesc(imgtmp/max(max(max(imgtmp))))
title('Raw Data');
ylabel('[pixels]');
%colormap('gray');
subplot(3,1,2)
imagesc(index_vals,-numpixels/2:numpixels/2,fftshift(LSPIVresult(:,:),2)');
title('LSPIV xcorr');
ylabel({'displacement'; '[pixels/scan]'});
subplot(3,1,3)
plot(index_vals, velocity,'.');
hold all
plot(index_vals(badvals), velocity(badvals), 'ro');
hold off
xlim([index_vals(1) index_vals(end)]);
ylim([meanvel-stdvel*4 meanvel+stdvel*4]);
title('Fitted Pixel Displacement');
ylabel({'displacement'; '[pixels/scan]'});
xlabel('index [pixel]');
h = line([index_vals(1) index_vals(end)], [meanvel meanvel]);
set(h, 'LineStyle','--','Color','k');
h = line([index_vals(1) index_vals(end)], [meanvel+stdvel meanvel+stdvel]);
set(h, 'LineStyle','--','Color',[.5 .5 .5]);
h = line([index_vals(1) index_vals(end)], [meanvel-stdvel meanvel-stdvel]);
set(h, 'LineStyle','--','Color',[.5 .5 .5]);
fprintf('\nMean Velocity %0.2f [pixels/scan]\n', meanvel);
fprintf('Stdev Velocity %0.2f [pixels/scan]\n', stdvel);
xlfname = 'BL1.xlsx'; filename = convertCharsToStrings(fname);
d1 = [filename, meanvel, stdvel]; writematrix(d1, xlfname, 'WriteMode','append');

Antworten (1)

Walter Roberson
Walter Roberson am 23 Nov. 2023
[fname,pathname]=uigetfile('*.TIF','pick a linescan file');%loads file
If you set the Multiselect option, then the output variable fname will be one of three types
  • numeric (in particular 0), which signals that the user cancelled. Make sure you error() or return to caller or otherwise do not execute the rest of the code (your current version executes the rest of the code.)
  • character vector. The user selected exactly one file.
  • cell array of character vectors. The user selected multiple files.
The easiest way to deal with character vector vs cell array, is that after you have ensured that the user did not cancel, then use
fname = cellstr(fname);
If fname was already a cell array (because the user selected multiple) then it will not be changed; if it was a character vector (because the user selected only one) then the character vector will be wrapped in a cell.
Now that you have a cell array of character vectors, you can loop 1 to the number of entries in the cell.
It is recommended that you do not strcat() or [] together parts of file names. Convert
imageLines = imimportTif([pathname fname])';
to
thisfile = fullfile(pathname, fname{K}); %assuming you used for K = 1 : length(fname)
imageLines = imimportTif(thisfile).';

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by