Tracking Using Optical Flow
Tracking Using Optical Flow
hcr = video.ChromaResampler(...
'Resampling', '4:2:0 (MPEG1) to 4:4:4', ...
'InterpolationFilter', 'Pixel replication');
hmean1 = video.Mean;
hmean2 = video.Mean('RunningMean', true);
hmedianfilt = video.MedianFilter2D;
while ~isDone(hbfr)
[y, cb, cr] = step(hbfr); % Read input video frame
[cb, cr] = step(hcr, cb, cr);
imrgb = step(hcsc1, cat(3,y,cb,cr)); % Convert image from YCbCr to RGB
image = step(hidtc, imrgb); % Convert image to single
I = step(hcsc2, image); % Convert color image to intensity
of = step(hof, I); % Estimate optical flow
% Threshold the image and then filter it to remove fine speckle noise.
filteredout = step(hmedianfilt, y1 >= vel_th);
% Regional Filtering.
% Estimate the area and bounding box of the blobs in the thresholded
% image.
[area, bbox] = step(hblob, th_image);
% Select those boxes which are in our ROI.
Idx = bbox(1,:) > line_row;
% The next lines of code exclude other objects (like parts of the road)
% which are also segmented as blobs and select only cars. When the
% ratio between the area of the blob and the area of the bounding box
% is above 0.4 (40%), it is considered as a car and hence the bounding
% box for that object is used. Otherwise the bounding box is removed.
ratio = zeros(1, length(Idx));
ratio(Idx) = single(area(1,Idx))./single(bbox(3,Idx).*bbox(4,Idx));
ratiob = ratio > 0.4;
count = int32(sum(ratiob)); % Number of cars
bbox(:, ~ratiob) = int32(-1);
% Display the number of cars tracked and a white line showing ROI.
y2(22:23,:,:) = 1; % The white line.
y2(1:15,1:30,:) = 0; % Background for displaying count
image_out = step(htextins, y2, count);