redThresh = 0.25;
vidDevice = imaq.VideoDevice('winvideo', 1, 'YUY2_320x240', ...
'ROI', [1 1 320 240], ...
'ReturnedColorSpace', 'rgb');
VidDevice.FrameRate = '30.0000';
vidInfo = imaqhwinfo(vidDevice);
hblob = vision.BlobAnalysis('AreaOutputPort', false, ...
'CentroidOutputPort', true, ...
'BoundingBoxOutputPort', true', ...
'MinimumBlobArea', 400, ...
'MaximumBlobArea', 3000, ...
'MaximumCount', 1);
hshapeinsRedBox = vision.ShapeInserter('BorderColor', 'Custom', ...
'CustomBorderColor', [1 0 0], ...
'Fill', true, ...
'FillColor', 'Custom', ...
'CustomFillColor', [1 0 0], ...
'Opacity', 0.4);
htextins = vision.TextInserter('Text', 'Number of Red Object: %2d', ...
'Location', [7 2], ...
'Color', [1 0 0], ...
'FontSize', 12);
htextinsCent = vision.TextInserter('Text', '+ X:%4d, Y:%4d', ...
'LocationSource', 'Input port', ...
'Color', [1 1 0], ...
'FontSize', 14);
hVideoIn = vision.VideoPlayer('Name', 'Final Video', ...
'Position', [300 300 vidInfo.MaxWidth+20 vidInfo.MaxHeight+30]);
nFrame = 0;
center = [0 0];
k = 0;
A = [0 0];
while(nFrame < 300);
rgbFrame = step(vidDevice);
rgbFrame = flipdim(rgbFrame,2);
diffFrame = imsubtract(rgbFrame(:,:,1), rgb2gray(rgbFrame));
diffFrame = medfilt2(diffFrame, [3 3]);
binFrame = im2bw(diffFrame, redThresh);
[centroid, bbox] = step(hblob, binFrame);
centroid = uint16(centroid);
rgbFrame(1:20,1:165,:) = 0;
vidIn = step(hshapeinsRedBox, rgbFrame, bbox);
for object = 1:1:length(bbox(:,1))
k = k+1
if isempty(hblob)
center(k+1,:) = [161 121];
else
centX = centroid(object,1); centY = centroid(object,2);
center(k+1,:) = [centX centY];
end
vidIn = step(htextinsCent, vidIn, [centX centY], [centX-6 centY-9]);
end
vidIn = step(htextins, vidIn, uint8(length(bbox(:,1))));
step(hVideoIn, vidIn);
nFrame = nFrame+1;
end
release(hVideoIn);
release(vidDevice);
clc;