幀間差分法是一種通過對視頻圖像序列中相鄰兩幀作差分運算來獲得運動目標輪廓的方法,它可以很好地適用於存在多個運動目標和攝像機移動的情況。當監控場景中出現異常物體運動時,幀與幀之間會出現較為明顯的差別,兩幀相減,得到兩幀圖像亮度差的絕對值,判斷它是否大於閾值來分析視頻或圖像序列的運動特性,確定圖像序列中有無物體運動。
源代碼:請選擇.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);
閱讀更多 科研IT生活 的文章