帧间差分法是一种通过对视频图像序列中相邻两帧作差分运算来获得运动目标轮廓的方法,它可以很好地适用于存在多个运动目标和摄像机移动的情况。当监控场景中出现异常物体运动时,帧与帧之间会出现较为明显的差别,两帧相减,得到两帧图像亮度差的绝对值,判断它是否大于阈值来分析视频或图像序列的运动特性,确定图像序列中有无物体运动。
源代码:请选择.avi格式的视频
clc; clear all; close all;
% 原始视频
[file_name,pname] = uigetfile('*.avi','Select the M-file');
% file_name = 'campus5.avi'; %视频所在文件夹
file_name=[pname file_name];
mov = VideoReader(file_name);
% 检测结果视频
% resultavi = 'result1.avi';
%% 读取视频
% mov = VideoReader(targetavi);
fnum = mov.NumberOfFrames;
%% 建立结果视频
two_video= VideoWriter('twozhen.avi'); %所转换成的视频名称
writerFrames = fnum; %视频帧数
open(two_video);
%% 帧间差分法
% figure(1);
for i = 2 : fnum
x = read(mov, i-1);
y = read(mov, i);
subplot(2, 2, 1); imshow(x, []); title(sprintf('第%d帧视频', i-1), 'FontWeight', 'Bold', 'Color', 'r');
% 灰度化
if ndims(x) == 3
m = rgb2gray(x);
else
m = x;
end
if ndims(y) == 3
n = rgb2gray(y);
else
n = y;
end
% 中值滤波
m = medfilt2(m);
% pause(1);
n = medfilt2(n);
% 数据类型转换
q = im2double(n);
w = im2double(m);
% 差分
c = q-w;
% 阈值,此值可以调节
t = 50/256;
% 阈值分割
c(abs(c)>=t)=255;
c(abs(c)
c = logical(c);
hh=0;
[height, width]=size(c);
for row=11:height-10
for col=11:width-10
if c(row,col) == 1
dd=0;
for r1=-10:10
for r2=-10:10
if c(row+r1,col+r2)== 1
% dd=1/(1+abs(r1+r2))+dd;
dd=dd+1;
end
end
end
if dd<10
c(row,col)=0;
end
if dd>50
hh=hh+1;
end
end
end
end
tud(i)=hh;
subplot(2, 2, 2); imshow(c, []); title(sprintf('第%d帧视频识别结果', i-1), 'FontWeight', 'Bold', 'Color', 'r');
se90 = strel('line',7,90); % 第一个结构元素线型90度
se0 = strel('line',6,0); % 第二个结构元素线型0度
out = imdilate(c, [se90 se0]); % 膨胀前景图
se = strel('disk',5); % 第二个结构元素
out = imopen(out,se); % 开运算去除噪点
out = imclose(out,se);
subplot(2, 2, 3); imshow(out, []); title(sprintf('第%d帧视频识别结果', i-1), 'FontWeight', 'Bold', 'Color', 'r');
out=~out;
x1 = x(:, :, 1); x2 = x(:, :, 2); x3 = x(:, :, 3);
x1(out) =0; x2(out) = 0; x3(out) = 0;
xc = cat(3, x1, x2, x3);
subplot(2, 2, 4); imshow(xc, []); title(sprintf('第%d帧视频识别结果', i-1), 'FontWeight', 'Bold', 'Color', 'r');
writeVideo(two_video, xc);
% 生成视频
% aviobj = addframe(aviobj, f);
end
%% 关闭视频句柄
close(two_video);
a=size(tud);
t=1;
zhen=[];
for i=1:a(2)
if tud(i)>5
zhen(t)=i;
t=t+1;
end
end
save 8 zhen
%aviobj = close(aviobj);aviobj = close(aviobj);