MATLAB: How to save the centroids and area of connected components of an image in a matrix

computer visiondigital image processingimage processingImage Processing Toolbox

I have a video,I am extracting its frames and I need to find the connected components of every frame of that video and also find the centroid of the connected components along with their corresponding pixel size.I am running a loop to do this.I want to save the centroids and pixel size in a matrix but I couldn't do that.How to do this?Below is the code-
vidobj=VideoReader('cloud.mp4');
Frame_No=vidobj.NumberOfFrames;
for i=1:NumberOfFrames
imwrite(read(vidobj,i),strcat('C:\Users\PRACKKZ\Documents\MATLAB\cloudframes\',num2str(i),'.png'))
end
for i=1:NoOfFrames
rgb=imread(strcat('C:\Users\PRACKKZ\Documents\MATLAB\cloudframes\',num2str(i),'.png'));
I=imresize(rgb,[512 512]);
bw = im2bw(I);
CC=bwconncomp(bw);
lab=labelmatrix(CC);
props = regionprops(lab, 'Centroid', 'Area');
After this I don't know how to save centroid and pixel size.

Best Answer

props is a structure array with two fields: Centroid and Area. For example, if you have 3 blobs, you'll have props(1).Centroid, props(1).Area, props(2).Centroid, props(2).Area, props(3).Centroid, and props(3).Area. Now Centroid is an vector of two doubles that are x and y centroid locations for that blob.
Now each frame could have a different number of blobs in it. Frame #1 might have 2 blobs but frame #73 might have 5 blobs in it. So since you'd need to save 2 centroids in one case and 5 centroids in the other case, you can either create a double array in advance with enough space to hold as many blobs as you ever expect to encounter, OR you can use a cell array. For the cell array approach, you might try something like this (untested):
for f = 1 : numFrames
% code to get props for this frame. Then...
theseCentroids = [props.Centroid];
% Get x and y for this frame only.
xCentroids = theseCentroids(1 : 2 : end);
yCentroids = theseCentroids(2 : 2 : end);
caCentroids{f} = [xCentroids; yCentroids];
end
Now caCentroids is a cell array where each cell is a 2 by N array of doubles where the first row is the x centroid values and the second row is the y centroids. Note that caCentroids{1} (for frame 1) might contain different sized arrays that caCentroids{2} if frame 1 and frame 2 don't both have the same number of blobs in them.