MATLAB: How do we compute regionprops for frames of a video, in a loop, in MATLAB

framesimage processing in matlabloopsregionpropsvideo

I have a code to read and threshold frames from a video to get the all the frames in the required format. I've been trying to run regionprops on each frame in order to get the centroid of the only object in each frame. But I''m getting stuck with applying regionprops to all frames in a loop.
My code:
r = VideoReader('file.avi');
for f = 1:r.NumberOfFrames;
filename = strcat('frame',num2str(f),'.jpg'); %creating names of each frame
onlyRead = read(r,f); %read all frames from video
convertToGrayscale = rgb2gray(onlyRead); %convert all frames from color to grayscale
adjustContrast = imadjust(convertToGrayscale,[0 0.17]); %contrast adjust for better thresholding
cropToRequiredSize = imcrop(adjustContrast,[500 0 720 400]); %cropping out the unnecessary parts from each image altogether
BW = cropToRequiredSize > 200; %binarize the image using either global or adaptive thresholding
edgeDet = edge(BW); %edge detection
fillImage = imfill(edgeDet,'holes'); %filling all 'holes' in edge-detected object to compute image region properties
imwrite(fillImage,filename); %write out all frames per the above directions
end

Best Answer

r = VideoReader('file.avi');
centroids = zeros(r.numberOfFrames, 2);
for f = 1:r.NumberOfFrames;
%...

fillImage = imfill(edgeDet,'holes'); %filling all 'holes' in edge-detected object to compute image region properties
stats = regionpros(fillImage, 'Centroid');
assert(numel(stats) == 1, 'More (or less) than 1 object detected in frame %d', f);
centroids(f, :) = stats.Centroid;
%...
end
Note that your comment on the line
BW = cropToRequiredSize > 200; %binarize the image using either global or adaptive thresholding
is misleading. You're clearly using global thresholding. I would have used imbinarize to get the option of either thresholding method.
Related Question