帧差法代码

合集下载
相关主题
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

% By lyqmath @ Matlab中文论坛

clc; clear all; close all;

avi = mmreader('samplevideo.avi');

for i = 1 : avi.NumberOfFrames

img = read(avi, i);

pixels(:, :, :, i) = img;

figure(1); imshow(img, []);

text(1, 15, sprintf('原视频:%d帧By lyqmath', i), 'FontWeight', 'Bold', 'Color', 'r'); end

tracking(pixels);

function d = tracking(video)

if ischar(video)

% 载入视频数据

for i = 1 : avi.NumberOfFrames

img = read(avi, i);

pixels(:, :, :, i) = img;

end

else

pixels = video;

end

nFrames = size(pixels, 4);

rows = size(pixels, 1);

cols = size(pixels, 2);

% 转换成灰度图像

for i = 1 : nFrames

pixel(:, :, i) = (rgb2gray(pixels(:,:,:,i)));

end

for i = 2 : nFrames

d(:, :, i) = (abs(pixel(:,:,i) - pixel(:,:,i-1)));

bw(:, :, i) = im2bw(d(:, :, i), 0.2);

% 寻找上下边界

cou=1;

for h = 1:rows

for w = 1:cols

if bw(h, w, i) > 0.5

bottomEdge = h;

if cou == 1

topEdge = bottomEdge;

end

cou = cou+1;

break;

end

end

end

% 寻找左右边界

coun=1;

for w = 1:cols

for h = 1:rows

if bw(h, w, i) > 0.5

rightEdge = w;

if coun == 1

leftEdge = rightEdge;

coun = coun+1;

end

break;

end

end

end

% 矩形框生成

wd = rightEdge-leftEdge;

hg = bottomEdge-topEdge;

widt = wd/2;

heit = hg/2;

cenx = leftEdge+widt;

ceny = topEdge+heit;

% 显示并标记

figure(1);

imshow(pixels(:, :, :, i), []);

hold on

rectangle('Position',[leftEdge topEdge wd hg], 'EdgeColor', 'r', 'LineWidth', 2);

plot(cenx, ceny, 'ko', 'MarkerFaceColor', 'y', 'MarkerSize', 20, 'LineWidth', 2);

text(1, 15, sprintf('跟踪视频:%d帧By lyqmath', i), 'FontWeight', 'Bold', 'Color', 'r');

hold off

End

另一段代码

% 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;

pression = '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;

% 阈值,此值可以调节

相关文档
最新文档