赞
踩
clc; clear; video = VideoReader('4.mp4'); %读取视频 vidHeight = video.Height; %视频高度 vidWidth = video.Width; %视频宽度 nFrames = video.NumberOfFrames-5; %视频总帧数(去掉了一些不必要的东西) s = read(video,[1,nFrames]); %获取所有视频帧 % 储存背景图像矩阵 r = zeros(vidHeight,vidWidth); g = zeros(vidHeight,vidWidth); b = zeros(vidHeight,vidWidth); % 提取背景图像 for i=1:nFrames img = s(:,:,:,i); R = double(img(:,:,1)); G = double(img(:,:,2)); B = double(img(:,:,3)); r = r + R/(nFrames-1); g = g + G/(nFrames-1); b = b + B/(nFrames-1); end r = uint8(r); g = uint8(g); b = uint8(b); % 显示背景图片 % Img(:,:,1) = uint8(r); % Img(:,:,2) = uint8(g); % Img(:,:,3) = uint8(b); % imshow(Img); % 实际背景图片(纯白)(useless) background = uint8(255 * ones(vidHeight,vidWidth,3)); % 寻找目标区域 for k=1:nFrames % img = s(:,:,:,k); x = uint16([]); y = uint16([]); % 获取对应的像素点数组(x,y) for i=1:vidHeight for j=1:vidWidth % 实际检测条件: (s(i,j,1,k)-r(i,j))>20 && (s(i,j,2,k)-g(i,j))>20 && (s(i,j,3,k)-b(i,j))>70 if ((255-s(i,j,1,k))<20 && (255-s(i,j,2,k))>230 && (255-s(i,j,3,k))>230) x = [x i]; y = [y j]; end end end % 绘制矩形框(宽2像素) max_x = max(max(x)); max_y = max(max(y)); min_x = min(min(x)); min_y = min(min(y)); for m=min_x:max_x s(m,min_y,1,k) = 0;s(m,min_y,2,k) = 0;s(m,min_y,3,k) = 0; s(m,min_y-1,1,k) = 0;s(m,min_y-1,2,k) = 0;s(m,min_y-1,3,k) = 0; s(m,max_y,1,k) = 0;s(m,max_y,2,k) = 0;s(m,max_y,3,k) = 0; s(m,max_y+1,1,k) = 0;s(m,max_y+1,2,k) = 0;s(m,max_y+1,3,k) = 0; end for n=min_y:max_y s(min_x,n,1,k) = 0;s(min_x,n,2,k) = 0;s(min_x,n,3,k) = 0; s(min_x-1,n,1,k) = 0;s(min_x-1,n,2,k) = 0;s(min_x-1,n,3,k) = 0; s(max_x,n,1,k) = 0;s(max_x,n,2,k) = 0;s(max_x,n,3,k) = 0; s(max_x+1,n,1,k) = 0;s(max_x+1,n,2,k) = 0;s(max_x+1,n,3,k) = 0; end % imshow(s(:,:,:,k)); % 播放视频(存在窗口大小的问题) % mov(k).cdata = s(:,:,:,k); % mov(k).colormap = []; % 保存每一帧图片 imwrite(s(:,:,:,k),strcat('D:\MATLAB\R2019a\bin\project\Output\video_frame',num2str(k),'.jpg')); end % 播放视频 % movie(mov); % 合成视频 writerObj = VideoWriter('Output.avi'); open(writerObj); for i=1:nFrames frame = imread(strcat('D:\MATLAB\R2019a\bin\project\Output\video_frame',num2str(i),'.jpg'));%从文件夹中读取图像 writeVideo(writerObj,frame); end close(writerObj);
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。