[filename, pathname] = uigetfile({ '*.*'},'打开视频');
videoName = [pathname filename];
Objs=VideoReader(videoName);
Nums=Objs.NumberOfFrames;%读取视频的帧数
FrameRate=Objs.FrameRate;%每秒多少帧
%% <________________________vibe>%%
%% 设定参数
sample_num = 10; % 样本库
match_thres = 20; % 匹配阈值
frame_count = 0; % 处理帧数
neighbor = [1, 0, -1, -1, 1, 0, 0, -1, 1]; % 邻域选择
%% 判断是否为第一帧
first_flag = true;
for num=1:1:Nums
frame = read(Objs,num);
frame_gray = double(rgb2gray(frame));
if first_flag
first_flag = false;
%% 开始初始化
samples = cell(1, sample_num);
% 前两个样本设置初始像素
samples{1} = frame_gray;
samples{2} = frame_gray;
% 剩下的样本初始化
for i = 3:sample_num
samples{i} = frame_gray + double(floor(rand(rows, cols) * 20) - 10);
end
fore_count = uint8(zeros(rows, cols));
frame_count = frame_count + 1;
% 初始化结束
continue
end
%% 前景分割
fgMask = uint8(ones(rows, cols) * match_num);
for i = 1:sample_num
distance = uint8(abs(samples{i} - frame_gray) <= match_thres);
fgMask = fgMask - distance;
end
fgMask = logical(fgMask * 255);
% 更新前景计数
for r = 1 : rows
for c = 1:cols
if fgMask(r, c) == 1
fore_count(r, c) = fore_count(r, c) + 1;
if fore_count(r, c) >= fore_thres
fore_count(r,c) = 0;
fgMask(r, c) = 0;
end
else
fore_count(r, c) = 0;
end
end
end
updateMask = fgMask;
updateMask = imfill(updateMask, 'hole');
%% 更新样本库
% 一边更新前景计数,一边更新样本库
for r = 2:rows-1
for c = 2:cols-1
% 为背景时,更新背景样本库
if updateMask(r, c) == 0
fore_count(r, c) = 0;
% 有一定概率更新自身
if update_factor == 1 || floor(rand() * update_factor) == 0
samples{floor(rand() * sample_num) + 1}(r, c) = frame_gray(r, c);
end
% 也有一定概率更新周围像素样本库
if update_factor == 1 || floor(rand() * update_factor) == 0
samples{floor(rand() * sample_num) + 1}(r + neighbor(floor(rand() * 9) + 1), ...
c + neighbor(floor(rand() * 9) + 1)) = frame_gray(r, c);
end
end
end
end
frame_count = frame_count + 1;
if frame_count >= 50
update_factor = next_update_factor;
end
fgMask = imopen(fgMask, strel('rectangle', [3, 3]));
fgMask = imfill(fgMask, 'hole');
% subplot(1,2,1);
axes(handles.axes1);
imshow(frame);
drawnow;%刷新屏幕
%subplot(1,2,2);
%imshow(fgMask);
% drawnow;%刷新屏幕
A = zhixin(fgMask);
if num >4
if A >0
K = abs( W(num-2,1) - A);
if K>5
%%黑-》绿-》蓝-》-》红,风险等级依次提高
title('快跑中','Color','R');
%风险过高报警提示
fs=20000; %确定采样频率
t=0: 1/fs: 0.2; %t为音长
c=sin(6*pi*261.63 *t); %中央c的频率为261.63Hz
sound(c, fs);
elseif K>2.5
title('慢跑中','Color','B');
elseif K>0
title('步行中','Color','G');
else
title('静止中');
end
else
title('图像中无人');
end
pause(0.1);
end
end