简介
视频图像序列处理方法中,差分算法以其高效性、简便性应用广泛。这里给出应用实例,并给出实验结果。
代码
% By lyqmath
clc; clear all; close all;
% 原始视频
targetavi = 'traffic.avi';
% 检测结果视频
resultavi = 'c:\\result.avi';
%% 读取视频
mov = mmreader(targetavi);
fnum = mov.NumberOfFrames;
%% 建立结果视频
aviobj = avifile(resultavi);
aviobj.Quality = 100;
aviobj.Fps = 25;
aviobj.compression = 'Indeo5';
%% 帧间差分法
figure(1);
for i = 2 : fnum
x = read(mov, i-1);
y = read(mov, i);
subplot(1, 2, 1); imshow(x, []); title(sprintf('第%d帧视频,By lyqmath', 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);
n = medfilt2(n);
% 数据类型转换
q = im2double(n);
w = im2double(m);
% 差分
c = q-w;
% 阈值,此值可以调节
t = 40/256;
% 阈值分割
c(abs(c)>=t)=255;
c(abs(c)<t) = 0;
c = logical(c);
x1 = x(:, :, 1); x2 = x(:, :, 2); x3 = x(:, :, 3);
x1(c) = 255; x2(c) = 0; x3(c) = 0;
xc = cat(3, x1, x2, x3);
subplot(1, 2, 2); imshow(xc, []); title(sprintf('第%d帧视频识别结果,By lyqmath', i-1), 'FontWeight', 'Bold', 'Color', 'r');
f = getframe(gcf);
f = frame2im(f);
% 生成视频
aviobj = addframe(aviobj, f);
end
%% 关闭视频句柄
aviobj = close(aviobj);
结果
http://blog.sina.com.cn/lyqmath